diff --git a/README.md b/README.md index 2d4ee16..5cca4d7 100644 --- a/README.md +++ b/README.md @@ -515,14 +515,13 @@ every path and the loaded config. ```bash knowledge mode [--json] ``` -Report which backend this process would use — `local` (the on-box store) or -`cloud` (the HTTP `/v1` API) — and which environment variable selected it. +Report which backend this process would use — `sqlite` (the on-box store) or +`postgres` (the HTTP `/v1` API) — and which environment variable selected it. -Selection is **explicit only**. Set `HASNA_KNOWLEDGE_STORAGE_MODE=local|cloud` +Selection is **explicit only**. Set `HASNA_KNOWLEDGE_STORAGE_MODE=sqlite|postgres` (aliases `HASNA_KNOWLEDGE_MODE`, `KNOWLEDGE_STORAGE_MODE`, `KNOWLEDGE_MODE`, in -that precedence order; `self_hosted` is accepted as a deprecated spelling of -`cloud`). Setting `HASNA_KNOWLEDGE_API_URL` / `HASNA_KNOWLEDGE_API_KEY` alone -does **not** switch backends — those are pointers saying where the cloud is and +that precedence order). Setting `HASNA_KNOWLEDGE_API_URL` / `HASNA_KNOWLEDGE_API_KEY` alone +does **not** switch backends — those are pointers saying where the API is and how to authenticate, and `mode` reports them as present-but-ignored so a machine that has them exported in its shell is not silently reading a different store than a machine that does not. @@ -731,8 +730,9 @@ the remote repo root or remote `.hasna/knowledge` path. `knowledge sync` owns knowledge semantics and conflict visibility for peer/machine catalog transfer. It is distinct from `db storage status`, which is a read-only local catalog inspector. (The legacy `db storage sync`/`push`/`pull` -Postgres-DSN commands were removed; cross-machine sharing uses cloud mode — -`HASNA_KNOWLEDGE_STORAGE_MODE=cloud` plus `HASNA_KNOWLEDGE_API_URL` + +Postgres-DSN commands were removed; cross-machine sharing uses the postgres +backend through the HTTP API — `HASNA_KNOWLEDGE_STORAGE_MODE=postgres` plus +`HASNA_KNOWLEDGE_API_URL` + `HASNA_KNOWLEDGE_API_KEY` — instead. The mode var is required: the two pointer vars on their own do not switch backends. See [`mode`](#mode).) @@ -768,8 +768,8 @@ Initialize or inspect the versioned SQLite catalog at durable table list, and local sync history. It is read-only. The legacy `push`/`pull`/`sync` Postgres commands and the client `HASNA_KNOWLEDGE_DATABASE_URL` DSN were removed — a raw database DSN is never distributed to clients. To share -knowledge across machines, use cloud mode instead: set -`HASNA_KNOWLEDGE_STORAGE_MODE=cloud` **and** `HASNA_KNOWLEDGE_API_URL` + +knowledge across machines, use the postgres HTTP API backend instead: set +`HASNA_KNOWLEDGE_STORAGE_MODE=postgres` **and** `HASNA_KNOWLEDGE_API_URL` + `HASNA_KNOWLEDGE_API_KEY` so every read/write routes through the HTTP API. The mode var is **not** optional and the pointer vars are **not** a substitute for it: presence of a URL and a key never switches backends on its own. Run diff --git a/bin/knowledge-mcp.js b/bin/knowledge-mcp.js index f77db8a..c52acb5 100755 --- a/bin/knowledge-mcp.js +++ b/bin/knowledge-mcp.js @@ -14993,7 +14993,7 @@ var init_mcp_http = () => {}; init_zod(); import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; -import { existsSync as existsSync15, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs"; +import { existsSync as existsSync15, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs"; // package.json var package_default = { name: "@hasna/knowledge", @@ -15098,7 +15098,7 @@ var package_default = { }, devDependencies: { "@electric-sql/pglite": "^0.5.4", - "@hasna/contracts": "0.5.2", + "@hasna/contracts": "0.8.5", "@types/bun": "^1.3.14", "@types/pg": "^8.15.6" } @@ -15287,18469 +15287,945 @@ function writeKnowledgeConfig(path, config2) { } // node_modules/@hasna/contracts/dist/client/storage.js -var __defProp2 = Object.defineProperty; -var __returnValue2 = (v) => v; -function __exportSetter2(name, newValue) { - this[name] = __returnValue2.bind(null, newValue); +import { isIP } from "net"; +import { readFileSync as readFileSync2, statSync } from "fs"; +import { join as join2 } from "path"; +function envToken(name) { + return name.toUpperCase().replace(/-/g, "_"); } -var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter2.bind(all, name) - }); -}; -var exports_external2 = {}; -__export2(exports_external2, { - void: () => voidType, - util: () => util, - unknown: () => unknownType, - union: () => unionType, - undefined: () => undefinedType, - tuple: () => tupleType, - transformer: () => effectsType, - symbol: () => symbolType, - string: () => stringType, - strictObject: () => strictObjectType, - setErrorMap: () => setErrorMap2, - set: () => setType, - record: () => recordType, - quotelessJson: () => quotelessJson, - promise: () => promiseType, - preprocess: () => preprocessType, - pipeline: () => pipelineType, - ostring: () => ostring, - optional: () => optionalType, - onumber: () => onumber, - oboolean: () => oboolean, - objectUtil: () => objectUtil, - object: () => objectType, - number: () => numberType, - nullable: () => nullableType, - null: () => nullType, - never: () => neverType, - nativeEnum: () => nativeEnumType, - nan: () => nanType, - map: () => mapType, - makeIssue: () => makeIssue, - literal: () => literalType, - lazy: () => lazyType, - late: () => late, - isValid: () => isValid, - isDirty: () => isDirty, - isAsync: () => isAsync, - isAborted: () => isAborted, - intersection: () => intersectionType, - instanceof: () => instanceOfType, - getParsedType: () => getParsedType2, - getErrorMap: () => getErrorMap2, - function: () => functionType, - enum: () => enumType, - effect: () => effectsType, - discriminatedUnion: () => discriminatedUnionType, - defaultErrorMap: () => en_default2, - datetimeRegex: () => datetimeRegex, - date: () => dateType, - custom: () => custom2, - coerce: () => coerce, - boolean: () => booleanType, - bigint: () => bigIntType, - array: () => arrayType, - any: () => anyType, - addIssueToContext: () => addIssueToContext, - ZodVoid: () => ZodVoid2, - ZodUnknown: () => ZodUnknown2, - ZodUnion: () => ZodUnion2, - ZodUndefined: () => ZodUndefined2, - ZodType: () => ZodType2, - ZodTuple: () => ZodTuple2, - ZodTransformer: () => ZodEffects, - ZodSymbol: () => ZodSymbol2, - ZodString: () => ZodString2, - ZodSet: () => ZodSet2, - ZodSchema: () => ZodType2, - ZodRecord: () => ZodRecord2, - ZodReadonly: () => ZodReadonly2, - ZodPromise: () => ZodPromise2, - ZodPipeline: () => ZodPipeline, - ZodParsedType: () => ZodParsedType, - ZodOptional: () => ZodOptional2, - ZodObject: () => ZodObject2, - ZodNumber: () => ZodNumber2, - ZodNullable: () => ZodNullable2, - ZodNull: () => ZodNull2, - ZodNever: () => ZodNever2, - ZodNativeEnum: () => ZodNativeEnum, - ZodNaN: () => ZodNaN2, - ZodMap: () => ZodMap2, - ZodLiteral: () => ZodLiteral2, - ZodLazy: () => ZodLazy2, - ZodIssueCode: () => ZodIssueCode2, - ZodIntersection: () => ZodIntersection2, - ZodFunction: () => ZodFunction2, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, - ZodError: () => ZodError2, - ZodEnum: () => ZodEnum2, - ZodEffects: () => ZodEffects, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, - ZodDefault: () => ZodDefault2, - ZodDate: () => ZodDate2, - ZodCatch: () => ZodCatch2, - ZodBranded: () => ZodBranded, - ZodBoolean: () => ZodBoolean2, - ZodBigInt: () => ZodBigInt2, - ZodArray: () => ZodArray2, - ZodAny: () => ZodAny2, - Schema: () => ZodType2, - ParseStatus: () => ParseStatus, - OK: () => OK, - NEVER: () => NEVER2, - INVALID: () => INVALID, - EMPTY_PATH: () => EMPTY_PATH, - DIRTY: () => DIRTY, - BRAND: () => BRAND -}); -var util; -(function(util2) { - util2.assertEqual = (_) => {}; - function assertIs2(_arg) {} - util2.assertIs = assertIs2; - function assertNever2(_x) { - throw new Error; - } - util2.assertNever = assertNever2; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { - const keys = []; - for (const key in object2) { - if (Object.prototype.hasOwnProperty.call(object2, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues2(array2, separator = " | ") { - return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util2.joinValues = joinValues2; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; +function normalizeStorageMode(value) { + const normalized = value.trim().toLowerCase().replace(/-/g, "_"); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); +} +function clientTransportEnvKeys(name) { + const envSegment = envToken(name); + return { + modeKeys: [ + `HASNA_${envSegment}_STORAGE_MODE`, + `HASNA_${envSegment}_MODE`, + `${envSegment}_STORAGE_MODE`, + `${envSegment}_MODE` + ], + apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], + apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; -var ZodIssueCode2 = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json2 = JSON.stringify(obj, null, 2); - return json2.replace(/"([^"]+)":/g, "$1:"); -}; +} +function credentialOverrideEnvKey(name) { + return `HASNA_${envToken(name)}_API_KEY_OVERRIDE`; +} +var CREDENTIAL_PROFILE_ENV_KEY = "HASNA_PROFILE"; -class ZodError2 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; +class CredentialResolutionError extends Error { + appName; + attempted; + constructor(appName, message, attempted) { + super(message); + this.name = "CredentialResolutionError"; + this.appName = appName; + this.attempted = attempted; + } +} +var HASNA_STATE_DIR = ".hasna"; +var FLEET_CREDENTIAL_DIR = "cloud"; +var CONFIG_DIR = ".config"; +var CONFIG_NAMESPACE = "hasna"; +var MAX_CREDENTIAL_FILE_BYTES = 64 * 1024; +var SAFE_APP_SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/; +var SAFE_PROFILE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/; +var ILLEGAL_IN_HEADER_VALUE = /[^\t\x20-\x7e]/; +function homeDir(env) { + const home = env.HOME?.trim(); + return home ? home : null; +} +function credentialDiskSources(name, env) { + return profileDiskSources(name, env, null); +} +function profileDiskSources(name, env, profile) { + const home = homeDir(env); + if (!home || !SAFE_APP_SLUG.test(name)) + return []; + const stem = profile ? `${name}.${profile}` : name; + const configStem = profile ? `${name}-${profile}` : name; + return [ + join2(home, HASNA_STATE_DIR, FLEET_CREDENTIAL_DIR, `${stem}.env`), + join2(home, CONFIG_DIR, CONFIG_NAMESPACE, `${configStem}-cloud.env`) + ]; +} +function parseEnvFile(text) { + const values = new Map; + for (const rawLine of text.split(/\r?\n/)) { + const line = rawLine.trim(); + if (line.length === 0 || line.startsWith("#")) + continue; + const withoutExport = line.startsWith("export ") ? line.slice("export ".length).trim() : line; + const equals = withoutExport.indexOf("="); + if (equals <= 0) + continue; + const key = withoutExport.slice(0, equals).trim(); + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) + continue; + let value = withoutExport.slice(equals + 1).trim(); + const quote = value[0]; + if (quote === '"' || quote === "'") { + if (value.length < 2 || !value.endsWith(quote)) + continue; + value = value.slice(1, -1); } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error51) => { - for (const issue2 of error51.issues) { - if (issue2.code === "invalid_union") { - issue2.unionErrors.map(processError); - } else if (issue2.code === "invalid_return_type") { - processError(issue2.returnTypeError); - } else if (issue2.code === "invalid_arguments") { - processError(issue2.argumentsError); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; + if (value.length === 0) + continue; + values.set(key, value); } - static assert(value) { - if (!(value instanceof ZodError2)) { - throw new Error(`Not a ZodError: ${value}`); - } + return values; +} +function readCredentialFile(path, apiKeyKeys) { + let text; + try { + const stats = statSync(path); + if (!stats.isFile() || stats.size > MAX_CREDENTIAL_FILE_BYTES) + return null; + text = readFileSync2(path, "utf8"); + } catch { + return null; } - toString() { - return this.message; + const values = parseEnvFile(text); + for (const key of apiKeyKeys) { + const value = values.get(key)?.trim(); + if (value) + return value; } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + return null; +} +function assertUsableCredential(appName, source, value) { + if (!ILLEGAL_IN_HEADER_VALUE.test(value)) + return; + throw new CredentialResolutionError(appName, `The credential from ${source} contains characters that cannot be sent in an HTTP header ` + `(a control character or non-ASCII byte). A file written with CR-only line endings is the usual ` + `cause. Rewrite that credential file with one LF-terminated KEY=value line. ` + `The value is not shown here, and is deliberately never logged.`, [source]); +} +var INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom"); +function sealCredential(fields) { + const { apiKey, ...visible } = fields; + const sealed = { ...visible }; + Object.defineProperty(sealed, "apiKey", { + value: apiKey, + enumerable: false, + writable: false, + configurable: false + }); + Object.defineProperty(sealed, INSPECT_CUSTOM, { + value: () => ({ ...visible, apiKey: "[redacted]" }), + enumerable: false, + writable: false, + configurable: false + }); + return sealed; +} +function explicitCredential(appName, apiKey) { + const source = "explicit apiKey option"; + assertUsableCredential(appName, source, apiKey); + return sealCredential({ + apiKey, + tier: "argument", + source, + deliberate: true, + deprecated: false, + diskCandidates: [], + warning: null + }); +} +function firstEnvValue(env, keys) { + for (const key of keys) { + const value = env[key]?.trim(); + if (value) + return { key, value }; } - get isEmpty() { - return this.issues.length === 0; + return null; +} +var DEPRECATION_REGISTRY = Symbol.for("hasna:contracts:credentialDeprecationNotices"); +function deprecationNotified() { + const host = globalThis; + const existing = host[DEPRECATION_REGISTRY]; + if (existing instanceof Set) + return existing; + const created = new Set; + host[DEPRECATION_REGISTRY] = created; + return created; +} +function defaultDeprecationSink(message) { + if (typeof process !== "undefined" && process.stderr) { + process.stderr.write(`${message} +`); } - flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); +} +function resolveCredential(name, env, options = {}) { + const { apiKeyKeys } = clientTransportEnvKeys(name); + const diskPaths = credentialDiskSources(name, env); + const explicitKey = options.apiKey?.trim(); + if (explicitKey) { + assertUsableCredential(name, "the explicit apiKey argument", explicitKey); + return sealCredential({ + apiKey: explicitKey, + tier: "argument", + source: "explicit apiKey argument", + deliberate: true, + deprecated: false, + diskCandidates: diskPaths, + warning: null + }); + } + const overrideKeyName = credentialOverrideEnvKey(name); + const overrideRaw = env[overrideKeyName]; + if (overrideRaw !== undefined) { + const override = overrideRaw.trim(); + if (!override) { + throw new CredentialResolutionError(name, `${overrideKeyName} is set but empty. It is a deliberate override, so it is not resolved around: ` + `either give it a real key or unset it to fall back to the credential on disk.`, [overrideKeyName]); + } + assertUsableCredential(name, overrideKeyName, override); + return sealCredential({ + apiKey: override, + tier: "override", + source: overrideKeyName, + deliberate: true, + deprecated: false, + diskCandidates: diskPaths, + warning: null + }); + } + const profile = options.profile?.trim() || env[CREDENTIAL_PROFILE_ENV_KEY]?.trim(); + if (profile) { + const profileSource = options.profile?.trim() ? "explicit profile argument" : CREDENTIAL_PROFILE_ENV_KEY; + if (!SAFE_PROFILE.test(profile)) { + throw new CredentialResolutionError(name, `Profile name from ${profileSource} is not usable in a path. ` + `Use letters, digits, dot, dash, or underscore.`, [profileSource]); + } + const paths = profileDiskSources(name, env, profile); + for (const path of paths) { + const value = readCredentialFile(path, apiKeyKeys); + if (value) { + assertUsableCredential(name, path, value); + return sealCredential({ + apiKey: value, + tier: "profile", + source: path, + deliberate: true, + deprecated: false, + diskCandidates: paths, + warning: null + }); } } - return { formErrors, fieldErrors }; + throw new CredentialResolutionError(name, `Profile '${profile}' (from ${profileSource}) has no ${apiKeyKeys[0]} for '${name}'. ` + `Looked in: ${paths.join(", ") || ""}. ` + `A profile names WHICH identity to use, so it is never resolved around \u2014 ` + `create the profile's credential file or unset ${CREDENTIAL_PROFILE_ENV_KEY}.`, paths); } - get formErrors() { - return this.flatten(); + const diskHits = diskPaths.map((path) => ({ path, value: readCredentialFile(path, apiKeyKeys) })).filter((hit) => hit.value !== null); + if (diskHits.length > 0) { + const winner = diskHits[0]; + assertUsableCredential(name, winner.path, winner.value); + const divergentSources = [ + ...diskHits.slice(1).filter((hit) => hit.value !== winner.value).map((hit) => hit.path), + ...(() => { + const legacyHit = firstEnvValue(env, apiKeyKeys); + return legacyHit && legacyHit.value !== winner.value ? [legacyHit.key] : []; + })() + ]; + const warning = divergentSources.length > 0 ? `Credential sources disagree for '${name}': ${winner.path} and ` + `${divergentSources.join(", ")} hold different keys. ${winner.path} wins, because a file on ` + `disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 ` + `a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.` : null; + return sealCredential({ + apiKey: winner.value, + tier: "disk", + source: winner.path, + deliberate: false, + deprecated: false, + diskCandidates: diskPaths, + warning + }); + } + const legacy = firstEnvValue(env, apiKeyKeys); + if (legacy) { + assertUsableCredential(name, legacy.key, legacy.value); + const where = diskPaths.length > 0 ? `Put the current key in ${diskPaths[0]} \u2014 it is re-read on every call, so rotations take effect immediately.` : `This environment has no HOME, so no credential file could be consulted at all; the disk tier is ` + `unavailable here and this process will keep using the environment snapshot.`; + const message = `[${name}] DEPRECATED: the API key came from ${legacy.key} in this process's environment. ` + `Environment variables are a snapshot taken when this process started, so a shell that started ` + `before a key rotation keeps using the old key until it exits. ${where}`; + const sink = options.onDeprecation ?? defaultDeprecationSink; + const notified = deprecationNotified(); + if (!notified.has(name)) { + notified.add(name); + sink(message); + } + return sealCredential({ + apiKey: legacy.value, + tier: "legacy-env", + source: legacy.key, + deliberate: false, + deprecated: true, + diskCandidates: diskPaths, + warning: message + }); } + return null; } -ZodError2.create = (issues) => { - const error51 = new ZodError2(issues); - return error51; -}; -var errorMap = (issue2, _ctx) => { - let message; - switch (issue2.code) { - case ZodIssueCode2.invalid_type: - if (issue2.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue2.expected}, received ${issue2.received}`; - } - break; - case ZodIssueCode2.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode2.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; - break; - case ZodIssueCode2.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; - break; - case ZodIssueCode2.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; - break; - case ZodIssueCode2.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode2.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode2.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode2.invalid_string: - if (typeof issue2.validation === "object") { - if ("includes" in issue2.validation) { - message = `Invalid input: must include "${issue2.validation.includes}"`; - if (typeof issue2.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; - } - } else if ("startsWith" in issue2.validation) { - message = `Invalid input: must start with "${issue2.validation.startsWith}"`; - } else if ("endsWith" in issue2.validation) { - message = `Invalid input: must end with "${issue2.validation.endsWith}"`; - } else { - util.assertNever(issue2.validation); - } - } else if (issue2.validation !== "regex") { - message = `Invalid ${issue2.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode2.too_small: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "bigint") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.too_big: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "bigint") - message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.custom: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode2.not_multiple_of: - message = `Number must be a multiple of ${issue2.multipleOf}`; - break; - case ZodIssueCode2.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue2); +var FLEET_API_DOMAIN_ENV_KEY = "HASNA_FLEET_API_DOMAIN"; +var NEUTRAL_FLEET_API_DOMAIN = "your-deployment.example"; +var ASCII_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/; +var DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/; +function isValidDnsDomain(value) { + if (value.length === 0 || value.length > 253 || ASCII_CONTROL_PATTERN.test(value) || /[^\x00-\x7f]/.test(value)) { + return false; } - return { message }; -}; -var en_default2 = errorMap; -var overrideErrorMap = en_default2; -function setErrorMap2(map2) { - overrideErrorMap = map2; -} -function getErrorMap2() { - return overrideErrorMap; -} -var makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { + return value.split(".").every((label) => label.length <= 63 && !label.startsWith("xn--") && DNS_LABEL_PATTERN.test(label)); +} +function resolveFleetApiDomain(env) { + const raw = env[FLEET_API_DOMAIN_ENV_KEY]; + if (raw === undefined) { return { - ...issueData, - path: fullPath, - message: issueData.message + domain: NEUTRAL_FLEET_API_DOMAIN, + source: "default", + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} is not set; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` }; } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map2 of maps) { - errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; + const configured = raw.trim().toLowerCase(); + if (ASCII_CONTROL_PATTERN.test(raw) || !isValidDnsDomain(configured)) { + return { + domain: NEUTRAL_FLEET_API_DOMAIN, + source: FLEET_API_DOMAIN_ENV_KEY, + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} is blank or invalid; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` + }; } return { - ...issueData, - path: fullPath, - message: errorMessage + domain: configured, + source: FLEET_API_DOMAIN_ENV_KEY, + misconfigured: false, + warning: null }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap2(); - const issue2 = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default2 ? undefined : en_default2 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue2); } - -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; +function validateAppSlug(name) { + if (name.length > 63 || !DNS_LABEL_PATTERN.test(name)) { + throw new Error("App name must be one lowercase DNS label."); } + return name; } -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x) => x.status === "aborted"; -var isDirty = (x) => x.status === "dirty"; -var isValid = (x) => x.status === "valid"; -var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; +function composeCloudHostname(name, domain2) { + const hostname3 = `${validateAppSlug(name)}.${domain2}`; + if (!isValidDnsDomain(hostname3)) { + throw new Error("Composed cloud hostname must be a valid DNS domain"); } + return hostname3; } -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } +function resolveDefaultCloudBaseUrl(name, env) { + const appSlug = validateAppSlug(name); + const fleetDomain = resolveFleetApiDomain(env); + const configuredHostname = `${appSlug}.${fleetDomain.domain}`; + if (isValidDnsDomain(configuredHostname)) { return { - success: false, - get error() { - if (this._error) - return this._error; - const error51 = new ZodError2(ctx.common.issues); - this._error = error51; - return this._error; - } + baseUrl: `https://${configuredHostname}`, + source: fleetDomain.source, + misconfigured: fleetDomain.misconfigured, + warning: fleetDomain.warning }; } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; + const fallbackHostname = composeCloudHostname(appSlug, NEUTRAL_FLEET_API_DOMAIN); + return { + baseUrl: `https://${fallbackHostname}`, + source: fleetDomain.source, + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} cannot form a valid composed cloud hostname for app '${appSlug}'; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` }; - return { errorMap: customMap, description }; } - -class ZodType2 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType2(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; +function firstEnv2(env, keys, options = {}) { + for (const key of keys) { + const raw = env[key]; + const value = raw?.trim(); + if (value) + return { key, value: options.preserveRaw ? raw : value }; } - _processInputParams(input) { - return { - status: new ParseStatus, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; + return null; +} +function rawAuthority(value) { + const match = /^[a-z][a-z0-9+.-]*:\/\//i.exec(value); + if (!match) + throw new Error("API URL must be absolute."); + const afterScheme = value.slice(match[0].length); + const boundary = afterScheme.search(/[/?#]/); + const authority = boundary === -1 ? afterScheme : afterScheme.slice(0, boundary); + if (!authority) + throw new Error("API URL must include a hostname."); + return authority; +} +function assertCanonicalPort(port) { + if (!/^[0-9]+$/.test(port) || port.length > 1 && port.startsWith("0")) { + throw new Error("API URL authority must contain a canonical port between 1 and 65535."); } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; + const numericPort = Number(port); + if (!Number.isSafeInteger(numericPort) || numericPort < 1 || numericPort > 65535) { + throw new Error("API URL authority must contain a canonical port between 1 and 65535."); } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } +} +function canonicalAuthorityHostname(authority) { + let rawHostname; + if (authority.startsWith("[")) { + const closingBracket = authority.indexOf("]"); + if (closingBracket === -1) { + throw new Error("API URL authority must contain a canonical hostname."); } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check2, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check2(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode2.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; + rawHostname = authority.slice(0, closingBracket + 1); + const portSuffix = authority.slice(closingBracket + 1); + if (portSuffix) { + if (!portSuffix.startsWith(":")) { + throw new Error("API URL authority must contain a canonical hostname and port."); } - }); - } - refinement(check2, refinementData) { - return this._refinement((val, ctx) => { - if (!check2(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "refinement", refinement } - }); + assertCanonicalPort(portSuffix.slice(1)); + } + if (isIP(rawHostname.slice(1, -1)) !== 6) { + throw new Error("API URL authority must contain a canonical IPv6 literal."); + } + } else { + const firstColon = authority.indexOf(":"); + const lastColon = authority.lastIndexOf(":"); + if (firstColon !== lastColon) { + throw new Error("IPv6 API URL authorities must use brackets."); + } + if (lastColon !== -1) { + const port = authority.slice(lastColon + 1); + assertCanonicalPort(port); + rawHostname = authority.slice(0, lastColon); + } else { + rawHostname = authority; + } + const ipVersion = isIP(rawHostname); + const numericAddressParts = rawHostname.split("."); + const looksLikeNonCanonicalIpv4 = numericAddressParts.every((part) => /^(?:0x[0-9a-f]+|[0-9]+)$/i.test(part)); + if (ipVersion !== 4 && looksLikeNonCanonicalIpv4 || ipVersion !== 4 && !isValidDnsDomain(rawHostname.toLowerCase())) { + throw new Error("API URL authority must contain a canonical ASCII hostname."); + } } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; + return rawHostname.toLowerCase(); +} +function isDeliberateLoopbackHttpAuthority(authority) { + return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(authority); +} +function toV1BaseUrl(apiUrl) { + if (ASCII_CONTROL_PATTERN.test(apiUrl)) { + throw new Error("API URL must not contain ASCII control characters."); } - optional() { - return ZodOptional2.create(this, this._def); + const input = apiUrl.trim(); + const authority = rawAuthority(input); + if (authority.includes("@") || authority.includes("\\") || authority.includes("%") || /[^\x00-\x7f]/.test(authority)) { + throw new Error("API URL authority must be canonical ASCII without credentials."); } - nullable() { - return ZodNullable2.create(this, this._def); + const canonicalHostname = canonicalAuthorityHostname(authority); + const url2 = new URL(input); + if (url2.protocol !== "http:" && url2.protocol !== "https:") { + throw new Error("API URL must use http or https."); } - nullish() { - return this.nullable().optional(); + if (url2.username || url2.password) { + throw new Error("API URL must not include credentials."); } - array() { - return ZodArray2.create(this); + if (!url2.hostname || url2.hostname.endsWith(".")) { + throw new Error("API URL must include a canonical hostname."); } - promise() { - return ZodPromise2.create(this, this._def); + if (url2.hostname.toLowerCase() !== canonicalHostname) { + throw new Error("API URL authority must not rely on parser hostname normalization."); } - or(option) { - return ZodUnion2.create([this, option], this._def); + if (url2.hostname.split(".").some((label) => label.toLowerCase().startsWith("xn--"))) { + throw new Error("API URL must not use IDN or punycode hostnames."); } - and(incoming) { - return ZodIntersection2.create(this, incoming, this._def); + if (url2.protocol === "http:" && !isDeliberateLoopbackHttpAuthority(authority)) { + throw new Error("API URL may use http only for an exact loopback authority."); } - transform(transform2) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "transform", transform: transform2 } - }); + if (url2.search || url2.hash) { + throw new Error("API URL must not include a query string or fragment."); } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault2({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind2.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch2({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly2.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?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)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?: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])$/; -var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\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])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); + let path = url2.pathname.replace(/\/+$/, ""); + if (path.endsWith("/v1")) + path = path.slice(0, -"/v1".length); + url2.pathname = `${path}/v1`; + return url2.toString().replace(/\/+$/, ""); } -function isValidIP(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { - return true; +function resolveClientTransport(name, env = process.env, options = {}) { + const keys = clientTransportEnvKeys(name); + const modeHit = firstEnv2(env, keys.modeKeys); + const urlHit = firstEnv2(env, keys.apiUrlKeys, { preserveRaw: true }); + const keyHit = firstEnv2(env, keys.apiKeyKeys); + let mode = "sqlite"; + let modeSource = "default"; + const warnings = []; + let credential; + if (modeHit) { + mode = normalizeStorageMode(modeHit.value).mode; + modeSource = modeHit.key; + } else if (urlHit) { + credential = resolveCredential(name, env, options.credentials); + if (credential) { + mode = "postgres"; + modeSource = `${urlHit.key}+${credential.source}`; + } } - if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { - return true; + if (mode === "sqlite") { + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: Boolean(keyHit), + apiKeySource: keyHit ? keyHit.key : null, + apiKeyTier: null, + misconfigured: false, + warning: warnings.length > 0 ? warnings.join(" ") : null + }; } - return false; -} -function isValidJWT2(jwt2, alg) { - if (!jwtRegex.test(jwt2)) - return false; + if (credential === undefined) + credential = resolveCredential(name, env, options.credentials); + if (!credential) { + const diskHint = credentialDiskSourcesForMessage(name, env); + warnings.push(`${modeSource}=postgres but no API key could be resolved for '${name}'. A client reaches server data ` + `over HTTP only; refusing to route. Using the local sqlite store. ` + `Looked for a credential file at ${diskHint}, then for ${keys.apiKeyKeys[0]} in the environment.`); + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: false, + apiKeySource: null, + apiKeyTier: null, + misconfigured: true, + warning: warnings.join(" ") + }; + } + if (credential.warning) + warnings.push(credential.warning); + let defaultBaseUrl = null; + let apiUrlSource = urlHit?.key ?? (env[FLEET_API_DOMAIN_ENV_KEY] === undefined ? "default" : FLEET_API_DOMAIN_ENV_KEY); + let baseUrl; try { - const [header] = jwt2.split("."); - if (!header) - return false; - const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base643)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; + if (!urlHit) { + defaultBaseUrl = resolveDefaultCloudBaseUrl(name, env); + apiUrlSource = defaultBaseUrl.source; + } + const rawUrl = urlHit?.value ?? defaultBaseUrl.baseUrl; + baseUrl = toV1BaseUrl(rawUrl); + } catch (error51) { + const message = error51 instanceof Error ? error51.message : String(error51); + warnings.push(`Invalid API URL from ${apiUrlSource}: ${message}. Using local store.`); + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: true, + apiKeySource: credential.source, + apiKeyTier: credential.tier, + misconfigured: true, + warning: warnings.join(" ") + }; } + if (defaultBaseUrl?.warning) + warnings.push(defaultBaseUrl.warning); + return { + transport: "http", + mode, + modeSource, + baseUrl, + apiUrlSource, + apiKeyPresent: true, + apiKeySource: credential.source, + apiKeyTier: credential.tier, + misconfigured: defaultBaseUrl?.misconfigured ?? false, + warning: warnings.length > 0 ? warnings.join(" ") : null + }; } -function isValidCidr(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; +function credentialDiskSourcesForMessage(name, env) { + const paths = credentialDiskSources(name, env); + return paths.length > 0 ? paths.join(" or ") : ""; } -class ZodString2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.length < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.length > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "length") { - const tooBig = input.data.length > check2.value; - const tooSmall = input.data.length < check2.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } - status.dirty(); - } - } else if (check2.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "regex") { - check2.regex.lastIndex = 0; - const testResult = check2.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "trim") { - input.data = input.data.trim(); - } else if (check2.kind === "includes") { - if (!input.data.includes(check2.value, check2.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { includes: check2.value, position: check2.position }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check2.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check2.kind === "startsWith") { - if (!input.data.startsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { startsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "endsWith") { - if (!input.data.endsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { endsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "datetime") { - const regex = datetimeRegex(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "datetime", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "date", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "time") { - const regex = timeRegex(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "time", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ip") { - if (!isValidIP(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "jwt") { - if (!isValidJWT2(input.data, check2.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cidr") { - if (!isValidCidr(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode2.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check2) { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); +class HasnaHttpError extends Error { + status; + method; + path; + body; + credentialSource; + credentialTier; + constructor(method, path, status, body, credential) { + const guidance = credential ? `. ${credential.guidance}` : ""; + super(`Hasna cloud request failed: ${method} ${path} -> ${status}${guidance}`); + this.name = "HasnaHttpError"; + this.status = status; + this.method = method; + this.path = path; + this.body = body; + this.credentialSource = credential?.source ?? null; + this.credentialTier = credential?.tier ?? null; } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); +} +function currentCredential(name, apiKey) { + if (typeof apiKey === "function") + return apiKey(); + return explicitCredential(name, apiKey); +} +function authFailureGuidance(credential) { + const origin = `The API key for this request came from ${credential.source}`; + if (credential.deliberate) { + return `${origin} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: ` + `falling back here would authenticate as a different principal than the one you named, which is ` + `exactly the failure an override exists to prevent. Rotate that key, or unset the override to use ` + `the credential on disk.`; } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); + if (credential.deprecated) { + const target = credential.diskCandidates[0]; + const remedy = target ? `Write the CURRENT key to ${target} \u2014 that file is re-read on every call, so rotations take ` + `effect immediately and in every shell. Do not simply unset ${credential.source}: nothing was ` + `found on disk, so that would leave this client with no credential at all.` : `This environment has no HOME, so no credential file could be consulted; the disk tier is ` + `unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.`; + return `${origin}, a variable in this process's environment \u2014 which is a snapshot taken when the process ` + `started. A STALE SHELL is the most common cause of this error: this shell exported the key before ` + `it was rotated, and will keep sending the old one until it exits. ${remedy}`; } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; + return `${origin}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. ` + `The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution ` + `so this machine gets the current key.`; +} +var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504]; +var IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); +var AUTHORITY_OVERRIDE_HEADERS = new Set([ + "host", + ":authority", + "forwarded", + "x-forwarded-host", + "x-original-host" +]); +function assertNoAuthorityOverrideHeaders(headers, source) { + if (!headers) + return; + const forbidden = Object.keys(headers).find((name) => AUTHORITY_OVERRIDE_HEADERS.has(name.trim().toLowerCase())); + if (forbidden) { + throw new Error(`Authenticated ${source} headers must not set authority header '${forbidden}'.`); } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; +} +function appendQuery(path, query) { + if (!query) + return path; + const params = query instanceof URLSearchParams ? query : new URLSearchParams; + if (!(query instanceof URLSearchParams)) { + for (const [key, value] of Object.entries(query)) { + if (value === null || value === undefined) + continue; + if (Array.isArray(value)) { + for (const v of value) + params.append(key, String(v)); + } else { + params.append(key, String(value)); } } - return max; } + const qs = params.toString(); + if (!qs) + return path; + return `${path}${path.includes("?") ? "&" : "?"}${qs}`; } -ZodString2.create = (params) => { - return new ZodString2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder2(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} - -class ZodNumber2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = undefined; - const status = new ParseStatus; - for (const check2 of this._def.checks) { - if (check2.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: "integer", - received: "float", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (floatSafeRemainder2(input.data, check2.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.not_finite, - message: check2.message - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodNumber2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber2.create = (params) => { - return new ZodNumber2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; - -class ZodBigInt2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - type: "bigint", - minimum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - type: "bigint", - maximum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (input.data % check2.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodBigInt2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt2.create = (params) => { - return new ZodBigInt2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; - -class ZodBoolean2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodBoolean2.create = (params) => { - return new ZodBoolean2({ - typeName: ZodFirstPartyTypeKind2.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; - -class ZodDate2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_date - }); - return INVALID; - } - const status = new ParseStatus; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.getTime() < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - message: check2.message, - inclusive: true, - exact: false, - minimum: check2.value, - type: "date" - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.getTime() > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - message: check2.message, - inclusive: true, - exact: false, - maximum: check2.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check2) { - return new ZodDate2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate2.create = (params) => { - return new ZodDate2({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind2.ZodDate, - ...processCreateParams(params) - }); -}; - -class ZodSymbol2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodSymbol2.create = (params) => { - return new ZodSymbol2({ - typeName: ZodFirstPartyTypeKind2.ZodSymbol, - ...processCreateParams(params) - }); -}; - -class ZodUndefined2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodUndefined2.create = (params) => { - return new ZodUndefined2({ - typeName: ZodFirstPartyTypeKind2.ZodUndefined, - ...processCreateParams(params) - }); -}; - -class ZodNull2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodNull2.create = (params) => { - return new ZodNull2({ - typeName: ZodFirstPartyTypeKind2.ZodNull, - ...processCreateParams(params) - }); -}; - -class ZodAny2 extends ZodType2 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodAny2.create = (params) => { - return new ZodAny2({ - typeName: ZodFirstPartyTypeKind2.ZodAny, - ...processCreateParams(params) - }); -}; - -class ZodUnknown2 extends ZodType2 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodUnknown2.create = (params) => { - return new ZodUnknown2({ - typeName: ZodFirstPartyTypeKind2.ZodUnknown, - ...processCreateParams(params) - }); -}; - -class ZodNever2 extends ZodType2 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -} -ZodNever2.create = (params) => { - return new ZodNever2({ - typeName: ZodFirstPartyTypeKind2.ZodNever, - ...processCreateParams(params) - }); -}; - -class ZodVoid2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodVoid2.create = (params) => { - return new ZodVoid2({ - typeName: ZodFirstPartyTypeKind2.ZodVoid, - ...processCreateParams(params) - }); -}; - -class ZodArray2 extends ZodType2 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray2({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray2({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new ZodArray2({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray2.create = (schema, params) => { - return new ZodArray2({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind2.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject2) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema)); - } - return new ZodObject2({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray2) { - return new ZodArray2({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional2) { - return ZodOptional2.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable2) { - return ZodNullable2.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple2) { - return ZodTuple2.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} - -class ZodObject2 extends ZodType2 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever2) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode2.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject2({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue2, ctx) => { - const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; - if (issue2.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject2({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject2({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject2({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject2({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind2.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject2({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject2({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional2) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject2({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -} -ZodObject2.create = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject2.strictCreate = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject2.lazycreate = (shape, params) => { - return new ZodObject2({ - shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams(params) - }); -}; - -class ZodUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError2(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -} -ZodUnion2.create = (types, params) => { - return new ZodUnion2({ - options: types, - typeName: ZodFirstPartyTypeKind2.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy2) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral2) { - return [type.value]; - } else if (type instanceof ZodEnum2) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault2) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined2) { - return [undefined]; - } else if (type instanceof ZodNull2) { - return [null]; - } else if (type instanceof ZodOptional2) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable2) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly2) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch2) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion2({ - typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -} -function mergeValues2(a, b) { - const aType = getParsedType2(a); - const bType = getParsedType2(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues2(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues2(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues2(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection2.create = (left, right, params) => { - return new ZodIntersection2({ - left, - right, - typeName: ZodFirstPartyTypeKind2.ZodIntersection, - ...processCreateParams(params) - }); -}; - -class ZodTuple2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple2({ - ...this._def, - rest - }); - } -} -ZodTuple2.create = (schemas3, params) => { - if (!Array.isArray(schemas3)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple2({ - items: schemas3, - typeName: ZodFirstPartyTypeKind2.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; - -class ZodRecord2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType2) { - return new ZodRecord2({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams(third) - }); - } - return new ZodRecord2({ - keyType: ZodString2.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams(second) - }); - } -} - -class ZodMap2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap2.create = (keyType, valueType, params) => { - return new ZodMap2({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind2.ZodMap, - ...processCreateParams(params) - }); -}; - -class ZodSet2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet2({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet2({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet2.create = (valueType, params) => { - return new ZodSet2({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind2.ZodSet, - ...processCreateParams(params) - }); -}; - -class ZodFunction2 extends ZodType2 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error51) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_arguments, - argumentsError: error51 - } - }); - } - function makeReturnsIssue(returns, error51) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_return_type, - returnTypeError: error51 - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise2) { - const me = this; - return OK(async function(...args) { - const error51 = new ZodError2([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error51.addIssue(makeArgsIssue(args, e)); - throw error51; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error51.addIssue(makeReturnsIssue(result, e)); - throw error51; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction2({ - ...this._def, - args: ZodTuple2.create(items).rest(ZodUnknown2.create()) - }); - } - returns(returnType) { - return new ZodFunction2({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction2({ - args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), - returns: returns || ZodUnknown2.create(), - typeName: ZodFirstPartyTypeKind2.ZodFunction, - ...processCreateParams(params) - }); - } -} - -class ZodLazy2 extends ZodType2 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy2.create = (getter, params) => { - return new ZodLazy2({ - getter, - typeName: ZodFirstPartyTypeKind2.ZodLazy, - ...processCreateParams(params) - }); -}; - -class ZodLiteral2 extends ZodType2 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral2.create = (value, params) => { - return new ZodLiteral2({ - value, - typeName: ZodFirstPartyTypeKind2.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum2({ - values, - typeName: ZodFirstPartyTypeKind2.ZodEnum, - ...processCreateParams(params) - }); -} - -class ZodEnum2 extends ZodType2 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum2.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum2.create = createZodEnum; - -class ZodNativeEnum extends ZodType2 { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, - ...processCreateParams(params) - }); -}; - -class ZodPromise2 extends ZodType2 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise2.create = (schema, params) => { - return new ZodPromise2({ - type: schema, - typeName: ZodFirstPartyTypeKind2.ZodPromise, - ...processCreateParams(params) - }); -}; - -class ZodEffects extends ZodType2 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util.assertNever(effect); - } -} -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess2 }, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - ...processCreateParams(params) - }); -}; - -class ZodOptional2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional2.create = (type, params) => { - return new ZodOptional2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodOptional, - ...processCreateParams(params) - }); -}; - -class ZodNullable2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable2.create = (type, params) => { - return new ZodNullable2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodNullable, - ...processCreateParams(params) - }); -}; - -class ZodDefault2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault2.create = (type, params) => { - return new ZodDefault2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; - -class ZodCatch2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch2.create = (type, params) => { - return new ZodCatch2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; - -class ZodNaN2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN2.create = (params) => { - return new ZodNaN2({ - typeName: ZodFirstPartyTypeKind2.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = Symbol("zod_brand"); - -class ZodBranded extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind2.ZodPipeline - }); - } -} - -class ZodReadonly2 extends ZodType2 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly2.create = (type, params) => { - return new ZodReadonly2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom2(check2, _params = {}, fatal) { - if (check2) - return ZodAny2.create().superRefine((data, ctx) => { - const r = check2(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny2.create(); -} -var late = { - object: ZodObject2.lazycreate -}; -var ZodFirstPartyTypeKind2; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom2((data) => data instanceof cls, params); -var stringType = ZodString2.create; -var numberType = ZodNumber2.create; -var nanType = ZodNaN2.create; -var bigIntType = ZodBigInt2.create; -var booleanType = ZodBoolean2.create; -var dateType = ZodDate2.create; -var symbolType = ZodSymbol2.create; -var undefinedType = ZodUndefined2.create; -var nullType = ZodNull2.create; -var anyType = ZodAny2.create; -var unknownType = ZodUnknown2.create; -var neverType = ZodNever2.create; -var voidType = ZodVoid2.create; -var arrayType = ZodArray2.create; -var objectType = ZodObject2.create; -var strictObjectType = ZodObject2.strictCreate; -var unionType = ZodUnion2.create; -var discriminatedUnionType = ZodDiscriminatedUnion2.create; -var intersectionType = ZodIntersection2.create; -var tupleType = ZodTuple2.create; -var recordType = ZodRecord2.create; -var mapType = ZodMap2.create; -var setType = ZodSet2.create; -var functionType = ZodFunction2.create; -var lazyType = ZodLazy2.create; -var literalType = ZodLiteral2.create; -var enumType = ZodEnum2.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise2.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional2.create; -var nullableType = ZodNullable2.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: (arg) => ZodString2.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber2.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean2.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt2.create({ ...arg, coerce: true }), - date: (arg) => ZodDate2.create({ ...arg, coerce: true }) -}; -var NEVER2 = INVALID; -var SCHEMA_IDS = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema = exports_external2.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema = exports_external2.string().datetime(); -var NonEmptyStringSchema = exports_external2.string().trim().min(1); -var UriSchema = NonEmptyStringSchema.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema = exports_external2.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema = exports_external2.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema = exports_external2.record(exports_external2.unknown()); -var TagsSchema = exports_external2.array(exports_external2.string().min(1)).default([]); -var OptionalTimestampSchema = TimestampSchema.nullable().optional(); -var TerminalStatuses = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema = exports_external2.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema(schema) { - return exports_external2.object({ - schema: exports_external2.literal(schema), - id: exports_external2.string().min(1), - createdAt: TimestampSchema, - updatedAt: OptionalTimestampSchema, - metadata: MetadataSchema.optional() - }).strict(); -} -var ContractEnvelopeSchema = exports_external2.object({ - schema: SchemaIdSchema, - id: exports_external2.string().min(1), - createdAt: TimestampSchema, - updatedAt: OptionalTimestampSchema, - metadata: MetadataSchema.optional() -}).strict(); -var ActorKindSchema = exports_external2.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema = contractBaseSchema(SCHEMA_IDS.actorRef).extend({ - kind: ActorKindSchema, - name: exports_external2.string().min(1).optional(), - provider: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - machineId: exports_external2.string().min(1).optional(), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema = exports_external2.object({ - kind: ActorKindSchema, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - provider: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - machineId: exports_external2.string().min(1).optional() -}).strict(); -var ResourceKindSchema = exports_external2.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema = contractBaseSchema(SCHEMA_IDS.resourceRef).extend({ - kind: ResourceKindSchema, - name: exports_external2.string().min(1).optional(), - uri: UriSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema = exports_external2.object({ - kind: ResourceKindSchema, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - uri: UriSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema = exports_external2.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema = exports_external2.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema = contractBaseSchema(SCHEMA_IDS.evidenceRef).extend({ - kind: EvidenceKindSchema, - uri: UriSchema, - sha256: Sha256DigestSchema.optional(), - summary: exports_external2.string().min(1).optional(), - contentType: exports_external2.string().min(1).optional(), - sizeBytes: exports_external2.number().int().nonnegative().optional(), - redaction: RedactionStateSchema.default("unknown"), - producer: ActorPointerSchema.optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - tags: TagsSchema -}).strict(); -var EvidencePointerSchema = exports_external2.object({ - id: exports_external2.string().min(1), - kind: EvidenceKindSchema.optional(), - uri: UriSchema.optional(), - sha256: Sha256DigestSchema.optional(), - summary: exports_external2.string().min(1).optional() -}).strict(); -var CostEstimateSchema = contractBaseSchema(SCHEMA_IDS.costEstimate).extend({ - currency: exports_external2.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external2.number().int().nonnegative(), - provider: exports_external2.string().min(1).optional(), - model: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - promptTokens: exports_external2.number().int().nonnegative().optional(), - completionTokens: exports_external2.number().int().nonnegative().optional(), - totalTokens: exports_external2.number().int().nonnegative().optional(), - basis: exports_external2.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema = exports_external2.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.decisionEnvelope).extend({ - decisionType: exports_external2.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema, - actor: ActorPointerSchema.optional(), - traceId: exports_external2.string().min(1).optional(), - inputHash: HashStringSchema.optional(), - policyBundleId: exports_external2.string().min(1).optional(), - selected: exports_external2.array(ResourcePointerSchema).default([]), - skipped: exports_external2.array(ResourcePointerSchema).default([]), - reason: exports_external2.string().min(1), - obligations: exports_external2.array(exports_external2.string().min(1)).default([]), - redactions: exports_external2.array(exports_external2.string().min(1)).default([]), - costEstimate: CostEstimateSchema.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema = contractBaseSchema(SCHEMA_IDS.capabilityCard).extend({ - kind: exports_external2.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external2.string().min(1), - version: exports_external2.string().min(1).optional(), - status: exports_external2.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), - limitations: exports_external2.array(exports_external2.string().min(1)).default([]), - riskLevel: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict(); -var ProviderModeSchema = exports_external2.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema = exports_external2.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema = exports_external2.object({ - refName: NonEmptyStringSchema, - requiredForModes: exports_external2.array(ProviderModeSchema).min(1), - allowedSecretInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema, - revocationCheck: exports_external2.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema = exports_external2.object({ - operation: NonEmptyStringSchema, - supportedModes: exports_external2.array(ProviderModeSchema).min(1), - sideEffectClass: ProviderSideEffectClassSchema, - requiresApproval: exports_external2.boolean().default(false), - requiresIdempotencyKey: exports_external2.boolean().default(false), - requiresSandboxEvidence: exports_external2.boolean().default(false), - requiresRollbackOrRevocation: exports_external2.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema.optional(), - noSideEffectSmoke: NonEmptyStringSchema.optional(), - reconciliation: NonEmptyStringSchema.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema = exports_external2.object({ - providerId: NonEmptyStringSchema, - appId: NonEmptyStringSchema, - adapterId: NonEmptyStringSchema, - ownerPackage: NonEmptyStringSchema, - modes: exports_external2.array(ProviderModeSchema).min(1), - defaultMode: ProviderModeSchema, - credentialRequirements: exports_external2.array(CredentialRequirementSchema).default([]), - operations: exports_external2.array(ProviderOperationCardSchema).min(1), - rateLimitPosture: NonEmptyStringSchema, - costPosture: NonEmptyStringSchema.optional(), - auditEvents: exports_external2.array(NonEmptyStringSchema).default([]), - redactionRules: exports_external2.array(NonEmptyStringSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema = exports_external2.object({ - appId: NonEmptyStringSchema, - repo: NonEmptyStringSchema, - priority: exports_external2.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external2.array(NonEmptyStringSchema).min(1), - firstOperations: exports_external2.array(NonEmptyStringSchema).min(1), - blockedUntil: exports_external2.array(NonEmptyStringSchema).default([]) -}).strict(); -var ProviderLiveModeStandardSchema = contractBaseSchema(SCHEMA_IDS.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema, - version: NonEmptyStringSchema, - modes: exports_external2.array(ProviderModeSchema).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external2.array(NonEmptyStringSchema).min(1), - liveMutationGate: exports_external2.object({ - requiredMode: exports_external2.literal("live_mutating"), - requiredChecks: exports_external2.array(NonEmptyStringSchema).min(1), - forbiddenBypassSignals: exports_external2.array(NonEmptyStringSchema).min(1), - disabledLiveSmoke: NonEmptyStringSchema - }).strict(), - noSideEffectSmoke: exports_external2.object({ - requiredForModes: exports_external2.array(ProviderModeSchema).min(1), - commandEvidence: exports_external2.array(NonEmptyStringSchema).min(1), - secretOutputScan: exports_external2.boolean().default(true) - }).strict(), - credentialPolicy: exports_external2.object({ - acceptedInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external2.literal(false), - missingCredentialBehavior: exports_external2.literal("fail_closed"), - revocationCheckRequired: exports_external2.boolean().default(true) - }).strict(), - operationCards: exports_external2.array(ProviderCapabilityCardSchema).min(1), - firstAdoptionTargets: exports_external2.array(ProviderLiveModeTargetSchema).min(1), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1).optional(), - summary: exports_external2.string().min(1), - text: exports_external2.string().optional(), - tokens: exports_external2.number().int().nonnegative().optional(), - source: EvidencePointerSchema, - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) -}).strict(); -var ContextPackSchema = contractBaseSchema(SCHEMA_IDS.contextPack).extend({ - objective: exports_external2.string().min(1), - budget: exports_external2.object({ - maxTokens: exports_external2.number().int().positive().optional(), - maxBytes: exports_external2.number().int().positive().optional() - }).strict().optional(), - items: exports_external2.array(ContextPackItemSchema).default([]), - citations: exports_external2.array(EvidencePointerSchema).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external2.array(exports_external2.string().min(1)).default([]), - redactions: exports_external2.array(exports_external2.string().min(1)).default([]), - conflicts: exports_external2.array(exports_external2.string().min(1)).default([]), - uncertainty: exports_external2.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema = NonEmptyStringSchema.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema = exports_external2.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema = exports_external2.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema = exports_external2.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema = contractBaseSchema(SCHEMA_IDS.integrationRef).extend({ - kind: ProjectIntegrationKindSchema, - name: exports_external2.string().min(1), - projectId: ProjectSlugSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - uri: UriSchema.optional(), - enabled: exports_external2.boolean().default(true), - readOnly: exports_external2.boolean().default(true), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - config: MetadataSchema.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema = exports_external2.object({ - schemaRoot: RelativeProjectPathSchema.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema.default("documents"), - reportsDir: RelativeProjectPathSchema.default("reports"), - evidenceDir: RelativeProjectPathSchema.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema = contractBaseSchema(SCHEMA_IDS.projectManifest).extend({ - projectId: ProjectSlugSchema, - slug: ProjectSlugSchema, - name: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - status: ProjectStatusSchema.default("active"), - classification: ProjectClassificationSchema.default("private"), - owner: ActorPointerSchema.optional(), - layout: ProjectLayoutSchema.default({}), - integrations: exports_external2.array(IntegrationRefSchema).default([]), - renderManifests: exports_external2.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema = exports_external2.enum(["local", "package", "provider", "url"]); -var RenderImportSchema = exports_external2.object({ - id: exports_external2.string().min(1), - kind: RenderImportKindSchema, - specifier: exports_external2.string().min(1), - path: RelativeProjectPathSchema.optional(), - packageName: exports_external2.string().min(1).optional(), - uri: UriSchema.optional(), - provider: ProjectIntegrationKindSchema.optional(), - schemaId: SchemaIdSchema.optional(), - integrity: HashStringSchema.optional(), - resourceRef: ResourcePointerSchema.optional(), - optional: exports_external2.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema = exports_external2.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1), - kind: RenderViewKindSchema, - default: exports_external2.boolean().default(false), - entry: RelativeProjectPathSchema.optional(), - imports: exports_external2.array(RenderImportSchema).default([]), - panelRefs: exports_external2.array(ResourcePointerSchema).default([]), - dataRefs: exports_external2.array(ResourcePointerSchema).default([]), - layout: MetadataSchema.optional() -}).strict(); -var RenderManifestSchema = contractBaseSchema(SCHEMA_IDS.renderManifest).extend({ - projectId: ProjectSlugSchema, - name: exports_external2.string().min(1), - version: exports_external2.string().min(1), - manifestPath: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), - renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external2.array(RenderViewSchema).min(1), - imports: exports_external2.array(RenderImportSchema).default([]), - theme: MetadataSchema.optional(), - compatibility: exports_external2.object({ - minProjectsVersion: exports_external2.string().min(1).optional(), - minContractsVersion: exports_external2.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema = exports_external2.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema = exports_external2.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema = exports_external2.object({ - id: exports_external2.string().min(1), - label: exports_external2.string().min(1), - value: exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]), - unit: exports_external2.string().min(1).optional(), - status: exports_external2.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) -}).strict(); -var ProjectPanelItemSchema = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - status: exports_external2.string().min(1).optional(), - priority: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema.optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - metadata: MetadataSchema.optional() -}).strict(); -var ProjectRenderFragmentSchema = exports_external2.object({ - renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external2.string().min(1).optional(), - entry: RelativeProjectPathSchema.optional(), - imports: exports_external2.array(RenderImportSchema).default([]), - spec: MetadataSchema.default({}) -}).strict(); -var ProjectPanelSchema = contractBaseSchema(SCHEMA_IDS.projectPanel).extend({ - projectId: ProjectSlugSchema, - provider: exports_external2.object({ - kind: ProjectIntegrationKindSchema, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema.optional(), - externalId: NonEmptyStringSchema.optional() - }).strict(), - kind: ProjectPanelKindSchema, - title: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - state: ProjectPanelStateSchema.default("ready"), - stateReason: exports_external2.string().min(1).optional(), - generatedAt: TimestampSchema, - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external2.array(ProjectPanelMetricSchema).default([]), - items: exports_external2.array(ProjectPanelItemSchema).default([]), - actions: exports_external2.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - renderFragment: ProjectRenderFragmentSchema.optional(), - warnings: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema = contractBaseSchema(SCHEMA_IDS.projectSnapshot).extend({ - projectId: ProjectSlugSchema, - generatedAt: TimestampSchema, - status: ContractStatusSchema.default("unknown"), - manifestRef: ResourcePointerSchema, - renderManifestRef: ResourcePointerSchema.optional(), - panels: exports_external2.array(ProjectPanelSchema).default([]), - contextPacks: exports_external2.array(ContextPackSchema).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - warnings: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema = exports_external2.object({ - id: exports_external2.string().min(1), - kind: exports_external2.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external2.boolean().default(true), - command: exports_external2.string().min(1).optional(), - expected: exports_external2.string().min(1).optional(), - timeoutMs: exports_external2.number().int().positive().optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema = contractBaseSchema(SCHEMA_IDS.validationPlan).extend({ - objective: exports_external2.string().min(1), - subject: ResourcePointerSchema.optional(), - checks: exports_external2.array(ValidationCheckSchema).min(1), - verifier: ActorPointerSchema.optional(), - requiredEvidenceKinds: exports_external2.array(EvidenceKindSchema).default([]) -}).strict(); -var ScaffoldTypeSchema = exports_external2.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema = exports_external2.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema = exports_external2.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema = exports_external2.object({ - key: exports_external2.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external2.string().min(1), - required: exports_external2.boolean().default(false), - ["secret"]: exports_external2.boolean().default(false), - group: exports_external2.string().min(1).optional(), - default: exports_external2.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema = exports_external2.object({ - name: exports_external2.string().min(1), - command: exports_external2.string().min(1), - description: exports_external2.string().min(1).optional(), - required: exports_external2.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema = exports_external2.object({ - packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external2.array(exports_external2.string().min(1)).default([]), - requiredFiles: exports_external2.array(exports_external2.string().min(1)).default([]), - requiredDirectories: exports_external2.array(exports_external2.string().min(1)).default([]), - optionalDirectories: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema = contractBaseSchema(SCHEMA_IDS.scaffoldManifest).extend({ - name: exports_external2.string().min(1), - version: exports_external2.string().min(1), - summary: exports_external2.string().min(1), - type: ScaffoldTypeSchema, - status: ScaffoldStatusSchema.default("draft"), - capabilities: exports_external2.array(ScaffoldCapabilitySchema).default([]), - techStack: exports_external2.array(exports_external2.string().min(1)).default([]), - tags: TagsSchema, - source: ResourcePointerSchema.optional(), - output: ScaffoldOutputShapeSchema, - env: exports_external2.array(ScaffoldEnvVarSchema).default([]), - scripts: exports_external2.array(ScaffoldScriptSchema).default([]), - validationChecks: exports_external2.array(ValidationCheckSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema = exports_external2.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema = contractBaseSchema(SCHEMA_IDS.scaffoldInstallRecord).extend({ - scaffoldId: exports_external2.string().min(1), - scaffoldVersion: exports_external2.string().min(1).optional(), - manifestRef: ResourcePointerSchema.optional(), - target: ResourcePointerSchema, - status: ScaffoldInstallStatusSchema, - installedAt: TimestampSchema.optional(), - installer: ActorPointerSchema.optional(), - packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema.optional(), - generatedFiles: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema = exports_external2.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema = exports_external2.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema = exports_external2.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema = NonEmptyStringSchema.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema = exports_external2.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema = exports_external2.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema = exports_external2.object({ - transport: exports_external2.enum(["http", "stdio"]).default("http"), - bin: exports_external2.string().min(1).optional(), - url: UriSchema.optional() -}).strict(); -var AppHttpSurfaceSchema = exports_external2.object({ - healthPath: exports_external2.string().min(1).default("/health"), - port: exports_external2.number().int().positive().optional(), - baseUrl: UriSchema.optional() -}).strict(); -var AppSurfacesSchema = exports_external2.object({ - bins: exports_external2.array(exports_external2.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema.optional(), - http: AppHttpSurfaceSchema.optional() -}).strict(); -var AppSchema = contractBaseSchema(SCHEMA_IDS.app).extend({ - appId: AppIdSchema, - npmName: NpmPackageNameSchema, - repoFolder: AppIdSchema, - githubUrl: GithubUrlSchema, - projectSlug: ProjectSlugSchema, - surfaces: AppSurfacesSchema.default({}), - lifecycle: AppLifecycleSchema, - releaseChannel: ReleaseChannelSchema.default("stable"), - summary: exports_external2.string().min(1).optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema = exports_external2.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema = contractBaseSchema(SCHEMA_IDS.release).extend({ - appId: AppIdSchema, - package: NpmPackageNameSchema, - version: SemverSchema, - gitSha: GitShaSchema, - publishedAt: TimestampSchema, - publishPath: PublishPathSchema, - changelogRef: ResourcePointerSchema.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema = exports_external2.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema = exports_external2.object({ - cliVersion: exports_external2.string().min(1).optional(), - mcpHealth: exports_external2.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema = contractBaseSchema(SCHEMA_IDS.rolloutRecord).extend({ - appId: AppIdSchema, - package: NpmPackageNameSchema, - version: SemverSchema, - machine: NonEmptyStringSchema, - action: RolloutActionSchema, - result: ContractStatusSchema, - verifiedBy: RolloutVerificationSchema.optional(), - at: TimestampSchema, - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema = exports_external2.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema = exports_external2.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema = exports_external2.object({ - channel: AnnouncementChannelKindSchema, - status: AnnouncementDeliveryStatusSchema, - deliveredAt: TimestampSchema.optional(), - detail: exports_external2.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema = contractBaseSchema(SCHEMA_IDS.announcement).extend({ - campaignId: NonEmptyStringSchema, - appId: AppIdSchema.optional(), - releaseRef: ResourcePointerSchema.optional(), - channels: exports_external2.array(AnnouncementChannelSchema).min(1), - audienceRef: ResourcePointerSchema, - sentAt: TimestampSchema -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema = exports_external2.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema = exports_external2.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema = exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]); -var AudiencePredicateSchema = exports_external2.object({ - kind: AudiencePredicateKindSchema, - key: exports_external2.string().min(1).optional(), - op: AudiencePredicateOpSchema.default("eq"), - value: AudiencePredicateValueSchema.optional(), - values: exports_external2.array(AudiencePredicateValueSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema = exports_external2.object({ - match: exports_external2.enum(["all", "any"]).default("all"), - predicates: exports_external2.array(AudiencePredicateSchema).min(1) -}).strict(); -var ConsentPolicySchema = exports_external2.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema = contractBaseSchema(SCHEMA_IDS.audience).extend({ - audienceId: AppIdSchema, - name: NonEmptyStringSchema, - definition: AudienceDefinitionSchema, - consentPolicy: ConsentPolicySchema, - suppressionSyncedAt: OptionalTimestampSchema -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema = exports_external2.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema = exports_external2.object({ - id: exports_external2.string().min(1), - provider: AppCloudProviderSchema, - kind: exports_external2.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external2.string().min(1), - region: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - uri: UriSchema.optional(), - machineScoped: exports_external2.boolean().default(false) -}).strict(); -var AppCloudManifestSchema = contractBaseSchema(SCHEMA_IDS.appCloudManifest).extend({ - packageName: exports_external2.string().min(1), - packageVersion: exports_external2.string().min(1).optional(), - appId: exports_external2.string().min(1), - repository: ResourcePointerSchema.optional(), - storageMode: exports_external2.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external2.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external2.array(AppCloudResourceSchema).default([]), - localCache: exports_external2.object({ - path: exports_external2.string().min(1).optional(), - pullMode: exports_external2.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external2.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external2.array(exports_external2.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES]), - dependencies: exports_external2.array(exports_external2.string().min(1)).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema = exports_external2.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema = exports_external2.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema = exports_external2.object({ - id: exports_external2.string().min(1), - kind: NoCloudCheckKindSchema, - severity: NoCloudFindingSeveritySchema, - path: exports_external2.string().min(1).optional(), - packageName: exports_external2.string().min(1).optional(), - pattern: exports_external2.string().min(1), - message: exports_external2.string().min(1), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict(); -var NoCloudCheckResultSchema = exports_external2.object({ - id: exports_external2.string().min(1), - kind: NoCloudCheckKindSchema, - status: ContractStatusSchema, - target: exports_external2.string().min(1), - command: exports_external2.string().min(1).optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - findings: exports_external2.array(NoCloudFindingSchema).default([]) -}).strict(); -var NoCloudEvidencePackSchema = contractBaseSchema(SCHEMA_IDS.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema, - packageName: exports_external2.string().min(1).optional(), - packageVersion: exports_external2.string().min(1).optional(), - generatedBy: ActorPointerSchema.optional(), - scanMode: exports_external2.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema, - verdict: exports_external2.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema.optional(), - checks: exports_external2.array(NoCloudCheckResultSchema).min(1), - findings: exports_external2.array(NoCloudFindingSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check2) => check2.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check2) => check2.status !== "succeeded")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check2) => check2.status === "failed")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check2, index) => { - const checkBlockingFindings = check2.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check2.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema = exports_external2.object({ - checkId: exports_external2.string().min(1), - status: ContractStatusSchema, - summary: exports_external2.string().min(1).optional(), - startedAt: OptionalTimestampSchema, - finishedAt: OptionalTimestampSchema, - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict(); -var ProofBundleSchema = contractBaseSchema(SCHEMA_IDS.proofBundle).extend({ - subject: ResourcePointerSchema, - validationPlanRef: ResourcePointerSchema.optional(), - status: ContractStatusSchema, - verdict: exports_external2.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external2.array(ProofCheckResultSchema).default([]), - verifier: ActorPointerSchema.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - residualRisks: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check2, index) => { - if (check2.status !== "succeeded") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check2) => check2.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check2) => check2.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema = contractBaseSchema(SCHEMA_IDS.workRun).extend({ - objective: exports_external2.string().min(1), - status: ContractStatusSchema, - actor: ActorPointerSchema, - traceId: exports_external2.string().min(1).optional(), - startedAt: OptionalTimestampSchema, - finishedAt: OptionalTimestampSchema, - constraints: exports_external2.array(exports_external2.string().min(1)).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - decisions: exports_external2.array(DecisionEnvelopeSchema).default([]), - costEstimates: exports_external2.array(CostEstimateSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - validationPlanRefs: exports_external2.array(ResourcePointerSchema).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema = exports_external2.object({ - id: exports_external2.string().min(1), - at: TimestampSchema, - kind: exports_external2.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external2.string().min(1), - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), - costEstimate: CostEstimateSchema.optional() -}).strict(); -var AgentTrajectorySchema = contractBaseSchema(SCHEMA_IDS.agentTrajectory).extend({ - actor: ActorPointerSchema, - workRunRef: ResourcePointerSchema.optional(), - events: exports_external2.array(TrajectoryEventSchema).default([]), - outcome: exports_external2.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION = "v1"; -var RepoClassSchema = exports_external2.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema = exports_external2.enum(DEPLOYMENT_MODES); -var ServiceSurfaceStatusSchema = exports_external2.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema = exports_external2.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema = exports_external2.object({ - method: exports_external2.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external2.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external2.boolean().default(false), - description: exports_external2.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema = exports_external2.object({ - id: exports_external2.string().min(1), - kind: exports_external2.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external2.boolean().default(true), - command: exports_external2.string().min(1).optional(), - evidenceRef: EvidencePointerSchema.optional(), - status: exports_external2.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external2.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema = exports_external2.object({ - name: exports_external2.string().min(1), - status: ServiceSurfaceStatusSchema, - bin: exports_external2.string().min(1).optional(), - mcpBin: exports_external2.string().min(1).optional(), - authMode: ServiceAuthModeSchema, - deploymentModes: exports_external2.array(DeploymentModeSchema).min(1), - health: ServiceEndpointSchema.optional(), - readiness: ServiceEndpointSchema.optional(), - version: ServiceEndpointSchema.optional(), - apiBasePath: exports_external2.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external2.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external2.string().min(1).optional(), - readinessGates: exports_external2.array(DeploymentReadinessGateSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES = ["local", "cloud"]; -var StorageModeSchema = exports_external2.enum(STORAGE_MODES); -var DEPRECATED_STORAGE_MODE_ALIASES = ["remote", "hybrid", "self_hosted"]; -var AppNameSchema = exports_external2.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName(name) { - return ALLOWED_BIN_SUFFIXES.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema = exports_external2.object({ - mode: StorageModeSchema, - envPrefix: exports_external2.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external2.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external2.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external2.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema = exports_external2.object({ - $schema: exports_external2.string().min(1).optional(), - schema: exports_external2.literal(SCHEMA_IDS.serviceContract), - name: AppNameSchema, - class: RepoClassSchema, - contractVersion: exports_external2.literal(SERVICE_CONTRACT_VERSION), - kitVersion: exports_external2.string().min(1), - description: exports_external2.string().min(1).optional(), - bins: exports_external2.array(exports_external2.string().min(1)).default([]), - storage: StorageContractSchema.optional(), - deploymentModes: exports_external2.array(DeploymentModeSchema).default(["local"]), - serviceSurfaces: exports_external2.array(ServiceSurfaceSchema).default([]), - metadata: MetadataSchema.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor(value.name)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna//.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } - } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); - } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } - } - } -}); -var HealthResponseSchema = exports_external2.object({ - status: exports_external2.enum(["ok", "degraded", "unavailable"]), - version: exports_external2.string().min(1), - mode: StorageModeSchema -}).strict(); -var ReadyResponseSchema = exports_external2.object({ - ready: exports_external2.boolean(), - reason: exports_external2.string().min(1).optional() -}).strict(); -var VersionResponseSchema = exports_external2.object({ - version: exports_external2.string().min(1) -}).strict(); -var CommsSeveritySchema = exports_external2.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema = exports_external2.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (..)"); -var COMMS_SEVERITY_TAGS = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema = exports_external2.enum(COMMS_SEVERITY_TAGS); -var CommsScopeSchema = exports_external2.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.commsEventEnvelope).extend({ - type: CommsEventTypeSchema, - severity: CommsSeveritySchema, - scope: CommsScopeSchema, - summary: exports_external2.string().min(1).optional(), - source: ActorPointerSchema.optional(), - affected_packages: exports_external2.array(NonEmptyStringSchema).default([]), - affected_machines: exports_external2.array(NonEmptyStringSchema).default([]), - action_required: exports_external2.boolean().default(false), - ack_by: TimestampSchema.optional(), - dedupe_key: NonEmptyStringSchema, - resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); - } - } -}); -var CommsChannelClassSchema = exports_external2.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema = exports_external2.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema = NonEmptyStringSchema.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"); -var CommsChannelMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsChannelMetadata).extend({ - class: CommsChannelClassSchema, - noise: CommsChannelNoiseSchema.optional(), - owner: NonEmptyStringSchema.optional(), - until: CommsUntilHorizonSchema.optional(), - successor: NonEmptyStringSchema.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); - } - } -}); -var COMMS_SEVERITY_TAG_INFO = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema, - envelope: CommsEventEnvelopeSchema -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] - }); - } - } -}); -var ContractSchemaRegistry = { - [SCHEMA_IDS.actorRef]: ActorRefSchema, - [SCHEMA_IDS.resourceRef]: ResourceRefSchema, - [SCHEMA_IDS.evidenceRef]: EvidenceRefSchema, - [SCHEMA_IDS.workRun]: WorkRunSchema, - [SCHEMA_IDS.decisionEnvelope]: DecisionEnvelopeSchema, - [SCHEMA_IDS.costEstimate]: CostEstimateSchema, - [SCHEMA_IDS.capabilityCard]: CapabilityCardSchema, - [SCHEMA_IDS.providerLiveModeStandard]: ProviderLiveModeStandardSchema, - [SCHEMA_IDS.contextPack]: ContextPackSchema, - [SCHEMA_IDS.integrationRef]: IntegrationRefSchema, - [SCHEMA_IDS.projectManifest]: ProjectManifestSchema, - [SCHEMA_IDS.projectPanel]: ProjectPanelSchema, - [SCHEMA_IDS.projectSnapshot]: ProjectSnapshotSchema, - [SCHEMA_IDS.renderManifest]: RenderManifestSchema, - [SCHEMA_IDS.agentTrajectory]: AgentTrajectorySchema, - [SCHEMA_IDS.validationPlan]: ValidationPlanSchema, - [SCHEMA_IDS.proofBundle]: ProofBundleSchema, - [SCHEMA_IDS.scaffoldManifest]: ScaffoldManifestSchema, - [SCHEMA_IDS.scaffoldInstallRecord]: ScaffoldInstallRecordSchema, - [SCHEMA_IDS.appCloudManifest]: AppCloudManifestSchema, - [SCHEMA_IDS.noCloudEvidencePack]: NoCloudEvidencePackSchema, - [SCHEMA_IDS.serviceContract]: ServiceContractManifestSchema, - [SCHEMA_IDS.commsEventEnvelope]: CommsEventEnvelopeSchema, - [SCHEMA_IDS.commsChannelMetadata]: CommsChannelMetadataSchema, - [SCHEMA_IDS.commsMessageMetadata]: CommsMessageMetadataSchema, - [SCHEMA_IDS.app]: AppSchema, - [SCHEMA_IDS.release]: ReleaseSchema, - [SCHEMA_IDS.rolloutRecord]: RolloutRecordSchema, - [SCHEMA_IDS.announcement]: AnnouncementSchema, - [SCHEMA_IDS.audience]: AudienceSchema -}; -function normalizeStorageMode(value) { - const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); -} -function envToken(name) { - return name.toUpperCase().replace(/-/g, "_"); -} -function defaultCloudBaseUrl(name) { - return `https://${name}.hasna.xyz`; -} -function clientTransportEnvKeys(name) { - const envSegment = envToken(name); - return { - modeKeys: [ - `HASNA_${envSegment}_STORAGE_MODE`, - `HASNA_${envSegment}_MODE`, - `${envSegment}_STORAGE_MODE`, - `${envSegment}_MODE` - ], - apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], - apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] - }; -} -function firstEnv2(env, keys) { - for (const key of keys) { - const value = env[key]?.trim(); - if (value) - return { key, value }; - } - return null; -} -function toV1BaseUrl(apiUrl) { - const url2 = new URL(apiUrl); - if (url2.protocol !== "http:" && url2.protocol !== "https:") { - throw new Error("API URL must use http or https."); - } - let path = url2.pathname.replace(/\/+$/, ""); - if (path.endsWith("/v1")) - path = path.slice(0, -"/v1".length); - url2.pathname = `${path}/v1`; - url2.search = ""; - url2.hash = ""; - return url2.toString().replace(/\/+$/, ""); -} -function resolveClientTransport(name, env = process.env) { - const keys = clientTransportEnvKeys(name); - const modeHit = firstEnv2(env, keys.modeKeys); - const urlHit = firstEnv2(env, keys.apiUrlKeys); - const keyHit = firstEnv2(env, keys.apiKeyKeys); - let mode = "local"; - let deprecatedAlias = null; - let modeSource = "default"; - const warnings = []; - if (modeHit) { - const normalized = normalizeStorageMode(modeHit.value); - mode = normalized.mode; - deprecatedAlias = normalized.deprecatedAlias; - modeSource = modeHit.key; - if (deprecatedAlias) { - warnings.push(`Deprecated mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Prefer ${keys.modeKeys[0]}=cloud.`); - } - } else if (urlHit && keyHit) { - mode = "cloud"; - modeSource = `${urlHit.key}+${keyHit.key}`; - } - if (mode === "local") { - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: Boolean(keyHit), - apiKeySource: keyHit ? keyHit.key : null, - misconfigured: false, - warning: warnings.length > 0 ? warnings.join(" ") : null - }; - } - if (!keyHit) { - warnings.push(`${modeSource}=cloud but no API key is set (${keys.apiKeyKeys[0]}). Refusing to route to cloud; using local store. Set ${keys.apiKeyKeys[0]} to enable the cloud client.`); - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: false, - apiKeySource: null, - misconfigured: true, - warning: warnings.join(" ") - }; - } - const rawUrl = urlHit?.value ?? defaultCloudBaseUrl(name); - const apiUrlSource = urlHit ? urlHit.key : "default"; - let baseUrl; - try { - baseUrl = toV1BaseUrl(rawUrl); - } catch (error51) { - const message = error51 instanceof Error ? error51.message : String(error51); - warnings.push(`Invalid API URL from ${apiUrlSource}: ${message}. Using local store.`); - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: true, - apiKeySource: keyHit.key, - misconfigured: true, - warning: warnings.join(" ") - }; - } - return { - transport: "cloud-http", - mode, - deprecatedAlias, - modeSource, - baseUrl, - apiUrlSource, - apiKeyPresent: true, - apiKeySource: keyHit.key, - misconfigured: false, - warning: warnings.length > 0 ? warnings.join(" ") : null - }; -} - -class HasnaHttpError extends Error { - status; - method; - path; - body; - constructor(method, path, status, body) { - super(`Hasna cloud request failed: ${method} ${path} -> ${status}`); - this.name = "HasnaHttpError"; - this.status = status; - this.method = method; - this.path = path; - this.body = body; - } -} -var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504]; -var IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); -function appendQuery(path, query) { - if (!query) - return path; - const params = query instanceof URLSearchParams ? query : new URLSearchParams; - if (!(query instanceof URLSearchParams)) { - for (const [key, value] of Object.entries(query)) { - if (value === null || value === undefined) - continue; - if (Array.isArray(value)) { - for (const v of value) - params.append(key, String(v)); - } else { - params.append(key, String(value)); - } - } - } - const qs = params.toString(); - if (!qs) - return path; - return `${path}${path.includes("?") ? "&" : "?"}${qs}`; -} -var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); -function createHasnaHttpTransport(options) { - const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init)); - const base = options.baseUrl.replace(/\/+$/, ""); - const timeoutMs = options.timeoutMs ?? 30000; - const sleep = options.sleepImpl ?? defaultSleep; - const defaultRetry = options.retry; - function resolveRetry(callRetry) { - const chosen = callRetry !== undefined ? callRetry : defaultRetry; - if (chosen === false) - return null; - const r = chosen ?? {}; - return { - retries: r.retries ?? 2, - baseDelayMs: r.baseDelayMs ?? 200, - maxDelayMs: r.maxDelayMs ?? 2000, - retryStatuses: r.retryStatuses ?? [...DEFAULT_RETRY_STATUSES] - }; - } - async function once(method, rel, url2, body, opts) { - const headers = { - "x-api-key": options.apiKey, - Authorization: `Bearer ${options.apiKey}`, - Accept: "application/json", - ...options.headers ?? {}, - ...opts.headers ?? {} - }; - if (opts.idempotencyKey) - headers["Idempotency-Key"] = opts.idempotencyKey; - const init = { method, headers }; - if (body !== undefined) { - headers["Content-Type"] = "application/json"; - init.body = JSON.stringify(body); - } - const controller = new AbortController; - const onAbort = () => controller.abort(); - if (opts.signal) { - if (opts.signal.aborted) - controller.abort(); - else - opts.signal.addEventListener("abort", onAbort, { once: true }); - } - const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? timeoutMs); - init.signal = controller.signal; - let response; - try { - response = await fetchImpl(url2, init); - } catch (error51) { - const err = error51 instanceof Error ? error51 : new Error(String(error51)); - if (opts.signal?.aborted) - return { ok: false, retryable: false, error: err }; - return { ok: false, retryable: true, error: err }; - } finally { - clearTimeout(timer); - if (opts.signal) - opts.signal.removeEventListener("abort", onAbort); - } - const text = await response.text(); - let parsed = undefined; - if (text.length > 0) { - try { - parsed = JSON.parse(text); - } catch { - parsed = text; - } - } - if (!response.ok) { - const retry = resolveRetry(opts.retry); - const retryable = retry ? retry.retryStatuses.includes(response.status) : false; - return { ok: false, retryable, error: new HasnaHttpError(method, rel, response.status, parsed) }; - } - return { ok: true, value: parsed }; - } - async function request(method, path, body, opts = {}) { - const upper = method.toUpperCase(); - const rel = appendQuery(path.startsWith("/") ? path : `/${path}`, opts.query); - const url2 = `${base}${rel}`; - const retry = resolveRetry(opts.retry); - const methodRetryable = IDEMPOTENT_METHODS.has(upper) || Boolean(opts.idempotencyKey); - const maxAttempts = retry && methodRetryable ? retry.retries + 1 : 1; - let last = null; - for (let attempt = 1;attempt <= maxAttempts; attempt++) { - const result = await once(upper, rel, url2, body, opts); - if (result.ok) - return result.value; - last = result; - const canRetry = retry !== null && methodRetryable && result.retryable && attempt < maxAttempts; - if (!canRetry) - break; - const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1)); - const jitter = Math.floor(Math.random() * (backoff / 2 + 1)); - await sleep(backoff + jitter); - } - throw last.error; - } - return { - baseUrl: base, - request, - get: (path, opts) => request("GET", path, undefined, opts), - post: (path, body, opts) => request("POST", path, body, opts), - put: (path, body, opts) => request("PUT", path, body, opts), - patch: (path, body, opts) => request("PATCH", path, body, opts), - del: (path, body, opts) => request("DELETE", path, body, opts) - }; -} -function createClientTransport(name, env = process.env, overrides) { - const resolution = resolveClientTransport(name, env); - if (resolution.misconfigured) { - throw new Error(resolution.warning ?? `Client for '${name}' is misconfigured for cloud mode.`); - } - if (resolution.transport === "local" || !resolution.baseUrl) { - return { transport: "local", client: null, resolution }; - } - const keys = clientTransportEnvKeys(name); - const apiKey = firstEnv2(env, keys.apiKeyKeys)?.value; - if (!apiKey) { - throw new Error(`Client for '${name}' resolved to cloud-http without an API key.`); - } - return { - transport: "cloud-http", - client: createHasnaHttpTransport({ - name, - baseUrl: resolution.baseUrl, - apiKey, - ...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {}, - ...overrides?.headers ? { headers: overrides.headers } : {}, - ...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {}, - ...overrides?.retry !== undefined ? { retry: overrides.retry } : {}, - ...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {} - }), - resolution - }; -} -function resourcePath(resource) { - const trimmed = resource.replace(/^\/+|\/+$/g, ""); - if (!trimmed) - throw new Error("resource must be a non-empty path segment"); - return `/${trimmed}`; -} -function entityPath(resource, id) { - if (id === undefined || id === null || `${id}`.length === 0) { - throw new Error("id must be a non-empty string"); - } - return `${resourcePath(resource)}/${encodeURIComponent(String(id))}`; -} -function newIdempotencyKey() { - const g = globalThis; - if (g.crypto?.randomUUID) - return g.crypto.randomUUID(); - return `idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`; -} -function extractItems(raw) { - if (Array.isArray(raw)) - return raw; - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["items", "data", "results", "rows", "records"]) { - if (Array.isArray(obj[key])) - return obj[key]; - } - } - return []; -} -function extractTotal(raw) { - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["total", "count", "totalCount", "total_count"]) { - if (typeof obj[key] === "number") - return obj[key]; - } - } - return null; -} -function extractCursor(raw) { - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["cursor", "nextCursor", "next_cursor", "next"]) { - if (typeof obj[key] === "string") - return obj[key]; - } - } - return null; -} -function createHasnaStorageClient(name, transport) { - return { - name, - baseUrl: transport.baseUrl, - transport, - async list(resource, options = {}) { - const raw = await transport.get(resourcePath(resource), options); - return { - items: extractItems(raw), - total: extractTotal(raw), - cursor: extractCursor(raw), - raw - }; - }, - async get(resource, id, options = {}) { - try { - return await transport.get(entityPath(resource, id), options); - } catch (error51) { - if (error51 instanceof HasnaHttpError && error51.status === 404) - return null; - throw error51; - } - }, - async create(resource, body, options = {}) { - const { idempotencyKey, ...rest } = options; - return transport.post(resourcePath(resource), body, { - ...rest, - idempotencyKey: idempotencyKey ?? newIdempotencyKey() - }); - }, - async update(resource, id, patch, options = {}) { - const { method = "PATCH", idempotencyKey, ...rest } = options; - const call = method === "PUT" ? transport.put : transport.patch; - return call(entityPath(resource, id), patch, { ...rest, ...idempotencyKey ? { idempotencyKey } : {} }); - }, - async delete(resource, id, options = {}) { - try { - await transport.del(entityPath(resource, id), undefined, options); - } catch (error51) { - if (error51 instanceof HasnaHttpError && error51.status === 404) - return; - throw error51; - } - } - }; -} -function resolveStorageClient(name, env = process.env, overrides) { - const wired = createClientTransport(name, env, overrides); - if (wired.transport === "cloud-http") { - return { transport: "cloud-http", client: createHasnaStorageClient(name, wired.client) }; - } - return { transport: "local", client: null }; -} - -// node_modules/@hasna/contracts/dist/client/transport.js -var __defProp3 = Object.defineProperty; -var __returnValue3 = (v) => v; -function __exportSetter3(name, newValue) { - this[name] = __returnValue3.bind(null, newValue); -} -var __export3 = (target, all) => { - for (var name in all) - __defProp3(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter3.bind(all, name) - }); -}; -var exports_external3 = {}; -__export3(exports_external3, { - void: () => voidType2, - util: () => util2, - unknown: () => unknownType2, - union: () => unionType2, - undefined: () => undefinedType2, - tuple: () => tupleType2, - transformer: () => effectsType2, - symbol: () => symbolType2, - string: () => stringType2, - strictObject: () => strictObjectType2, - setErrorMap: () => setErrorMap3, - set: () => setType2, - record: () => recordType2, - quotelessJson: () => quotelessJson2, - promise: () => promiseType2, - preprocess: () => preprocessType2, - pipeline: () => pipelineType2, - ostring: () => ostring2, - optional: () => optionalType2, - onumber: () => onumber2, - oboolean: () => oboolean2, - objectUtil: () => objectUtil2, - object: () => objectType2, - number: () => numberType2, - nullable: () => nullableType2, - null: () => nullType2, - never: () => neverType2, - nativeEnum: () => nativeEnumType2, - nan: () => nanType2, - map: () => mapType2, - makeIssue: () => makeIssue2, - literal: () => literalType2, - lazy: () => lazyType2, - late: () => late2, - isValid: () => isValid2, - isDirty: () => isDirty2, - isAsync: () => isAsync2, - isAborted: () => isAborted2, - intersection: () => intersectionType2, - instanceof: () => instanceOfType2, - getParsedType: () => getParsedType3, - getErrorMap: () => getErrorMap3, - function: () => functionType2, - enum: () => enumType2, - effect: () => effectsType2, - discriminatedUnion: () => discriminatedUnionType2, - defaultErrorMap: () => en_default3, - datetimeRegex: () => datetimeRegex2, - date: () => dateType2, - custom: () => custom3, - coerce: () => coerce2, - boolean: () => booleanType2, - bigint: () => bigIntType2, - array: () => arrayType2, - any: () => anyType2, - addIssueToContext: () => addIssueToContext2, - ZodVoid: () => ZodVoid3, - ZodUnknown: () => ZodUnknown3, - ZodUnion: () => ZodUnion3, - ZodUndefined: () => ZodUndefined3, - ZodType: () => ZodType3, - ZodTuple: () => ZodTuple3, - ZodTransformer: () => ZodEffects2, - ZodSymbol: () => ZodSymbol3, - ZodString: () => ZodString3, - ZodSet: () => ZodSet3, - ZodSchema: () => ZodType3, - ZodRecord: () => ZodRecord3, - ZodReadonly: () => ZodReadonly3, - ZodPromise: () => ZodPromise3, - ZodPipeline: () => ZodPipeline2, - ZodParsedType: () => ZodParsedType2, - ZodOptional: () => ZodOptional3, - ZodObject: () => ZodObject3, - ZodNumber: () => ZodNumber3, - ZodNullable: () => ZodNullable3, - ZodNull: () => ZodNull3, - ZodNever: () => ZodNever3, - ZodNativeEnum: () => ZodNativeEnum2, - ZodNaN: () => ZodNaN3, - ZodMap: () => ZodMap3, - ZodLiteral: () => ZodLiteral3, - ZodLazy: () => ZodLazy3, - ZodIssueCode: () => ZodIssueCode3, - ZodIntersection: () => ZodIntersection3, - ZodFunction: () => ZodFunction3, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind3, - ZodError: () => ZodError3, - ZodEnum: () => ZodEnum3, - ZodEffects: () => ZodEffects2, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion3, - ZodDefault: () => ZodDefault3, - ZodDate: () => ZodDate3, - ZodCatch: () => ZodCatch3, - ZodBranded: () => ZodBranded2, - ZodBoolean: () => ZodBoolean3, - ZodBigInt: () => ZodBigInt3, - ZodArray: () => ZodArray3, - ZodAny: () => ZodAny3, - Schema: () => ZodType3, - ParseStatus: () => ParseStatus2, - OK: () => OK2, - NEVER: () => NEVER3, - INVALID: () => INVALID2, - EMPTY_PATH: () => EMPTY_PATH2, - DIRTY: () => DIRTY2, - BRAND: () => BRAND2 -}); -var util2; -(function(util22) { - util22.assertEqual = (_) => {}; - function assertIs2(_arg) {} - util22.assertIs = assertIs2; - function assertNever2(_x) { - throw new Error; - } - util22.assertNever = assertNever2; - util22.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util22.getValidEnumValues = (obj) => { - const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util22.objectValues(filtered); - }; - util22.objectValues = (obj) => { - return util22.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { - const keys = []; - for (const key in object2) { - if (Object.prototype.hasOwnProperty.call(object2, key)) { - keys.push(key); - } - } - return keys; - }; - util22.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues2(array2, separator = " | ") { - return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util22.joinValues = joinValues2; - util22.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util2 || (util2 = {})); -var objectUtil2; -(function(objectUtil22) { - objectUtil22.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; -})(objectUtil2 || (objectUtil2 = {})); -var ZodParsedType2 = util2.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType3 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType2.undefined; - case "string": - return ZodParsedType2.string; - case "number": - return Number.isNaN(data) ? ZodParsedType2.nan : ZodParsedType2.number; - case "boolean": - return ZodParsedType2.boolean; - case "function": - return ZodParsedType2.function; - case "bigint": - return ZodParsedType2.bigint; - case "symbol": - return ZodParsedType2.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType2.array; - } - if (data === null) { - return ZodParsedType2.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType2.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType2.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType2.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType2.date; - } - return ZodParsedType2.object; - default: - return ZodParsedType2.unknown; - } -}; -var ZodIssueCode3 = util2.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson2 = (obj) => { - const json2 = JSON.stringify(obj, null, 2); - return json2.replace(/"([^"]+)":/g, "$1:"); -}; - -class ZodError3 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error51) => { - for (const issue2 of error51.issues) { - if (issue2.code === "invalid_union") { - issue2.unionErrors.map(processError); - } else if (issue2.code === "invalid_return_type") { - processError(issue2.returnTypeError); - } else if (issue2.code === "invalid_arguments") { - processError(issue2.argumentsError); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError3)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError3.create = (issues) => { - const error51 = new ZodError3(issues); - return error51; -}; -var errorMap2 = (issue2, _ctx) => { - let message; - switch (issue2.code) { - case ZodIssueCode3.invalid_type: - if (issue2.received === ZodParsedType2.undefined) { - message = "Required"; - } else { - message = `Expected ${issue2.expected}, received ${issue2.received}`; - } - break; - case ZodIssueCode3.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util2.jsonStringifyReplacer)}`; - break; - case ZodIssueCode3.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util2.joinValues(issue2.keys, ", ")}`; - break; - case ZodIssueCode3.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode3.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util2.joinValues(issue2.options)}`; - break; - case ZodIssueCode3.invalid_enum_value: - message = `Invalid enum value. Expected ${util2.joinValues(issue2.options)}, received '${issue2.received}'`; - break; - case ZodIssueCode3.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode3.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode3.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode3.invalid_string: - if (typeof issue2.validation === "object") { - if ("includes" in issue2.validation) { - message = `Invalid input: must include "${issue2.validation.includes}"`; - if (typeof issue2.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; - } - } else if ("startsWith" in issue2.validation) { - message = `Invalid input: must start with "${issue2.validation.startsWith}"`; - } else if ("endsWith" in issue2.validation) { - message = `Invalid input: must end with "${issue2.validation.endsWith}"`; - } else { - util2.assertNever(issue2.validation); - } - } else if (issue2.validation !== "regex") { - message = `Invalid ${issue2.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode3.too_small: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "bigint") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode3.too_big: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "bigint") - message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode3.custom: - message = `Invalid input`; - break; - case ZodIssueCode3.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode3.not_multiple_of: - message = `Number must be a multiple of ${issue2.multipleOf}`; - break; - case ZodIssueCode3.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util2.assertNever(issue2); - } - return { message }; -}; -var en_default3 = errorMap2; -var overrideErrorMap2 = en_default3; -function setErrorMap3(map2) { - overrideErrorMap2 = map2; -} -function getErrorMap3() { - return overrideErrorMap2; -} -var makeIssue2 = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map2 of maps) { - errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH2 = []; -function addIssueToContext2(ctx, issueData) { - const overrideMap = getErrorMap3(); - const issue2 = makeIssue2({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default3 ? undefined : en_default3 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue2); -} - -class ParseStatus2 { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID2; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus2.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID2; - if (value.status === "aborted") - return INVALID2; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -var INVALID2 = Object.freeze({ - status: "aborted" -}); -var DIRTY2 = (value) => ({ status: "dirty", value }); -var OK2 = (value) => ({ status: "valid", value }); -var isAborted2 = (x) => x.status === "aborted"; -var isDirty2 = (x) => x.status === "dirty"; -var isValid2 = (x) => x.status === "valid"; -var isAsync2 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil2; -(function(errorUtil22) { - errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil2 || (errorUtil2 = {})); - -class ParseInputLazyPath2 { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -var handleResult2 = (ctx, result) => { - if (isValid2(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error51 = new ZodError3(ctx.common.issues); - this._error = error51; - return this._error; - } - }; - } -}; -function processCreateParams2(params) { - if (!params) - return {}; - const { errorMap: errorMap22, invalid_type_error, required_error, description } = params; - if (errorMap22 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap22) - return { errorMap: errorMap22, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -class ZodType3 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType3(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType3(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus2, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType3(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync2(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult2(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult2(ctx, result); - } - refine(check2, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check2(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode3.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check2, refinementData) { - return this._refinement((val, ctx) => { - if (!check2(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects2({ - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional3.create(this, this._def); - } - nullable() { - return ZodNullable3.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray3.create(this); - } - promise() { - return ZodPromise3.create(this, this._def); - } - or(option) { - return ZodUnion3.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection3.create(this, incoming, this._def); - } - transform(transform2) { - return new ZodEffects2({ - ...processCreateParams2(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "transform", transform: transform2 } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault3({ - ...processCreateParams2(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodDefault - }); - } - brand() { - return new ZodBranded2({ - typeName: ZodFirstPartyTypeKind3.ZodBranded, - type: this, - ...processCreateParams2(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch3({ - ...processCreateParams2(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline2.create(this, target); - } - readonly() { - return ZodReadonly3.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex2 = /^c[^\s-]{8,}$/i; -var cuid2Regex2 = /^[0-9a-z]+$/; -var ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex2 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex2 = /^[a-z0-9_-]{21}$/i; -var jwtRegex2 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex2 = /^[-+]?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)?)??$/; -var emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex2 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex2; -var ipv4Regex2 = /^(?:(?: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])$/; -var ipv4CidrRegex2 = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex2 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex2 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex2 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource2 = `((\\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])))`; -var dateRegex2 = new RegExp(`^${dateRegexSource2}$`); -function timeRegexSource2(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex2(args) { - return new RegExp(`^${timeRegexSource2(args)}$`); -} -function datetimeRegex2(args) { - let regex = `${dateRegexSource2}T${timeRegexSource2(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP2(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4Regex2.test(ip)) { - return true; - } - if ((version2 === "v6" || !version2) && ipv6Regex2.test(ip)) { - return true; - } - return false; -} -function isValidJWT3(jwt2, alg) { - if (!jwtRegex2.test(jwt2)) - return false; - try { - const [header] = jwt2.split("."); - if (!header) - return false; - const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base643)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr2(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4CidrRegex2.test(ip)) { - return true; - } - if ((version2 === "v6" || !version2) && ipv6CidrRegex2.test(ip)) { - return true; - } - return false; -} - -class ZodString3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.string, - received: ctx2.parsedType - }); - return INVALID2; - } - const status = new ParseStatus2; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.length < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.length > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "length") { - const tooBig = input.data.length > check2.value; - const tooSmall = input.data.length < check2.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } else if (tooSmall) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } - status.dirty(); - } - } else if (check2.kind === "email") { - if (!emailRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "email", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "emoji") { - if (!emojiRegex2) { - emojiRegex2 = new RegExp(_emojiRegex2, "u"); - } - if (!emojiRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "emoji", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "uuid") { - if (!uuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "uuid", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "nanoid") { - if (!nanoidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "nanoid", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid") { - if (!cuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid2") { - if (!cuid2Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid2", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ulid") { - if (!ulidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ulid", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "url", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "regex") { - check2.regex.lastIndex = 0; - const testResult = check2.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "regex", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "trim") { - input.data = input.data.trim(); - } else if (check2.kind === "includes") { - if (!input.data.includes(check2.value, check2.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { includes: check2.value, position: check2.position }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check2.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check2.kind === "startsWith") { - if (!input.data.startsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { startsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "endsWith") { - if (!input.data.endsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { endsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "datetime") { - const regex = datetimeRegex2(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "datetime", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "date") { - const regex = dateRegex2; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "date", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "time") { - const regex = timeRegex2(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "time", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "duration") { - if (!durationRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "duration", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ip") { - if (!isValidIP2(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ip", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "jwt") { - if (!isValidJWT3(input.data, check2.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "jwt", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cidr") { - if (!isValidCidr2(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cidr", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64") { - if (!base64Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64url") { - if (!base64urlRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64url", - code: ZodIssueCode3.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else { - util2.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode3.invalid_string, - ...errorUtil2.errToObj(message) - }); - } - _addCheck(check2) { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil2.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil2.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil2.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil2.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil2.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil2.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil2.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil2.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil2.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil2.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil2.errToObj(message)); - } - trim() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString3.create = (params) => { - return new ZodString3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); -}; -function floatSafeRemainder3(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} - -class ZodNumber3 extends ZodType3 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.number, - received: ctx2.parsedType - }); - return INVALID2; - } - let ctx = undefined; - const status = new ParseStatus2; - for (const check2 of this._def.checks) { - if (check2.kind === "int") { - if (!util2.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: "integer", - received: "float", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - minimum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - maximum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (floatSafeRemainder3(input.data, check2.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.not_finite, - message: check2.message - }); - status.dirty(); - } - } else { - util2.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber3({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodNumber3({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil2.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil2.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil2.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil2.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber3.create = (params) => { - return new ZodNumber3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); -}; - -class ZodBigInt3 extends ZodType3 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus2; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - type: "bigint", - minimum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - type: "bigint", - maximum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (input.data % check2.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else { - util2.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.bigint, - received: ctx.parsedType - }); - return INVALID2; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt3({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodBigInt3({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt3.create = (params) => { - return new ZodBigInt3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); -}; - -class ZodBoolean3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.boolean, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodBoolean3.create = (params) => { - return new ZodBoolean3({ - typeName: ZodFirstPartyTypeKind3.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); -}; - -class ZodDate3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.date, - received: ctx2.parsedType - }); - return INVALID2; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode3.invalid_date - }); - return INVALID2; - } - const status = new ParseStatus2; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.getTime() < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - message: check2.message, - inclusive: true, - exact: false, - minimum: check2.value, - type: "date" - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.getTime() > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - message: check2.message, - inclusive: true, - exact: false, - maximum: check2.value, - type: "date" - }); - status.dirty(); - } - } else { - util2.assertNever(check2); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check2) { - return new ZodDate3({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil2.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil2.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate3.create = (params) => { - return new ZodDate3({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind3.ZodDate, - ...processCreateParams2(params) - }); -}; - -class ZodSymbol3 extends ZodType3 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.symbol, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodSymbol3.create = (params) => { - return new ZodSymbol3({ - typeName: ZodFirstPartyTypeKind3.ZodSymbol, - ...processCreateParams2(params) - }); -}; - -class ZodUndefined3 extends ZodType3 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.undefined, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodUndefined3.create = (params) => { - return new ZodUndefined3({ - typeName: ZodFirstPartyTypeKind3.ZodUndefined, - ...processCreateParams2(params) - }); -}; - -class ZodNull3 extends ZodType3 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.null, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodNull3.create = (params) => { - return new ZodNull3({ - typeName: ZodFirstPartyTypeKind3.ZodNull, - ...processCreateParams2(params) - }); -}; - -class ZodAny3 extends ZodType3 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK2(input.data); - } -} -ZodAny3.create = (params) => { - return new ZodAny3({ - typeName: ZodFirstPartyTypeKind3.ZodAny, - ...processCreateParams2(params) - }); -}; - -class ZodUnknown3 extends ZodType3 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK2(input.data); - } -} -ZodUnknown3.create = (params) => { - return new ZodUnknown3({ - typeName: ZodFirstPartyTypeKind3.ZodUnknown, - ...processCreateParams2(params) - }); -}; - -class ZodNever3 extends ZodType3 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.never, - received: ctx.parsedType - }); - return INVALID2; - } -} -ZodNever3.create = (params) => { - return new ZodNever3({ - typeName: ZodFirstPartyTypeKind3.ZodNever, - ...processCreateParams2(params) - }); -}; - -class ZodVoid3 extends ZodType3 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.void, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodVoid3.create = (params) => { - return new ZodVoid3({ - typeName: ZodFirstPartyTypeKind3.ZodVoid, - ...processCreateParams2(params) - }); -}; - -class ZodArray3 extends ZodType3 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext2(ctx, { - code: tooBig ? ZodIssueCode3.too_big : ZodIssueCode3.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus2.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - }); - return ParseStatus2.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray3({ - ...this._def, - minLength: { value: minLength, message: errorUtil2.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray3({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil2.toString(message) } - }); - } - length(len, message) { - return new ZodArray3({ - ...this._def, - exactLength: { value: len, message: errorUtil2.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray3.create = (schema, params) => { - return new ZodArray3({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind3.ZodArray, - ...processCreateParams2(params) - }); -}; -function deepPartialify2(schema) { - if (schema instanceof ZodObject3) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional3.create(deepPartialify2(fieldSchema)); - } - return new ZodObject3({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray3) { - return new ZodArray3({ - ...schema._def, - type: deepPartialify2(schema.element) - }); - } else if (schema instanceof ZodOptional3) { - return ZodOptional3.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodNullable3) { - return ZodNullable3.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodTuple3) { - return ZodTuple3.create(schema.items.map((item) => deepPartialify2(item))); - } else { - return schema; - } -} - -class ZodObject3 extends ZodType3 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util2.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.object, - received: ctx2.parsedType - }); - return INVALID2; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever3 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever3) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus2.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus2.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil2.errToObj; - return new ZodObject3({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue2, ctx) => { - const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; - if (issue2.code === "unrecognized_keys") - return { - message: errorUtil2.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject3({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject3({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject3({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject3({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind3.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject3({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util2.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject3({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject3({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify2(this); - } - partial(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject3({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional3) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject3({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum2(util2.objectKeys(this.shape)); - } -} -ZodObject3.create = (shape, params) => { - return new ZodObject3({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams2(params) - }); -}; -ZodObject3.strictCreate = (shape, params) => { - return new ZodObject3({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams2(params) - }); -}; -ZodObject3.lazycreate = (shape, params) => { - return new ZodObject3({ - shape, - unknownKeys: "strip", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams2(params) - }); -}; - -class ZodUnion3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError3(result.ctx.common.issues)); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_union, - unionErrors - }); - return INVALID2; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError3(issues2)); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_union, - unionErrors - }); - return INVALID2; - } - } - get options() { - return this._def.options; - } -} -ZodUnion3.create = (types, params) => { - return new ZodUnion3({ - options: types, - typeName: ZodFirstPartyTypeKind3.ZodUnion, - ...processCreateParams2(params) - }); -}; -var getDiscriminator2 = (type) => { - if (type instanceof ZodLazy3) { - return getDiscriminator2(type.schema); - } else if (type instanceof ZodEffects2) { - return getDiscriminator2(type.innerType()); - } else if (type instanceof ZodLiteral3) { - return [type.value]; - } else if (type instanceof ZodEnum3) { - return type.options; - } else if (type instanceof ZodNativeEnum2) { - return util2.objectValues(type.enum); - } else if (type instanceof ZodDefault3) { - return getDiscriminator2(type._def.innerType); - } else if (type instanceof ZodUndefined3) { - return [undefined]; - } else if (type instanceof ZodNull3) { - return [null]; - } else if (type instanceof ZodOptional3) { - return [undefined, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodNullable3) { - return [null, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodBranded2) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodReadonly3) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodCatch3) { - return getDiscriminator2(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID2; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator2(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion3({ - typeName: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams2(params) - }); - } -} -function mergeValues3(a, b) { - const aType = getParsedType3(a); - const bType = getParsedType3(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) { - const bKeys = util2.objectKeys(b); - const sharedKeys = util2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues3(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues3(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted2(parsedLeft) || isAborted2(parsedRight)) { - return INVALID2; - } - const merged = mergeValues3(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_intersection_types - }); - return INVALID2; - } - if (isDirty2(parsedLeft) || isDirty2(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection3.create = (left, right, params) => { - return new ZodIntersection3({ - left, - right, - typeName: ZodFirstPartyTypeKind3.ZodIntersection, - ...processCreateParams2(params) - }); -}; - -class ZodTuple3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID2; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath2(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus2.mergeArray(status, results); - }); - } else { - return ParseStatus2.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple3({ - ...this._def, - rest - }); - } -} -ZodTuple3.create = (schemas3, params) => { - if (!Array.isArray(schemas3)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple3({ - items: schemas3, - typeName: ZodFirstPartyTypeKind3.ZodTuple, - rest: null, - ...processCreateParams2(params) - }); -}; - -class ZodRecord3 extends ZodType3 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus2.mergeObjectAsync(status, pairs); - } else { - return ParseStatus2.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType3) { - return new ZodRecord3({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams2(third) - }); - } - return new ZodRecord3({ - keyType: ZodString3.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams2(second) - }); - } -} - -class ZodMap3 extends ZodType3 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.map) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.map, - received: ctx.parsedType - }); - return INVALID2; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap3.create = (keyType, valueType, params) => { - return new ZodMap3({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind3.ZodMap, - ...processCreateParams2(params) - }); -}; - -class ZodSet3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.set) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.set, - received: ctx.parsedType - }); - return INVALID2; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID2; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet3({ - ...this._def, - minSize: { value: minSize, message: errorUtil2.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet3({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil2.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet3.create = (valueType, params) => { - return new ZodSet3({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind3.ZodSet, - ...processCreateParams2(params) - }); -}; - -class ZodFunction3 extends ZodType3 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.function) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.function, - received: ctx.parsedType - }); - return INVALID2; - } - function makeArgsIssue(args, error51) { - return makeIssue2({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap3(), en_default3].filter((x) => !!x), - issueData: { - code: ZodIssueCode3.invalid_arguments, - argumentsError: error51 - } - }); - } - function makeReturnsIssue(returns, error51) { - return makeIssue2({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap3(), en_default3].filter((x) => !!x), - issueData: { - code: ZodIssueCode3.invalid_return_type, - returnTypeError: error51 - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise3) { - const me = this; - return OK2(async function(...args) { - const error51 = new ZodError3([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error51.addIssue(makeArgsIssue(args, e)); - throw error51; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error51.addIssue(makeReturnsIssue(result, e)); - throw error51; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK2(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError3([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError3([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction3({ - ...this._def, - args: ZodTuple3.create(items).rest(ZodUnknown3.create()) - }); - } - returns(returnType) { - return new ZodFunction3({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction3({ - args: args ? args : ZodTuple3.create([]).rest(ZodUnknown3.create()), - returns: returns || ZodUnknown3.create(), - typeName: ZodFirstPartyTypeKind3.ZodFunction, - ...processCreateParams2(params) - }); - } -} - -class ZodLazy3 extends ZodType3 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy3.create = (getter, params) => { - return new ZodLazy3({ - getter, - typeName: ZodFirstPartyTypeKind3.ZodLazy, - ...processCreateParams2(params) - }); -}; - -class ZodLiteral3 extends ZodType3 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_literal, - expected: this._def.value - }); - return INVALID2; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral3.create = (value, params) => { - return new ZodLiteral3({ - value, - typeName: ZodFirstPartyTypeKind3.ZodLiteral, - ...processCreateParams2(params) - }); -}; -function createZodEnum2(values, params) { - return new ZodEnum3({ - values, - typeName: ZodFirstPartyTypeKind3.ZodEnum, - ...processCreateParams2(params) - }); -} - -class ZodEnum3 extends ZodType3 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode3.invalid_type - }); - return INVALID2; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_enum_value, - options: expectedValues - }); - return INVALID2; - } - return OK2(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum3.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum3.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum3.create = createZodEnum2; - -class ZodNativeEnum2 extends ZodType3 { - _parse(input) { - const nativeEnumValues = util2.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode3.invalid_type - }); - return INVALID2; - } - if (!this._cache) { - this._cache = new Set(util2.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_enum_value, - options: expectedValues - }); - return INVALID2; - } - return OK2(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum2.create = (values, params) => { - return new ZodNativeEnum2({ - values, - typeName: ZodFirstPartyTypeKind3.ZodNativeEnum, - ...processCreateParams2(params) - }); -}; - -class ZodPromise3 extends ZodType3 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) { - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.promise, - received: ctx.parsedType - }); - return INVALID2; - } - const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data); - return OK2(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise3.create = (schema, params) => { - return new ZodPromise3({ - type: schema, - typeName: ZodFirstPartyTypeKind3.ZodPromise, - ...processCreateParams2(params) - }); -}; - -class ZodEffects2 extends ZodType3 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext2(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID2; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID2; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid2(base)) - return INVALID2; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid2(base)) - return INVALID2; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util2.assertNever(effect); - } -} -ZodEffects2.create = (schema, effect, params) => { - return new ZodEffects2({ - schema, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect, - ...processCreateParams2(params) - }); -}; -ZodEffects2.createWithPreprocess = (preprocess2, schema, params) => { - return new ZodEffects2({ - schema, - effect: { type: "preprocess", transform: preprocess2 }, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - ...processCreateParams2(params) - }); -}; - -class ZodOptional3 extends ZodType3 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType2.undefined) { - return OK2(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional3.create = (type, params) => { - return new ZodOptional3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodOptional, - ...processCreateParams2(params) - }); -}; - -class ZodNullable3 extends ZodType3 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType2.null) { - return OK2(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable3.create = (type, params) => { - return new ZodNullable3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodNullable, - ...processCreateParams2(params) - }); -}; - -class ZodDefault3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType2.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault3.create = (type, params) => { - return new ZodDefault3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams2(params) - }); -}; - -class ZodCatch3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync2(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError3(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError3(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch3.create = (type, params) => { - return new ZodCatch3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams2(params) - }); -}; - -class ZodNaN3 extends ZodType3 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType2.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType2.nan, - received: ctx.parsedType - }); - return INVALID2; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN3.create = (params) => { - return new ZodNaN3({ - typeName: ZodFirstPartyTypeKind3.ZodNaN, - ...processCreateParams2(params) - }); -}; -var BRAND2 = Symbol("zod_brand"); - -class ZodBranded2 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline2 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY2(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline2({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind3.ZodPipeline - }); - } -} - -class ZodReadonly3 extends ZodType3 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid2(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync2(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly3.create = (type, params) => { - return new ZodReadonly3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodReadonly, - ...processCreateParams2(params) - }); -}; -function cleanParams2(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom3(check2, _params = {}, fatal) { - if (check2) - return ZodAny3.create().superRefine((data, ctx) => { - const r = check2(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny3.create(); -} -var late2 = { - object: ZodObject3.lazycreate -}; -var ZodFirstPartyTypeKind3; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind3 || (ZodFirstPartyTypeKind3 = {})); -var instanceOfType2 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom3((data) => data instanceof cls, params); -var stringType2 = ZodString3.create; -var numberType2 = ZodNumber3.create; -var nanType2 = ZodNaN3.create; -var bigIntType2 = ZodBigInt3.create; -var booleanType2 = ZodBoolean3.create; -var dateType2 = ZodDate3.create; -var symbolType2 = ZodSymbol3.create; -var undefinedType2 = ZodUndefined3.create; -var nullType2 = ZodNull3.create; -var anyType2 = ZodAny3.create; -var unknownType2 = ZodUnknown3.create; -var neverType2 = ZodNever3.create; -var voidType2 = ZodVoid3.create; -var arrayType2 = ZodArray3.create; -var objectType2 = ZodObject3.create; -var strictObjectType2 = ZodObject3.strictCreate; -var unionType2 = ZodUnion3.create; -var discriminatedUnionType2 = ZodDiscriminatedUnion3.create; -var intersectionType2 = ZodIntersection3.create; -var tupleType2 = ZodTuple3.create; -var recordType2 = ZodRecord3.create; -var mapType2 = ZodMap3.create; -var setType2 = ZodSet3.create; -var functionType2 = ZodFunction3.create; -var lazyType2 = ZodLazy3.create; -var literalType2 = ZodLiteral3.create; -var enumType2 = ZodEnum3.create; -var nativeEnumType2 = ZodNativeEnum2.create; -var promiseType2 = ZodPromise3.create; -var effectsType2 = ZodEffects2.create; -var optionalType2 = ZodOptional3.create; -var nullableType2 = ZodNullable3.create; -var preprocessType2 = ZodEffects2.createWithPreprocess; -var pipelineType2 = ZodPipeline2.create; -var ostring2 = () => stringType2().optional(); -var onumber2 = () => numberType2().optional(); -var oboolean2 = () => booleanType2().optional(); -var coerce2 = { - string: (arg) => ZodString3.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber3.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean3.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt3.create({ ...arg, coerce: true }), - date: (arg) => ZodDate3.create({ ...arg, coerce: true }) -}; -var NEVER3 = INVALID2; -var SCHEMA_IDS2 = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema2 = exports_external3.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema2 = exports_external3.string().datetime(); -var NonEmptyStringSchema2 = exports_external3.string().trim().min(1); -var UriSchema2 = NonEmptyStringSchema2.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema2 = exports_external3.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema2 = exports_external3.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema2 = exports_external3.record(exports_external3.unknown()); -var TagsSchema2 = exports_external3.array(exports_external3.string().min(1)).default([]); -var OptionalTimestampSchema2 = TimestampSchema2.nullable().optional(); -var TerminalStatuses2 = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema2 = exports_external3.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema2(schema) { - return exports_external3.object({ - schema: exports_external3.literal(schema), - id: exports_external3.string().min(1), - createdAt: TimestampSchema2, - updatedAt: OptionalTimestampSchema2, - metadata: MetadataSchema2.optional() - }).strict(); -} -var ContractEnvelopeSchema2 = exports_external3.object({ - schema: SchemaIdSchema2, - id: exports_external3.string().min(1), - createdAt: TimestampSchema2, - updatedAt: OptionalTimestampSchema2, - metadata: MetadataSchema2.optional() -}).strict(); -var ActorKindSchema2 = exports_external3.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.actorRef).extend({ - kind: ActorKindSchema2, - name: exports_external3.string().min(1).optional(), - provider: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - machineId: exports_external3.string().min(1).optional(), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema2 = exports_external3.object({ - kind: ActorKindSchema2, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - provider: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - machineId: exports_external3.string().min(1).optional() -}).strict(); -var ResourceKindSchema2 = exports_external3.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.resourceRef).extend({ - kind: ResourceKindSchema2, - name: exports_external3.string().min(1).optional(), - uri: UriSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema2 = exports_external3.object({ - kind: ResourceKindSchema2, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - uri: UriSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema2 = exports_external3.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema2 = exports_external3.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.evidenceRef).extend({ - kind: EvidenceKindSchema2, - uri: UriSchema2, - sha256: Sha256DigestSchema2.optional(), - summary: exports_external3.string().min(1).optional(), - contentType: exports_external3.string().min(1).optional(), - sizeBytes: exports_external3.number().int().nonnegative().optional(), - redaction: RedactionStateSchema2.default("unknown"), - producer: ActorPointerSchema2.optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - tags: TagsSchema2 -}).strict(); -var EvidencePointerSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: EvidenceKindSchema2.optional(), - uri: UriSchema2.optional(), - sha256: Sha256DigestSchema2.optional(), - summary: exports_external3.string().min(1).optional() -}).strict(); -var CostEstimateSchema2 = contractBaseSchema2(SCHEMA_IDS2.costEstimate).extend({ - currency: exports_external3.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external3.number().int().nonnegative(), - provider: exports_external3.string().min(1).optional(), - model: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - promptTokens: exports_external3.number().int().nonnegative().optional(), - completionTokens: exports_external3.number().int().nonnegative().optional(), - totalTokens: exports_external3.number().int().nonnegative().optional(), - basis: exports_external3.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema2 = exports_external3.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema2 = contractBaseSchema2(SCHEMA_IDS2.decisionEnvelope).extend({ - decisionType: exports_external3.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema2, - actor: ActorPointerSchema2.optional(), - traceId: exports_external3.string().min(1).optional(), - inputHash: HashStringSchema2.optional(), - policyBundleId: exports_external3.string().min(1).optional(), - selected: exports_external3.array(ResourcePointerSchema2).default([]), - skipped: exports_external3.array(ResourcePointerSchema2).default([]), - reason: exports_external3.string().min(1), - obligations: exports_external3.array(exports_external3.string().min(1)).default([]), - redactions: exports_external3.array(exports_external3.string().min(1)).default([]), - costEstimate: CostEstimateSchema2.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema2 = contractBaseSchema2(SCHEMA_IDS2.capabilityCard).extend({ - kind: exports_external3.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external3.string().min(1), - version: exports_external3.string().min(1).optional(), - status: exports_external3.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]), - limitations: exports_external3.array(exports_external3.string().min(1)).default([]), - riskLevel: exports_external3.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema2.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict(); -var ProviderModeSchema2 = exports_external3.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema2 = exports_external3.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema2 = exports_external3.object({ - refName: NonEmptyStringSchema2, - requiredForModes: exports_external3.array(ProviderModeSchema2).min(1), - allowedSecretInputs: exports_external3.array(exports_external3.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema2, - revocationCheck: exports_external3.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema2 = exports_external3.object({ - operation: NonEmptyStringSchema2, - supportedModes: exports_external3.array(ProviderModeSchema2).min(1), - sideEffectClass: ProviderSideEffectClassSchema2, - requiresApproval: exports_external3.boolean().default(false), - requiresIdempotencyKey: exports_external3.boolean().default(false), - requiresSandboxEvidence: exports_external3.boolean().default(false), - requiresRollbackOrRevocation: exports_external3.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema2.optional(), - noSideEffectSmoke: NonEmptyStringSchema2.optional(), - reconciliation: NonEmptyStringSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema2 = exports_external3.object({ - providerId: NonEmptyStringSchema2, - appId: NonEmptyStringSchema2, - adapterId: NonEmptyStringSchema2, - ownerPackage: NonEmptyStringSchema2, - modes: exports_external3.array(ProviderModeSchema2).min(1), - defaultMode: ProviderModeSchema2, - credentialRequirements: exports_external3.array(CredentialRequirementSchema2).default([]), - operations: exports_external3.array(ProviderOperationCardSchema2).min(1), - rateLimitPosture: NonEmptyStringSchema2, - costPosture: NonEmptyStringSchema2.optional(), - auditEvents: exports_external3.array(NonEmptyStringSchema2).default([]), - redactionRules: exports_external3.array(NonEmptyStringSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema2 = exports_external3.object({ - appId: NonEmptyStringSchema2, - repo: NonEmptyStringSchema2, - priority: exports_external3.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external3.array(NonEmptyStringSchema2).min(1), - firstOperations: exports_external3.array(NonEmptyStringSchema2).min(1), - blockedUntil: exports_external3.array(NonEmptyStringSchema2).default([]) -}).strict(); -var ProviderLiveModeStandardSchema2 = contractBaseSchema2(SCHEMA_IDS2.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema2, - version: NonEmptyStringSchema2, - modes: exports_external3.array(ProviderModeSchema2).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external3.array(NonEmptyStringSchema2).min(1), - liveMutationGate: exports_external3.object({ - requiredMode: exports_external3.literal("live_mutating"), - requiredChecks: exports_external3.array(NonEmptyStringSchema2).min(1), - forbiddenBypassSignals: exports_external3.array(NonEmptyStringSchema2).min(1), - disabledLiveSmoke: NonEmptyStringSchema2 - }).strict(), - noSideEffectSmoke: exports_external3.object({ - requiredForModes: exports_external3.array(ProviderModeSchema2).min(1), - commandEvidence: exports_external3.array(NonEmptyStringSchema2).min(1), - secretOutputScan: exports_external3.boolean().default(true) - }).strict(), - credentialPolicy: exports_external3.object({ - acceptedInputs: exports_external3.array(exports_external3.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external3.literal(false), - missingCredentialBehavior: exports_external3.literal("fail_closed"), - revocationCheckRequired: exports_external3.boolean().default(true) - }).strict(), - operationCards: exports_external3.array(ProviderCapabilityCardSchema2).min(1), - firstAdoptionTargets: exports_external3.array(ProviderLiveModeTargetSchema2).min(1), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1).optional(), - summary: exports_external3.string().min(1), - text: exports_external3.string().optional(), - tokens: exports_external3.number().int().nonnegative().optional(), - source: EvidencePointerSchema2, - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]) -}).strict(); -var ContextPackSchema2 = contractBaseSchema2(SCHEMA_IDS2.contextPack).extend({ - objective: exports_external3.string().min(1), - budget: exports_external3.object({ - maxTokens: exports_external3.number().int().positive().optional(), - maxBytes: exports_external3.number().int().positive().optional() - }).strict().optional(), - items: exports_external3.array(ContextPackItemSchema2).default([]), - citations: exports_external3.array(EvidencePointerSchema2).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external3.array(exports_external3.string().min(1)).default([]), - redactions: exports_external3.array(exports_external3.string().min(1)).default([]), - conflicts: exports_external3.array(exports_external3.string().min(1)).default([]), - uncertainty: exports_external3.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema2 = NonEmptyStringSchema2.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema2 = exports_external3.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema2 = exports_external3.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema2 = exports_external3.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema2 = exports_external3.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.integrationRef).extend({ - kind: ProjectIntegrationKindSchema2, - name: exports_external3.string().min(1), - projectId: ProjectSlugSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - uri: UriSchema2.optional(), - enabled: exports_external3.boolean().default(true), - readOnly: exports_external3.boolean().default(true), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema2.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - config: MetadataSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema2 = exports_external3.object({ - schemaRoot: RelativeProjectPathSchema2.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema2.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema2.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema2.default("documents"), - reportsDir: RelativeProjectPathSchema2.default("reports"), - evidenceDir: RelativeProjectPathSchema2.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema2.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectManifest).extend({ - projectId: ProjectSlugSchema2, - slug: ProjectSlugSchema2, - name: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - status: ProjectStatusSchema2.default("active"), - classification: ProjectClassificationSchema2.default("private"), - owner: ActorPointerSchema2.optional(), - layout: ProjectLayoutSchema2.default({}), - integrations: exports_external3.array(IntegrationRefSchema2).default([]), - renderManifests: exports_external3.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema2 = exports_external3.enum(["local", "package", "provider", "url"]); -var RenderImportSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: RenderImportKindSchema2, - specifier: exports_external3.string().min(1), - path: RelativeProjectPathSchema2.optional(), - packageName: exports_external3.string().min(1).optional(), - uri: UriSchema2.optional(), - provider: ProjectIntegrationKindSchema2.optional(), - schemaId: SchemaIdSchema2.optional(), - integrity: HashStringSchema2.optional(), - resourceRef: ResourcePointerSchema2.optional(), - optional: exports_external3.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema2 = exports_external3.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1), - kind: RenderViewKindSchema2, - default: exports_external3.boolean().default(false), - entry: RelativeProjectPathSchema2.optional(), - imports: exports_external3.array(RenderImportSchema2).default([]), - panelRefs: exports_external3.array(ResourcePointerSchema2).default([]), - dataRefs: exports_external3.array(ResourcePointerSchema2).default([]), - layout: MetadataSchema2.optional() -}).strict(); -var RenderManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.renderManifest).extend({ - projectId: ProjectSlugSchema2, - name: exports_external3.string().min(1), - version: exports_external3.string().min(1), - manifestPath: RelativeProjectPathSchema2.default(".hasna/project/dashboard.render.json"), - renderer: exports_external3.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external3.array(RenderViewSchema2).min(1), - imports: exports_external3.array(RenderImportSchema2).default([]), - theme: MetadataSchema2.optional(), - compatibility: exports_external3.object({ - minProjectsVersion: exports_external3.string().min(1).optional(), - minContractsVersion: exports_external3.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema2 = exports_external3.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema2 = exports_external3.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - label: exports_external3.string().min(1), - value: exports_external3.union([exports_external3.string(), exports_external3.number(), exports_external3.boolean()]), - unit: exports_external3.string().min(1).optional(), - status: exports_external3.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]) -}).strict(); -var ProjectPanelItemSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - status: exports_external3.string().min(1).optional(), - priority: exports_external3.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema2.optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - metadata: MetadataSchema2.optional() -}).strict(); -var ProjectRenderFragmentSchema2 = exports_external3.object({ - renderer: exports_external3.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external3.string().min(1).optional(), - entry: RelativeProjectPathSchema2.optional(), - imports: exports_external3.array(RenderImportSchema2).default([]), - spec: MetadataSchema2.default({}) -}).strict(); -var ProjectPanelSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectPanel).extend({ - projectId: ProjectSlugSchema2, - provider: exports_external3.object({ - kind: ProjectIntegrationKindSchema2, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - externalId: NonEmptyStringSchema2.optional() - }).strict(), - kind: ProjectPanelKindSchema2, - title: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - state: ProjectPanelStateSchema2.default("ready"), - stateReason: exports_external3.string().min(1).optional(), - generatedAt: TimestampSchema2, - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external3.array(ProjectPanelMetricSchema2).default([]), - items: exports_external3.array(ProjectPanelItemSchema2).default([]), - actions: exports_external3.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - renderFragment: ProjectRenderFragmentSchema2.optional(), - warnings: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectSnapshot).extend({ - projectId: ProjectSlugSchema2, - generatedAt: TimestampSchema2, - status: ContractStatusSchema2.default("unknown"), - manifestRef: ResourcePointerSchema2, - renderManifestRef: ResourcePointerSchema2.optional(), - panels: exports_external3.array(ProjectPanelSchema2).default([]), - contextPacks: exports_external3.array(ContextPackSchema2).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - warnings: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: exports_external3.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external3.boolean().default(true), - command: exports_external3.string().min(1).optional(), - expected: exports_external3.string().min(1).optional(), - timeoutMs: exports_external3.number().int().positive().optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema2 = contractBaseSchema2(SCHEMA_IDS2.validationPlan).extend({ - objective: exports_external3.string().min(1), - subject: ResourcePointerSchema2.optional(), - checks: exports_external3.array(ValidationCheckSchema2).min(1), - verifier: ActorPointerSchema2.optional(), - requiredEvidenceKinds: exports_external3.array(EvidenceKindSchema2).default([]) -}).strict(); -var ScaffoldTypeSchema2 = exports_external3.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema2 = exports_external3.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema2 = exports_external3.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema2 = exports_external3.object({ - key: exports_external3.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external3.string().min(1), - required: exports_external3.boolean().default(false), - ["secret"]: exports_external3.boolean().default(false), - group: exports_external3.string().min(1).optional(), - default: exports_external3.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema2 = exports_external3.object({ - name: exports_external3.string().min(1), - command: exports_external3.string().min(1), - description: exports_external3.string().min(1).optional(), - required: exports_external3.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema2 = exports_external3.object({ - packageManager: exports_external3.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external3.array(exports_external3.string().min(1)).default([]), - requiredFiles: exports_external3.array(exports_external3.string().min(1)).default([]), - requiredDirectories: exports_external3.array(exports_external3.string().min(1)).default([]), - optionalDirectories: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.scaffoldManifest).extend({ - name: exports_external3.string().min(1), - version: exports_external3.string().min(1), - summary: exports_external3.string().min(1), - type: ScaffoldTypeSchema2, - status: ScaffoldStatusSchema2.default("draft"), - capabilities: exports_external3.array(ScaffoldCapabilitySchema2).default([]), - techStack: exports_external3.array(exports_external3.string().min(1)).default([]), - tags: TagsSchema2, - source: ResourcePointerSchema2.optional(), - output: ScaffoldOutputShapeSchema2, - env: exports_external3.array(ScaffoldEnvVarSchema2).default([]), - scripts: exports_external3.array(ScaffoldScriptSchema2).default([]), - validationChecks: exports_external3.array(ValidationCheckSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema2 = exports_external3.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema2 = contractBaseSchema2(SCHEMA_IDS2.scaffoldInstallRecord).extend({ - scaffoldId: exports_external3.string().min(1), - scaffoldVersion: exports_external3.string().min(1).optional(), - manifestRef: ResourcePointerSchema2.optional(), - target: ResourcePointerSchema2, - status: ScaffoldInstallStatusSchema2, - installedAt: TimestampSchema2.optional(), - installer: ActorPointerSchema2.optional(), - packageManager: exports_external3.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema2.optional(), - generatedFiles: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema2 = exports_external3.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema2 = exports_external3.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema2 = exports_external3.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema2 = exports_external3.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema2 = NonEmptyStringSchema2.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema2 = exports_external3.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema2 = exports_external3.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema2 = exports_external3.object({ - transport: exports_external3.enum(["http", "stdio"]).default("http"), - bin: exports_external3.string().min(1).optional(), - url: UriSchema2.optional() -}).strict(); -var AppHttpSurfaceSchema2 = exports_external3.object({ - healthPath: exports_external3.string().min(1).default("/health"), - port: exports_external3.number().int().positive().optional(), - baseUrl: UriSchema2.optional() -}).strict(); -var AppSurfacesSchema2 = exports_external3.object({ - bins: exports_external3.array(exports_external3.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema2.optional(), - http: AppHttpSurfaceSchema2.optional() -}).strict(); -var AppSchema2 = contractBaseSchema2(SCHEMA_IDS2.app).extend({ - appId: AppIdSchema2, - npmName: NpmPackageNameSchema2, - repoFolder: AppIdSchema2, - githubUrl: GithubUrlSchema2, - projectSlug: ProjectSlugSchema2, - surfaces: AppSurfacesSchema2.default({}), - lifecycle: AppLifecycleSchema2, - releaseChannel: ReleaseChannelSchema2.default("stable"), - summary: exports_external3.string().min(1).optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema2 = exports_external3.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema2 = contractBaseSchema2(SCHEMA_IDS2.release).extend({ - appId: AppIdSchema2, - package: NpmPackageNameSchema2, - version: SemverSchema2, - gitSha: GitShaSchema2, - publishedAt: TimestampSchema2, - publishPath: PublishPathSchema2, - changelogRef: ResourcePointerSchema2.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema2 = exports_external3.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema2 = exports_external3.object({ - cliVersion: exports_external3.string().min(1).optional(), - mcpHealth: exports_external3.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema2 = contractBaseSchema2(SCHEMA_IDS2.rolloutRecord).extend({ - appId: AppIdSchema2, - package: NpmPackageNameSchema2, - version: SemverSchema2, - machine: NonEmptyStringSchema2, - action: RolloutActionSchema2, - result: ContractStatusSchema2, - verifiedBy: RolloutVerificationSchema2.optional(), - at: TimestampSchema2, - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema2 = exports_external3.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema2 = exports_external3.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema2 = exports_external3.object({ - channel: AnnouncementChannelKindSchema2, - status: AnnouncementDeliveryStatusSchema2, - deliveredAt: TimestampSchema2.optional(), - detail: exports_external3.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema2 = contractBaseSchema2(SCHEMA_IDS2.announcement).extend({ - campaignId: NonEmptyStringSchema2, - appId: AppIdSchema2.optional(), - releaseRef: ResourcePointerSchema2.optional(), - channels: exports_external3.array(AnnouncementChannelSchema2).min(1), - audienceRef: ResourcePointerSchema2, - sentAt: TimestampSchema2 -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema2 = exports_external3.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema2 = exports_external3.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema2 = exports_external3.union([exports_external3.string(), exports_external3.number(), exports_external3.boolean()]); -var AudiencePredicateSchema2 = exports_external3.object({ - kind: AudiencePredicateKindSchema2, - key: exports_external3.string().min(1).optional(), - op: AudiencePredicateOpSchema2.default("eq"), - value: AudiencePredicateValueSchema2.optional(), - values: exports_external3.array(AudiencePredicateValueSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema2 = exports_external3.object({ - match: exports_external3.enum(["all", "any"]).default("all"), - predicates: exports_external3.array(AudiencePredicateSchema2).min(1) -}).strict(); -var ConsentPolicySchema2 = exports_external3.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema2 = contractBaseSchema2(SCHEMA_IDS2.audience).extend({ - audienceId: AppIdSchema2, - name: NonEmptyStringSchema2, - definition: AudienceDefinitionSchema2, - consentPolicy: ConsentPolicySchema2, - suppressionSyncedAt: OptionalTimestampSchema2 -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES2 = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema2 = exports_external3.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - provider: AppCloudProviderSchema2, - kind: exports_external3.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external3.string().min(1), - region: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - uri: UriSchema2.optional(), - machineScoped: exports_external3.boolean().default(false) -}).strict(); -var AppCloudManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.appCloudManifest).extend({ - packageName: exports_external3.string().min(1), - packageVersion: exports_external3.string().min(1).optional(), - appId: exports_external3.string().min(1), - repository: ResourcePointerSchema2.optional(), - storageMode: exports_external3.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external3.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external3.array(AppCloudResourceSchema2).default([]), - localCache: exports_external3.object({ - path: exports_external3.string().min(1).optional(), - pullMode: exports_external3.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external3.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external3.array(exports_external3.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES2]), - dependencies: exports_external3.array(exports_external3.string().min(1)).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES2, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES2) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema2 = exports_external3.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema2 = exports_external3.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: NoCloudCheckKindSchema2, - severity: NoCloudFindingSeveritySchema2, - path: exports_external3.string().min(1).optional(), - packageName: exports_external3.string().min(1).optional(), - pattern: exports_external3.string().min(1), - message: exports_external3.string().min(1), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict(); -var NoCloudCheckResultSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: NoCloudCheckKindSchema2, - status: ContractStatusSchema2, - target: exports_external3.string().min(1), - command: exports_external3.string().min(1).optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - findings: exports_external3.array(NoCloudFindingSchema2).default([]) -}).strict(); -var NoCloudEvidencePackSchema2 = contractBaseSchema2(SCHEMA_IDS2.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema2, - packageName: exports_external3.string().min(1).optional(), - packageVersion: exports_external3.string().min(1).optional(), - generatedBy: ActorPointerSchema2.optional(), - scanMode: exports_external3.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema2, - verdict: exports_external3.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema2.optional(), - checks: exports_external3.array(NoCloudCheckResultSchema2).min(1), - findings: exports_external3.array(NoCloudFindingSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check2) => check2.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check2) => check2.status !== "succeeded")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check2) => check2.status === "failed")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check2, index) => { - const checkBlockingFindings = check2.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check2.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema2 = exports_external3.object({ - checkId: exports_external3.string().min(1), - status: ContractStatusSchema2, - summary: exports_external3.string().min(1).optional(), - startedAt: OptionalTimestampSchema2, - finishedAt: OptionalTimestampSchema2, - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict(); -var ProofBundleSchema2 = contractBaseSchema2(SCHEMA_IDS2.proofBundle).extend({ - subject: ResourcePointerSchema2, - validationPlanRef: ResourcePointerSchema2.optional(), - status: ContractStatusSchema2, - verdict: exports_external3.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external3.array(ProofCheckResultSchema2).default([]), - verifier: ActorPointerSchema2.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - residualRisks: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check2, index) => { - if (check2.status !== "succeeded") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check2) => check2.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check2) => check2.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema2 = contractBaseSchema2(SCHEMA_IDS2.workRun).extend({ - objective: exports_external3.string().min(1), - status: ContractStatusSchema2, - actor: ActorPointerSchema2, - traceId: exports_external3.string().min(1).optional(), - startedAt: OptionalTimestampSchema2, - finishedAt: OptionalTimestampSchema2, - constraints: exports_external3.array(exports_external3.string().min(1)).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - decisions: exports_external3.array(DecisionEnvelopeSchema2).default([]), - costEstimates: exports_external3.array(CostEstimateSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - validationPlanRefs: exports_external3.array(ResourcePointerSchema2).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses2.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - at: TimestampSchema2, - kind: exports_external3.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external3.string().min(1), - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]), - costEstimate: CostEstimateSchema2.optional() -}).strict(); -var AgentTrajectorySchema2 = contractBaseSchema2(SCHEMA_IDS2.agentTrajectory).extend({ - actor: ActorPointerSchema2, - workRunRef: ResourcePointerSchema2.optional(), - events: exports_external3.array(TrajectoryEventSchema2).default([]), - outcome: exports_external3.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema2.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION2 = "v1"; -var RepoClassSchema2 = exports_external3.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES2 = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema2 = exports_external3.enum(DEPLOYMENT_MODES2); -var ServiceSurfaceStatusSchema2 = exports_external3.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema2 = exports_external3.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema2 = exports_external3.object({ - method: exports_external3.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external3.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external3.boolean().default(false), - description: exports_external3.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema2 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: exports_external3.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external3.boolean().default(true), - command: exports_external3.string().min(1).optional(), - evidenceRef: EvidencePointerSchema2.optional(), - status: exports_external3.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external3.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema2 = exports_external3.object({ - name: exports_external3.string().min(1), - status: ServiceSurfaceStatusSchema2, - bin: exports_external3.string().min(1).optional(), - mcpBin: exports_external3.string().min(1).optional(), - authMode: ServiceAuthModeSchema2, - deploymentModes: exports_external3.array(DeploymentModeSchema2).min(1), - health: ServiceEndpointSchema2.optional(), - readiness: ServiceEndpointSchema2.optional(), - version: ServiceEndpointSchema2.optional(), - apiBasePath: exports_external3.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external3.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external3.string().min(1).optional(), - readinessGates: exports_external3.array(DeploymentReadinessGateSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES2 = ["local", "cloud"]; -var StorageModeSchema2 = exports_external3.enum(STORAGE_MODES2); -var AppNameSchema2 = exports_external3.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES2 = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName2(name) { - return ALLOWED_BIN_SUFFIXES2.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor2(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema2 = exports_external3.object({ - mode: StorageModeSchema2, - envPrefix: exports_external3.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external3.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external3.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external3.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema2 = exports_external3.object({ - $schema: exports_external3.string().min(1).optional(), - schema: exports_external3.literal(SCHEMA_IDS2.serviceContract), - name: AppNameSchema2, - class: RepoClassSchema2, - contractVersion: exports_external3.literal(SERVICE_CONTRACT_VERSION2), - kitVersion: exports_external3.string().min(1), - description: exports_external3.string().min(1).optional(), - bins: exports_external3.array(exports_external3.string().min(1)).default([]), - storage: StorageContractSchema2.optional(), - deploymentModes: exports_external3.array(DeploymentModeSchema2).default(["local"]), - serviceSurfaces: exports_external3.array(ServiceSurfaceSchema2).default([]), - metadata: MetadataSchema2.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName2(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor2(value.name)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor2(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna//.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } - } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); - } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } - } - } -}); -var HealthResponseSchema2 = exports_external3.object({ - status: exports_external3.enum(["ok", "degraded", "unavailable"]), - version: exports_external3.string().min(1), - mode: StorageModeSchema2 -}).strict(); -var ReadyResponseSchema2 = exports_external3.object({ - ready: exports_external3.boolean(), - reason: exports_external3.string().min(1).optional() -}).strict(); -var VersionResponseSchema2 = exports_external3.object({ - version: exports_external3.string().min(1) -}).strict(); -var CommsSeveritySchema2 = exports_external3.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema2 = exports_external3.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (..)"); -var COMMS_SEVERITY_TAGS2 = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema2 = exports_external3.enum(COMMS_SEVERITY_TAGS2); -var CommsScopeSchema2 = exports_external3.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsEventEnvelope).extend({ - type: CommsEventTypeSchema2, - severity: CommsSeveritySchema2, - scope: CommsScopeSchema2, - summary: exports_external3.string().min(1).optional(), - source: ActorPointerSchema2.optional(), - affected_packages: exports_external3.array(NonEmptyStringSchema2).default([]), - affected_machines: exports_external3.array(NonEmptyStringSchema2).default([]), - action_required: exports_external3.boolean().default(false), - ack_by: TimestampSchema2.optional(), - dedupe_key: NonEmptyStringSchema2, - resourceRefs: exports_external3.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); - } - } -}); -var CommsChannelClassSchema2 = exports_external3.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema2 = exports_external3.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema2 = NonEmptyStringSchema2.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"); -var CommsChannelMetadataSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsChannelMetadata).extend({ - class: CommsChannelClassSchema2, - noise: CommsChannelNoiseSchema2.optional(), - owner: NonEmptyStringSchema2.optional(), - until: CommsUntilHorizonSchema2.optional(), - successor: NonEmptyStringSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); - } - } -}); -var COMMS_SEVERITY_TAG_INFO2 = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema2, - envelope: CommsEventEnvelopeSchema2 -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO2[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO2)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] - }); - } - } -}); -var ContractSchemaRegistry2 = { - [SCHEMA_IDS2.actorRef]: ActorRefSchema2, - [SCHEMA_IDS2.resourceRef]: ResourceRefSchema2, - [SCHEMA_IDS2.evidenceRef]: EvidenceRefSchema2, - [SCHEMA_IDS2.workRun]: WorkRunSchema2, - [SCHEMA_IDS2.decisionEnvelope]: DecisionEnvelopeSchema2, - [SCHEMA_IDS2.costEstimate]: CostEstimateSchema2, - [SCHEMA_IDS2.capabilityCard]: CapabilityCardSchema2, - [SCHEMA_IDS2.providerLiveModeStandard]: ProviderLiveModeStandardSchema2, - [SCHEMA_IDS2.contextPack]: ContextPackSchema2, - [SCHEMA_IDS2.integrationRef]: IntegrationRefSchema2, - [SCHEMA_IDS2.projectManifest]: ProjectManifestSchema2, - [SCHEMA_IDS2.projectPanel]: ProjectPanelSchema2, - [SCHEMA_IDS2.projectSnapshot]: ProjectSnapshotSchema2, - [SCHEMA_IDS2.renderManifest]: RenderManifestSchema2, - [SCHEMA_IDS2.agentTrajectory]: AgentTrajectorySchema2, - [SCHEMA_IDS2.validationPlan]: ValidationPlanSchema2, - [SCHEMA_IDS2.proofBundle]: ProofBundleSchema2, - [SCHEMA_IDS2.scaffoldManifest]: ScaffoldManifestSchema2, - [SCHEMA_IDS2.scaffoldInstallRecord]: ScaffoldInstallRecordSchema2, - [SCHEMA_IDS2.appCloudManifest]: AppCloudManifestSchema2, - [SCHEMA_IDS2.noCloudEvidencePack]: NoCloudEvidencePackSchema2, - [SCHEMA_IDS2.serviceContract]: ServiceContractManifestSchema2, - [SCHEMA_IDS2.commsEventEnvelope]: CommsEventEnvelopeSchema2, - [SCHEMA_IDS2.commsChannelMetadata]: CommsChannelMetadataSchema2, - [SCHEMA_IDS2.commsMessageMetadata]: CommsMessageMetadataSchema2, - [SCHEMA_IDS2.app]: AppSchema2, - [SCHEMA_IDS2.release]: ReleaseSchema2, - [SCHEMA_IDS2.rolloutRecord]: RolloutRecordSchema2, - [SCHEMA_IDS2.announcement]: AnnouncementSchema2, - [SCHEMA_IDS2.audience]: AudienceSchema2 -}; -function envToken2(name) { - return name.toUpperCase().replace(/-/g, "_"); -} -function clientTransportEnvKeys2(name) { - const envSegment = envToken2(name); - return { - modeKeys: [ - `HASNA_${envSegment}_STORAGE_MODE`, - `HASNA_${envSegment}_MODE`, - `${envSegment}_STORAGE_MODE`, - `${envSegment}_MODE` - ], - apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], - apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] - }; -} -var IDEMPOTENT_METHODS2 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); - -// node_modules/@hasna/contracts/dist/mode.js -var __defProp4 = Object.defineProperty; -var __returnValue4 = (v) => v; -function __exportSetter4(name, newValue) { - this[name] = __returnValue4.bind(null, newValue); -} -var __export4 = (target, all) => { - for (var name in all) - __defProp4(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter4.bind(all, name) - }); -}; -var exports_external4 = {}; -__export4(exports_external4, { - void: () => voidType3, - util: () => util3, - unknown: () => unknownType3, - union: () => unionType3, - undefined: () => undefinedType3, - tuple: () => tupleType3, - transformer: () => effectsType3, - symbol: () => symbolType3, - string: () => stringType3, - strictObject: () => strictObjectType3, - setErrorMap: () => setErrorMap4, - set: () => setType3, - record: () => recordType3, - quotelessJson: () => quotelessJson3, - promise: () => promiseType3, - preprocess: () => preprocessType3, - pipeline: () => pipelineType3, - ostring: () => ostring3, - optional: () => optionalType3, - onumber: () => onumber3, - oboolean: () => oboolean3, - objectUtil: () => objectUtil3, - object: () => objectType3, - number: () => numberType3, - nullable: () => nullableType3, - null: () => nullType3, - never: () => neverType3, - nativeEnum: () => nativeEnumType3, - nan: () => nanType3, - map: () => mapType3, - makeIssue: () => makeIssue3, - literal: () => literalType3, - lazy: () => lazyType3, - late: () => late3, - isValid: () => isValid3, - isDirty: () => isDirty3, - isAsync: () => isAsync3, - isAborted: () => isAborted3, - intersection: () => intersectionType3, - instanceof: () => instanceOfType3, - getParsedType: () => getParsedType4, - getErrorMap: () => getErrorMap4, - function: () => functionType3, - enum: () => enumType3, - effect: () => effectsType3, - discriminatedUnion: () => discriminatedUnionType3, - defaultErrorMap: () => en_default4, - datetimeRegex: () => datetimeRegex3, - date: () => dateType3, - custom: () => custom4, - coerce: () => coerce3, - boolean: () => booleanType3, - bigint: () => bigIntType3, - array: () => arrayType3, - any: () => anyType3, - addIssueToContext: () => addIssueToContext3, - ZodVoid: () => ZodVoid4, - ZodUnknown: () => ZodUnknown4, - ZodUnion: () => ZodUnion4, - ZodUndefined: () => ZodUndefined4, - ZodType: () => ZodType4, - ZodTuple: () => ZodTuple4, - ZodTransformer: () => ZodEffects3, - ZodSymbol: () => ZodSymbol4, - ZodString: () => ZodString4, - ZodSet: () => ZodSet4, - ZodSchema: () => ZodType4, - ZodRecord: () => ZodRecord4, - ZodReadonly: () => ZodReadonly4, - ZodPromise: () => ZodPromise4, - ZodPipeline: () => ZodPipeline3, - ZodParsedType: () => ZodParsedType3, - ZodOptional: () => ZodOptional4, - ZodObject: () => ZodObject4, - ZodNumber: () => ZodNumber4, - ZodNullable: () => ZodNullable4, - ZodNull: () => ZodNull4, - ZodNever: () => ZodNever4, - ZodNativeEnum: () => ZodNativeEnum3, - ZodNaN: () => ZodNaN4, - ZodMap: () => ZodMap4, - ZodLiteral: () => ZodLiteral4, - ZodLazy: () => ZodLazy4, - ZodIssueCode: () => ZodIssueCode4, - ZodIntersection: () => ZodIntersection4, - ZodFunction: () => ZodFunction4, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind4, - ZodError: () => ZodError4, - ZodEnum: () => ZodEnum4, - ZodEffects: () => ZodEffects3, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion4, - ZodDefault: () => ZodDefault4, - ZodDate: () => ZodDate4, - ZodCatch: () => ZodCatch4, - ZodBranded: () => ZodBranded3, - ZodBoolean: () => ZodBoolean4, - ZodBigInt: () => ZodBigInt4, - ZodArray: () => ZodArray4, - ZodAny: () => ZodAny4, - Schema: () => ZodType4, - ParseStatus: () => ParseStatus3, - OK: () => OK3, - NEVER: () => NEVER4, - INVALID: () => INVALID3, - EMPTY_PATH: () => EMPTY_PATH3, - DIRTY: () => DIRTY3, - BRAND: () => BRAND3 -}); -var util3; -(function(util22) { - util22.assertEqual = (_) => {}; - function assertIs2(_arg) {} - util22.assertIs = assertIs2; - function assertNever2(_x) { - throw new Error; - } - util22.assertNever = assertNever2; - util22.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util22.getValidEnumValues = (obj) => { - const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util22.objectValues(filtered); - }; - util22.objectValues = (obj) => { - return util22.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { - const keys = []; - for (const key in object2) { - if (Object.prototype.hasOwnProperty.call(object2, key)) { - keys.push(key); - } - } - return keys; - }; - util22.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues2(array2, separator = " | ") { - return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util22.joinValues = joinValues2; - util22.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util3 || (util3 = {})); -var objectUtil3; -(function(objectUtil22) { - objectUtil22.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; -})(objectUtil3 || (objectUtil3 = {})); -var ZodParsedType3 = util3.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType3.undefined; - case "string": - return ZodParsedType3.string; - case "number": - return Number.isNaN(data) ? ZodParsedType3.nan : ZodParsedType3.number; - case "boolean": - return ZodParsedType3.boolean; - case "function": - return ZodParsedType3.function; - case "bigint": - return ZodParsedType3.bigint; - case "symbol": - return ZodParsedType3.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType3.array; - } - if (data === null) { - return ZodParsedType3.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType3.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType3.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType3.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType3.date; - } - return ZodParsedType3.object; - default: - return ZodParsedType3.unknown; - } -}; -var ZodIssueCode4 = util3.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson3 = (obj) => { - const json2 = JSON.stringify(obj, null, 2); - return json2.replace(/"([^"]+)":/g, "$1:"); -}; - -class ZodError4 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error51) => { - for (const issue2 of error51.issues) { - if (issue2.code === "invalid_union") { - issue2.unionErrors.map(processError); - } else if (issue2.code === "invalid_return_type") { - processError(issue2.returnTypeError); - } else if (issue2.code === "invalid_arguments") { - processError(issue2.argumentsError); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError4)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util3.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError4.create = (issues) => { - const error51 = new ZodError4(issues); - return error51; -}; -var errorMap3 = (issue2, _ctx) => { - let message; - switch (issue2.code) { - case ZodIssueCode4.invalid_type: - if (issue2.received === ZodParsedType3.undefined) { - message = "Required"; - } else { - message = `Expected ${issue2.expected}, received ${issue2.received}`; - } - break; - case ZodIssueCode4.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util3.jsonStringifyReplacer)}`; - break; - case ZodIssueCode4.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util3.joinValues(issue2.keys, ", ")}`; - break; - case ZodIssueCode4.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode4.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util3.joinValues(issue2.options)}`; - break; - case ZodIssueCode4.invalid_enum_value: - message = `Invalid enum value. Expected ${util3.joinValues(issue2.options)}, received '${issue2.received}'`; - break; - case ZodIssueCode4.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode4.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode4.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode4.invalid_string: - if (typeof issue2.validation === "object") { - if ("includes" in issue2.validation) { - message = `Invalid input: must include "${issue2.validation.includes}"`; - if (typeof issue2.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; - } - } else if ("startsWith" in issue2.validation) { - message = `Invalid input: must start with "${issue2.validation.startsWith}"`; - } else if ("endsWith" in issue2.validation) { - message = `Invalid input: must end with "${issue2.validation.endsWith}"`; - } else { - util3.assertNever(issue2.validation); - } - } else if (issue2.validation !== "regex") { - message = `Invalid ${issue2.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode4.too_small: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "bigint") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode4.too_big: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "bigint") - message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode4.custom: - message = `Invalid input`; - break; - case ZodIssueCode4.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode4.not_multiple_of: - message = `Number must be a multiple of ${issue2.multipleOf}`; - break; - case ZodIssueCode4.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util3.assertNever(issue2); - } - return { message }; -}; -var en_default4 = errorMap3; -var overrideErrorMap3 = en_default4; -function setErrorMap4(map2) { - overrideErrorMap3 = map2; -} -function getErrorMap4() { - return overrideErrorMap3; -} -var makeIssue3 = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map2 of maps) { - errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH3 = []; -function addIssueToContext3(ctx, issueData) { - const overrideMap = getErrorMap4(); - const issue2 = makeIssue3({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default4 ? undefined : en_default4 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue2); -} - -class ParseStatus3 { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID3; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus3.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID3; - if (value.status === "aborted") - return INVALID3; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -var INVALID3 = Object.freeze({ - status: "aborted" -}); -var DIRTY3 = (value) => ({ status: "dirty", value }); -var OK3 = (value) => ({ status: "valid", value }); -var isAborted3 = (x) => x.status === "aborted"; -var isDirty3 = (x) => x.status === "dirty"; -var isValid3 = (x) => x.status === "valid"; -var isAsync3 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil3; -(function(errorUtil22) { - errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil3 || (errorUtil3 = {})); - -class ParseInputLazyPath3 { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -var handleResult3 = (ctx, result) => { - if (isValid3(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error51 = new ZodError4(ctx.common.issues); - this._error = error51; - return this._error; - } - }; - } -}; -function processCreateParams3(params) { - if (!params) - return {}; - const { errorMap: errorMap22, invalid_type_error, required_error, description } = params; - if (errorMap22 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap22) - return { errorMap: errorMap22, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -class ZodType4 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType4(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType4(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus3, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType4(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync3(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType4(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult3(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType4(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid3(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid3(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType4(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync3(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult3(ctx, result); - } - refine(check2, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check2(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode4.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check2, refinementData) { - return this._refinement((val, ctx) => { - if (!check2(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects3({ - schema: this, - typeName: ZodFirstPartyTypeKind4.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional4.create(this, this._def); - } - nullable() { - return ZodNullable4.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray4.create(this); - } - promise() { - return ZodPromise4.create(this, this._def); - } - or(option) { - return ZodUnion4.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection4.create(this, incoming, this._def); - } - transform(transform2) { - return new ZodEffects3({ - ...processCreateParams3(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind4.ZodEffects, - effect: { type: "transform", transform: transform2 } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault4({ - ...processCreateParams3(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind4.ZodDefault - }); - } - brand() { - return new ZodBranded3({ - typeName: ZodFirstPartyTypeKind4.ZodBranded, - type: this, - ...processCreateParams3(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch4({ - ...processCreateParams3(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind4.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline3.create(this, target); - } - readonly() { - return ZodReadonly4.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex3 = /^c[^\s-]{8,}$/i; -var cuid2Regex3 = /^[0-9a-z]+$/; -var ulidRegex3 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex3 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex3 = /^[a-z0-9_-]{21}$/i; -var jwtRegex3 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex3 = /^[-+]?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)?)??$/; -var emailRegex3 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex3; -var ipv4Regex3 = /^(?:(?: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])$/; -var ipv4CidrRegex3 = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex3 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex3 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex3 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex3 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource3 = `((\\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])))`; -var dateRegex3 = new RegExp(`^${dateRegexSource3}$`); -function timeRegexSource3(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex3(args) { - return new RegExp(`^${timeRegexSource3(args)}$`); -} -function datetimeRegex3(args) { - let regex = `${dateRegexSource3}T${timeRegexSource3(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP3(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4Regex3.test(ip)) { - return true; - } - if ((version2 === "v6" || !version2) && ipv6Regex3.test(ip)) { - return true; - } - return false; -} -function isValidJWT4(jwt2, alg) { - if (!jwtRegex3.test(jwt2)) - return false; - try { - const [header] = jwt2.split("."); - if (!header) - return false; - const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base643)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr3(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4CidrRegex3.test(ip)) { - return true; - } - if ((version2 === "v6" || !version2) && ipv6CidrRegex3.test(ip)) { - return true; - } - return false; -} - -class ZodString4 extends ZodType4 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.string, - received: ctx2.parsedType - }); - return INVALID3; - } - const status = new ParseStatus3; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.length < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.length > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "length") { - const tooBig = input.data.length > check2.value; - const tooSmall = input.data.length < check2.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } else if (tooSmall) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } - status.dirty(); - } - } else if (check2.kind === "email") { - if (!emailRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "email", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "emoji") { - if (!emojiRegex3) { - emojiRegex3 = new RegExp(_emojiRegex3, "u"); - } - if (!emojiRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "emoji", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "uuid") { - if (!uuidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "uuid", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "nanoid") { - if (!nanoidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "nanoid", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid") { - if (!cuidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cuid", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid2") { - if (!cuid2Regex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cuid2", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ulid") { - if (!ulidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "ulid", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "url", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "regex") { - check2.regex.lastIndex = 0; - const testResult = check2.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "regex", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "trim") { - input.data = input.data.trim(); - } else if (check2.kind === "includes") { - if (!input.data.includes(check2.value, check2.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_string, - validation: { includes: check2.value, position: check2.position }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check2.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check2.kind === "startsWith") { - if (!input.data.startsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_string, - validation: { startsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "endsWith") { - if (!input.data.endsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_string, - validation: { endsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "datetime") { - const regex = datetimeRegex3(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_string, - validation: "datetime", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "date") { - const regex = dateRegex3; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_string, - validation: "date", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "time") { - const regex = timeRegex3(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_string, - validation: "time", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "duration") { - if (!durationRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "duration", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ip") { - if (!isValidIP3(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "ip", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "jwt") { - if (!isValidJWT4(input.data, check2.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "jwt", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cidr") { - if (!isValidCidr3(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cidr", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64") { - if (!base64Regex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "base64", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64url") { - if (!base64urlRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "base64url", - code: ZodIssueCode4.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else { - util3.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode4.invalid_string, - ...errorUtil3.errToObj(message) - }); - } - _addCheck(check2) { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil3.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil3.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil3.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil3.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil3.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil3.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil3.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil3.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil3.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil3.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil3.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil3.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil3.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil3.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil3.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil3.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil3.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil3.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil3.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil3.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil3.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil3.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil3.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil3.errToObj(message)); - } - trim() { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString4.create = (params) => { - return new ZodString4({ - checks: [], - typeName: ZodFirstPartyTypeKind4.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams3(params) - }); -}; -function floatSafeRemainder4(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} - -class ZodNumber4 extends ZodType4 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.number, - received: ctx2.parsedType - }); - return INVALID3; - } - let ctx = undefined; - const status = new ParseStatus3; - for (const check2 of this._def.checks) { - if (check2.kind === "int") { - if (!util3.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: "integer", - received: "float", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - minimum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - maximum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (floatSafeRemainder4(input.data, check2.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.not_finite, - message: check2.message - }); - status.dirty(); - } - } else { - util3.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil3.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil3.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil3.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil3.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber4({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil3.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodNumber4({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil3.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil3.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil3.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil3.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil3.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil3.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil3.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil3.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil3.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util3.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber4.create = (params) => { - return new ZodNumber4({ - checks: [], - typeName: ZodFirstPartyTypeKind4.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams3(params) - }); -}; - -class ZodBigInt4 extends ZodType4 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus3; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - type: "bigint", - minimum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - type: "bigint", - maximum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (input.data % check2.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else { - util3.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.bigint, - received: ctx.parsedType - }); - return INVALID3; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil3.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil3.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil3.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil3.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt4({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil3.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodBigInt4({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil3.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil3.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil3.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil3.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil3.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt4.create = (params) => { - return new ZodBigInt4({ - checks: [], - typeName: ZodFirstPartyTypeKind4.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams3(params) - }); -}; - -class ZodBoolean4 extends ZodType4 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.boolean, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodBoolean4.create = (params) => { - return new ZodBoolean4({ - typeName: ZodFirstPartyTypeKind4.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams3(params) - }); -}; - -class ZodDate4 extends ZodType4 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.date, - received: ctx2.parsedType - }); - return INVALID3; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode4.invalid_date - }); - return INVALID3; - } - const status = new ParseStatus3; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.getTime() < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - message: check2.message, - inclusive: true, - exact: false, - minimum: check2.value, - type: "date" - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.getTime() > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - message: check2.message, - inclusive: true, - exact: false, - maximum: check2.value, - type: "date" - }); - status.dirty(); - } - } else { - util3.assertNever(check2); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check2) { - return new ZodDate4({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil3.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil3.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate4.create = (params) => { - return new ZodDate4({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind4.ZodDate, - ...processCreateParams3(params) - }); -}; - -class ZodSymbol4 extends ZodType4 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.symbol, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodSymbol4.create = (params) => { - return new ZodSymbol4({ - typeName: ZodFirstPartyTypeKind4.ZodSymbol, - ...processCreateParams3(params) - }); -}; - -class ZodUndefined4 extends ZodType4 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.undefined, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodUndefined4.create = (params) => { - return new ZodUndefined4({ - typeName: ZodFirstPartyTypeKind4.ZodUndefined, - ...processCreateParams3(params) - }); -}; - -class ZodNull4 extends ZodType4 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.null, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodNull4.create = (params) => { - return new ZodNull4({ - typeName: ZodFirstPartyTypeKind4.ZodNull, - ...processCreateParams3(params) - }); -}; - -class ZodAny4 extends ZodType4 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK3(input.data); - } -} -ZodAny4.create = (params) => { - return new ZodAny4({ - typeName: ZodFirstPartyTypeKind4.ZodAny, - ...processCreateParams3(params) - }); -}; - -class ZodUnknown4 extends ZodType4 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK3(input.data); - } -} -ZodUnknown4.create = (params) => { - return new ZodUnknown4({ - typeName: ZodFirstPartyTypeKind4.ZodUnknown, - ...processCreateParams3(params) - }); -}; - -class ZodNever4 extends ZodType4 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.never, - received: ctx.parsedType - }); - return INVALID3; - } -} -ZodNever4.create = (params) => { - return new ZodNever4({ - typeName: ZodFirstPartyTypeKind4.ZodNever, - ...processCreateParams3(params) - }); -}; - -class ZodVoid4 extends ZodType4 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.void, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodVoid4.create = (params) => { - return new ZodVoid4({ - typeName: ZodFirstPartyTypeKind4.ZodVoid, - ...processCreateParams3(params) - }); -}; - -class ZodArray4 extends ZodType4 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType3.array) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.array, - received: ctx.parsedType - }); - return INVALID3; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext3(ctx, { - code: tooBig ? ZodIssueCode4.too_big : ZodIssueCode4.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath3(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus3.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath3(ctx, item, ctx.path, i)); - }); - return ParseStatus3.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray4({ - ...this._def, - minLength: { value: minLength, message: errorUtil3.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray4({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil3.toString(message) } - }); - } - length(len, message) { - return new ZodArray4({ - ...this._def, - exactLength: { value: len, message: errorUtil3.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray4.create = (schema, params) => { - return new ZodArray4({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind4.ZodArray, - ...processCreateParams3(params) - }); -}; -function deepPartialify3(schema) { - if (schema instanceof ZodObject4) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional4.create(deepPartialify3(fieldSchema)); - } - return new ZodObject4({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray4) { - return new ZodArray4({ - ...schema._def, - type: deepPartialify3(schema.element) - }); - } else if (schema instanceof ZodOptional4) { - return ZodOptional4.create(deepPartialify3(schema.unwrap())); - } else if (schema instanceof ZodNullable4) { - return ZodNullable4.create(deepPartialify3(schema.unwrap())); - } else if (schema instanceof ZodTuple4) { - return ZodTuple4.create(schema.items.map((item) => deepPartialify3(item))); - } else { - return schema; - } -} - -class ZodObject4 extends ZodType4 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util3.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.object, - received: ctx2.parsedType - }); - return INVALID3; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever4 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever4) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus3.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus3.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil3.errToObj; - return new ZodObject4({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue2, ctx) => { - const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; - if (issue2.code === "unrecognized_keys") - return { - message: errorUtil3.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject4({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject4({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject4({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject4({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind4.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject4({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util3.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject4({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject4({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify3(this); - } - partial(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject4({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional4) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject4({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum3(util3.objectKeys(this.shape)); - } -} -ZodObject4.create = (shape, params) => { - return new ZodObject4({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever4.create(), - typeName: ZodFirstPartyTypeKind4.ZodObject, - ...processCreateParams3(params) - }); -}; -ZodObject4.strictCreate = (shape, params) => { - return new ZodObject4({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever4.create(), - typeName: ZodFirstPartyTypeKind4.ZodObject, - ...processCreateParams3(params) - }); -}; -ZodObject4.lazycreate = (shape, params) => { - return new ZodObject4({ - shape, - unknownKeys: "strip", - catchall: ZodNever4.create(), - typeName: ZodFirstPartyTypeKind4.ZodObject, - ...processCreateParams3(params) - }); -}; - -class ZodUnion4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError4(result.ctx.common.issues)); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_union, - unionErrors - }); - return INVALID3; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError4(issues2)); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_union, - unionErrors - }); - return INVALID3; - } - } - get options() { - return this._def.options; - } -} -ZodUnion4.create = (types, params) => { - return new ZodUnion4({ - options: types, - typeName: ZodFirstPartyTypeKind4.ZodUnion, - ...processCreateParams3(params) - }); -}; -var getDiscriminator3 = (type) => { - if (type instanceof ZodLazy4) { - return getDiscriminator3(type.schema); - } else if (type instanceof ZodEffects3) { - return getDiscriminator3(type.innerType()); - } else if (type instanceof ZodLiteral4) { - return [type.value]; - } else if (type instanceof ZodEnum4) { - return type.options; - } else if (type instanceof ZodNativeEnum3) { - return util3.objectValues(type.enum); - } else if (type instanceof ZodDefault4) { - return getDiscriminator3(type._def.innerType); - } else if (type instanceof ZodUndefined4) { - return [undefined]; - } else if (type instanceof ZodNull4) { - return [null]; - } else if (type instanceof ZodOptional4) { - return [undefined, ...getDiscriminator3(type.unwrap())]; - } else if (type instanceof ZodNullable4) { - return [null, ...getDiscriminator3(type.unwrap())]; - } else if (type instanceof ZodBranded3) { - return getDiscriminator3(type.unwrap()); - } else if (type instanceof ZodReadonly4) { - return getDiscriminator3(type.unwrap()); - } else if (type instanceof ZodCatch4) { - return getDiscriminator3(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.object) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.object, - received: ctx.parsedType - }); - return INVALID3; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID3; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator3(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion4({ - typeName: ZodFirstPartyTypeKind4.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams3(params) - }); - } -} -function mergeValues4(a, b) { - const aType = getParsedType4(a); - const bType = getParsedType4(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType3.object && bType === ZodParsedType3.object) { - const bKeys = util3.objectKeys(b); - const sharedKeys = util3.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues4(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType3.array && bType === ZodParsedType3.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues4(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType3.date && bType === ZodParsedType3.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection4 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted3(parsedLeft) || isAborted3(parsedRight)) { - return INVALID3; - } - const merged = mergeValues4(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_intersection_types - }); - return INVALID3; - } - if (isDirty3(parsedLeft) || isDirty3(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection4.create = (left, right, params) => { - return new ZodIntersection4({ - left, - right, - typeName: ZodFirstPartyTypeKind4.ZodIntersection, - ...processCreateParams3(params) - }); -}; - -class ZodTuple4 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.array) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.array, - received: ctx.parsedType - }); - return INVALID3; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID3; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath3(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus3.mergeArray(status, results); - }); - } else { - return ParseStatus3.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple4({ - ...this._def, - rest - }); - } -} -ZodTuple4.create = (schemas3, params) => { - if (!Array.isArray(schemas3)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple4({ - items: schemas3, - typeName: ZodFirstPartyTypeKind4.ZodTuple, - rest: null, - ...processCreateParams3(params) - }); -}; - -class ZodRecord4 extends ZodType4 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.object) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.object, - received: ctx.parsedType - }); - return INVALID3; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath3(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus3.mergeObjectAsync(status, pairs); - } else { - return ParseStatus3.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType4) { - return new ZodRecord4({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind4.ZodRecord, - ...processCreateParams3(third) - }); - } - return new ZodRecord4({ - keyType: ZodString4.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind4.ZodRecord, - ...processCreateParams3(second) - }); - } -} - -class ZodMap4 extends ZodType4 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.map) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.map, - received: ctx.parsedType - }); - return INVALID3; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath3(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID3; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID3; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap4.create = (keyType, valueType, params) => { - return new ZodMap4({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind4.ZodMap, - ...processCreateParams3(params) - }); -}; - -class ZodSet4 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.set) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.set, - received: ctx.parsedType - }); - return INVALID3; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID3; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath3(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet4({ - ...this._def, - minSize: { value: minSize, message: errorUtil3.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet4({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil3.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet4.create = (valueType, params) => { - return new ZodSet4({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind4.ZodSet, - ...processCreateParams3(params) - }); -}; - -class ZodFunction4 extends ZodType4 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.function) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.function, - received: ctx.parsedType - }); - return INVALID3; - } - function makeArgsIssue(args, error51) { - return makeIssue3({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap4(), en_default4].filter((x) => !!x), - issueData: { - code: ZodIssueCode4.invalid_arguments, - argumentsError: error51 - } - }); - } - function makeReturnsIssue(returns, error51) { - return makeIssue3({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap4(), en_default4].filter((x) => !!x), - issueData: { - code: ZodIssueCode4.invalid_return_type, - returnTypeError: error51 - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise4) { - const me = this; - return OK3(async function(...args) { - const error51 = new ZodError4([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error51.addIssue(makeArgsIssue(args, e)); - throw error51; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error51.addIssue(makeReturnsIssue(result, e)); - throw error51; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK3(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError4([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError4([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction4({ - ...this._def, - args: ZodTuple4.create(items).rest(ZodUnknown4.create()) - }); - } - returns(returnType) { - return new ZodFunction4({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction4({ - args: args ? args : ZodTuple4.create([]).rest(ZodUnknown4.create()), - returns: returns || ZodUnknown4.create(), - typeName: ZodFirstPartyTypeKind4.ZodFunction, - ...processCreateParams3(params) - }); - } -} - -class ZodLazy4 extends ZodType4 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy4.create = (getter, params) => { - return new ZodLazy4({ - getter, - typeName: ZodFirstPartyTypeKind4.ZodLazy, - ...processCreateParams3(params) - }); -}; - -class ZodLiteral4 extends ZodType4 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode4.invalid_literal, - expected: this._def.value - }); - return INVALID3; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral4.create = (value, params) => { - return new ZodLiteral4({ - value, - typeName: ZodFirstPartyTypeKind4.ZodLiteral, - ...processCreateParams3(params) - }); -}; -function createZodEnum3(values, params) { - return new ZodEnum4({ - values, - typeName: ZodFirstPartyTypeKind4.ZodEnum, - ...processCreateParams3(params) - }); -} - -class ZodEnum4 extends ZodType4 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext3(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode4.invalid_type - }); - return INVALID3; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode4.invalid_enum_value, - options: expectedValues - }); - return INVALID3; - } - return OK3(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum4.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum4.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum4.create = createZodEnum3; - -class ZodNativeEnum3 extends ZodType4 { - _parse(input) { - const nativeEnumValues = util3.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType3.string && ctx.parsedType !== ZodParsedType3.number) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext3(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode4.invalid_type - }); - return INVALID3; - } - if (!this._cache) { - this._cache = new Set(util3.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode4.invalid_enum_value, - options: expectedValues - }); - return INVALID3; - } - return OK3(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum3.create = (values, params) => { - return new ZodNativeEnum3({ - values, - typeName: ZodFirstPartyTypeKind4.ZodNativeEnum, - ...processCreateParams3(params) - }); -}; - -class ZodPromise4 extends ZodType4 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.promise && ctx.common.async === false) { - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.promise, - received: ctx.parsedType - }); - return INVALID3; - } - const promisified = ctx.parsedType === ZodParsedType3.promise ? ctx.data : Promise.resolve(ctx.data); - return OK3(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise4.create = (schema, params) => { - return new ZodPromise4({ - type: schema, - typeName: ZodFirstPartyTypeKind4.ZodPromise, - ...processCreateParams3(params) - }); -}; - -class ZodEffects3 extends ZodType4 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind4.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext3(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID3; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID3; - if (result.status === "dirty") - return DIRTY3(result.value); - if (status.value === "dirty") - return DIRTY3(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID3; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID3; - if (result.status === "dirty") - return DIRTY3(result.value); - if (status.value === "dirty") - return DIRTY3(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID3; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID3; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid3(base)) - return INVALID3; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid3(base)) - return INVALID3; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util3.assertNever(effect); - } -} -ZodEffects3.create = (schema, effect, params) => { - return new ZodEffects3({ - schema, - typeName: ZodFirstPartyTypeKind4.ZodEffects, - effect, - ...processCreateParams3(params) - }); -}; -ZodEffects3.createWithPreprocess = (preprocess2, schema, params) => { - return new ZodEffects3({ - schema, - effect: { type: "preprocess", transform: preprocess2 }, - typeName: ZodFirstPartyTypeKind4.ZodEffects, - ...processCreateParams3(params) - }); -}; - -class ZodOptional4 extends ZodType4 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType3.undefined) { - return OK3(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional4.create = (type, params) => { - return new ZodOptional4({ - innerType: type, - typeName: ZodFirstPartyTypeKind4.ZodOptional, - ...processCreateParams3(params) - }); -}; - -class ZodNullable4 extends ZodType4 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType3.null) { - return OK3(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable4.create = (type, params) => { - return new ZodNullable4({ - innerType: type, - typeName: ZodFirstPartyTypeKind4.ZodNullable, - ...processCreateParams3(params) - }); -}; - -class ZodDefault4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType3.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault4.create = (type, params) => { - return new ZodDefault4({ - innerType: type, - typeName: ZodFirstPartyTypeKind4.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams3(params) - }); -}; - -class ZodCatch4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync3(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError4(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError4(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch4.create = (type, params) => { - return new ZodCatch4({ - innerType: type, - typeName: ZodFirstPartyTypeKind4.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams3(params) - }); -}; - -class ZodNaN4 extends ZodType4 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType3.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType3.nan, - received: ctx.parsedType - }); - return INVALID3; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN4.create = (params) => { - return new ZodNaN4({ - typeName: ZodFirstPartyTypeKind4.ZodNaN, - ...processCreateParams3(params) - }); -}; -var BRAND3 = Symbol("zod_brand"); - -class ZodBranded3 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline3 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID3; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY3(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID3; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline3({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind4.ZodPipeline - }); - } -} - -class ZodReadonly4 extends ZodType4 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid3(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync3(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly4.create = (type, params) => { - return new ZodReadonly4({ - innerType: type, - typeName: ZodFirstPartyTypeKind4.ZodReadonly, - ...processCreateParams3(params) - }); -}; -function cleanParams3(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom4(check2, _params = {}, fatal) { - if (check2) - return ZodAny4.create().superRefine((data, ctx) => { - const r = check2(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams3(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams3(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny4.create(); -} -var late3 = { - object: ZodObject4.lazycreate -}; -var ZodFirstPartyTypeKind4; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind4 || (ZodFirstPartyTypeKind4 = {})); -var instanceOfType3 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom4((data) => data instanceof cls, params); -var stringType3 = ZodString4.create; -var numberType3 = ZodNumber4.create; -var nanType3 = ZodNaN4.create; -var bigIntType3 = ZodBigInt4.create; -var booleanType3 = ZodBoolean4.create; -var dateType3 = ZodDate4.create; -var symbolType3 = ZodSymbol4.create; -var undefinedType3 = ZodUndefined4.create; -var nullType3 = ZodNull4.create; -var anyType3 = ZodAny4.create; -var unknownType3 = ZodUnknown4.create; -var neverType3 = ZodNever4.create; -var voidType3 = ZodVoid4.create; -var arrayType3 = ZodArray4.create; -var objectType3 = ZodObject4.create; -var strictObjectType3 = ZodObject4.strictCreate; -var unionType3 = ZodUnion4.create; -var discriminatedUnionType3 = ZodDiscriminatedUnion4.create; -var intersectionType3 = ZodIntersection4.create; -var tupleType3 = ZodTuple4.create; -var recordType3 = ZodRecord4.create; -var mapType3 = ZodMap4.create; -var setType3 = ZodSet4.create; -var functionType3 = ZodFunction4.create; -var lazyType3 = ZodLazy4.create; -var literalType3 = ZodLiteral4.create; -var enumType3 = ZodEnum4.create; -var nativeEnumType3 = ZodNativeEnum3.create; -var promiseType3 = ZodPromise4.create; -var effectsType3 = ZodEffects3.create; -var optionalType3 = ZodOptional4.create; -var nullableType3 = ZodNullable4.create; -var preprocessType3 = ZodEffects3.createWithPreprocess; -var pipelineType3 = ZodPipeline3.create; -var ostring3 = () => stringType3().optional(); -var onumber3 = () => numberType3().optional(); -var oboolean3 = () => booleanType3().optional(); -var coerce3 = { - string: (arg) => ZodString4.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber4.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean4.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt4.create({ ...arg, coerce: true }), - date: (arg) => ZodDate4.create({ ...arg, coerce: true }) -}; -var NEVER4 = INVALID3; -var SCHEMA_IDS3 = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema3 = exports_external4.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema3 = exports_external4.string().datetime(); -var NonEmptyStringSchema3 = exports_external4.string().trim().min(1); -var UriSchema3 = NonEmptyStringSchema3.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema3 = exports_external4.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema3 = exports_external4.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema3 = exports_external4.record(exports_external4.unknown()); -var TagsSchema3 = exports_external4.array(exports_external4.string().min(1)).default([]); -var OptionalTimestampSchema3 = TimestampSchema3.nullable().optional(); -var TerminalStatuses3 = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema3 = exports_external4.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema3(schema) { - return exports_external4.object({ - schema: exports_external4.literal(schema), - id: exports_external4.string().min(1), - createdAt: TimestampSchema3, - updatedAt: OptionalTimestampSchema3, - metadata: MetadataSchema3.optional() - }).strict(); -} -var ContractEnvelopeSchema3 = exports_external4.object({ - schema: SchemaIdSchema3, - id: exports_external4.string().min(1), - createdAt: TimestampSchema3, - updatedAt: OptionalTimestampSchema3, - metadata: MetadataSchema3.optional() -}).strict(); -var ActorKindSchema3 = exports_external4.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.actorRef).extend({ - kind: ActorKindSchema3, - name: exports_external4.string().min(1).optional(), - provider: exports_external4.string().min(1).optional(), - accountId: exports_external4.string().min(1).optional(), - machineId: exports_external4.string().min(1).optional(), - capabilities: exports_external4.array(exports_external4.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema3 = exports_external4.object({ - kind: ActorKindSchema3, - id: exports_external4.string().min(1), - name: exports_external4.string().min(1).optional(), - provider: exports_external4.string().min(1).optional(), - accountId: exports_external4.string().min(1).optional(), - machineId: exports_external4.string().min(1).optional() -}).strict(); -var ResourceKindSchema3 = exports_external4.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.resourceRef).extend({ - kind: ResourceKindSchema3, - name: exports_external4.string().min(1).optional(), - uri: UriSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema3 = exports_external4.object({ - kind: ResourceKindSchema3, - id: exports_external4.string().min(1), - name: exports_external4.string().min(1).optional(), - uri: UriSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema3 = exports_external4.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema3 = exports_external4.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.evidenceRef).extend({ - kind: EvidenceKindSchema3, - uri: UriSchema3, - sha256: Sha256DigestSchema3.optional(), - summary: exports_external4.string().min(1).optional(), - contentType: exports_external4.string().min(1).optional(), - sizeBytes: exports_external4.number().int().nonnegative().optional(), - redaction: RedactionStateSchema3.default("unknown"), - producer: ActorPointerSchema3.optional(), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - tags: TagsSchema3 -}).strict(); -var EvidencePointerSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - kind: EvidenceKindSchema3.optional(), - uri: UriSchema3.optional(), - sha256: Sha256DigestSchema3.optional(), - summary: exports_external4.string().min(1).optional() -}).strict(); -var CostEstimateSchema3 = contractBaseSchema3(SCHEMA_IDS3.costEstimate).extend({ - currency: exports_external4.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external4.number().int().nonnegative(), - provider: exports_external4.string().min(1).optional(), - model: exports_external4.string().min(1).optional(), - accountId: exports_external4.string().min(1).optional(), - promptTokens: exports_external4.number().int().nonnegative().optional(), - completionTokens: exports_external4.number().int().nonnegative().optional(), - totalTokens: exports_external4.number().int().nonnegative().optional(), - basis: exports_external4.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema3 = exports_external4.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema3 = contractBaseSchema3(SCHEMA_IDS3.decisionEnvelope).extend({ - decisionType: exports_external4.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema3, - actor: ActorPointerSchema3.optional(), - traceId: exports_external4.string().min(1).optional(), - inputHash: HashStringSchema3.optional(), - policyBundleId: exports_external4.string().min(1).optional(), - selected: exports_external4.array(ResourcePointerSchema3).default([]), - skipped: exports_external4.array(ResourcePointerSchema3).default([]), - reason: exports_external4.string().min(1), - obligations: exports_external4.array(exports_external4.string().min(1)).default([]), - redactions: exports_external4.array(exports_external4.string().min(1)).default([]), - costEstimate: CostEstimateSchema3.optional(), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema3 = contractBaseSchema3(SCHEMA_IDS3.capabilityCard).extend({ - kind: exports_external4.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external4.string().min(1), - version: exports_external4.string().min(1).optional(), - status: exports_external4.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external4.array(exports_external4.string().min(1)).default([]), - limitations: exports_external4.array(exports_external4.string().min(1)).default([]), - riskLevel: exports_external4.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema3.optional(), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict(); -var ProviderModeSchema3 = exports_external4.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema3 = exports_external4.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema3 = exports_external4.object({ - refName: NonEmptyStringSchema3, - requiredForModes: exports_external4.array(ProviderModeSchema3).min(1), - allowedSecretInputs: exports_external4.array(exports_external4.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema3, - revocationCheck: exports_external4.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema3 = exports_external4.object({ - operation: NonEmptyStringSchema3, - supportedModes: exports_external4.array(ProviderModeSchema3).min(1), - sideEffectClass: ProviderSideEffectClassSchema3, - requiresApproval: exports_external4.boolean().default(false), - requiresIdempotencyKey: exports_external4.boolean().default(false), - requiresSandboxEvidence: exports_external4.boolean().default(false), - requiresRollbackOrRevocation: exports_external4.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema3.optional(), - noSideEffectSmoke: NonEmptyStringSchema3.optional(), - reconciliation: NonEmptyStringSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema3 = exports_external4.object({ - providerId: NonEmptyStringSchema3, - appId: NonEmptyStringSchema3, - adapterId: NonEmptyStringSchema3, - ownerPackage: NonEmptyStringSchema3, - modes: exports_external4.array(ProviderModeSchema3).min(1), - defaultMode: ProviderModeSchema3, - credentialRequirements: exports_external4.array(CredentialRequirementSchema3).default([]), - operations: exports_external4.array(ProviderOperationCardSchema3).min(1), - rateLimitPosture: NonEmptyStringSchema3, - costPosture: NonEmptyStringSchema3.optional(), - auditEvents: exports_external4.array(NonEmptyStringSchema3).default([]), - redactionRules: exports_external4.array(NonEmptyStringSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema3 = exports_external4.object({ - appId: NonEmptyStringSchema3, - repo: NonEmptyStringSchema3, - priority: exports_external4.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external4.array(NonEmptyStringSchema3).min(1), - firstOperations: exports_external4.array(NonEmptyStringSchema3).min(1), - blockedUntil: exports_external4.array(NonEmptyStringSchema3).default([]) -}).strict(); -var ProviderLiveModeStandardSchema3 = contractBaseSchema3(SCHEMA_IDS3.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema3, - version: NonEmptyStringSchema3, - modes: exports_external4.array(ProviderModeSchema3).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external4.array(NonEmptyStringSchema3).min(1), - liveMutationGate: exports_external4.object({ - requiredMode: exports_external4.literal("live_mutating"), - requiredChecks: exports_external4.array(NonEmptyStringSchema3).min(1), - forbiddenBypassSignals: exports_external4.array(NonEmptyStringSchema3).min(1), - disabledLiveSmoke: NonEmptyStringSchema3 - }).strict(), - noSideEffectSmoke: exports_external4.object({ - requiredForModes: exports_external4.array(ProviderModeSchema3).min(1), - commandEvidence: exports_external4.array(NonEmptyStringSchema3).min(1), - secretOutputScan: exports_external4.boolean().default(true) - }).strict(), - credentialPolicy: exports_external4.object({ - acceptedInputs: exports_external4.array(exports_external4.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external4.literal(false), - missingCredentialBehavior: exports_external4.literal("fail_closed"), - revocationCheckRequired: exports_external4.boolean().default(true) - }).strict(), - operationCards: exports_external4.array(ProviderCapabilityCardSchema3).min(1), - firstAdoptionTargets: exports_external4.array(ProviderLiveModeTargetSchema3).min(1), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - title: exports_external4.string().min(1).optional(), - summary: exports_external4.string().min(1), - text: exports_external4.string().optional(), - tokens: exports_external4.number().int().nonnegative().optional(), - source: EvidencePointerSchema3, - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]) -}).strict(); -var ContextPackSchema3 = contractBaseSchema3(SCHEMA_IDS3.contextPack).extend({ - objective: exports_external4.string().min(1), - budget: exports_external4.object({ - maxTokens: exports_external4.number().int().positive().optional(), - maxBytes: exports_external4.number().int().positive().optional() - }).strict().optional(), - items: exports_external4.array(ContextPackItemSchema3).default([]), - citations: exports_external4.array(EvidencePointerSchema3).default([]), - freshness: exports_external4.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external4.array(exports_external4.string().min(1)).default([]), - redactions: exports_external4.array(exports_external4.string().min(1)).default([]), - conflicts: exports_external4.array(exports_external4.string().min(1)).default([]), - uncertainty: exports_external4.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema3 = NonEmptyStringSchema3.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema3 = exports_external4.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema3 = exports_external4.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema3 = exports_external4.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema3 = exports_external4.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.integrationRef).extend({ - kind: ProjectIntegrationKindSchema3, - name: exports_external4.string().min(1), - projectId: ProjectSlugSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - uri: UriSchema3.optional(), - enabled: exports_external4.boolean().default(true), - readOnly: exports_external4.boolean().default(true), - capabilities: exports_external4.array(exports_external4.string().min(1)).default([]), - freshness: exports_external4.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema3.optional(), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - config: MetadataSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema3 = exports_external4.object({ - schemaRoot: RelativeProjectPathSchema3.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema3.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema3.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema3.default("documents"), - reportsDir: RelativeProjectPathSchema3.default("reports"), - evidenceDir: RelativeProjectPathSchema3.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema3.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectManifest).extend({ - projectId: ProjectSlugSchema3, - slug: ProjectSlugSchema3, - name: exports_external4.string().min(1), - summary: exports_external4.string().min(1).optional(), - status: ProjectStatusSchema3.default("active"), - classification: ProjectClassificationSchema3.default("private"), - owner: ActorPointerSchema3.optional(), - layout: ProjectLayoutSchema3.default({}), - integrations: exports_external4.array(IntegrationRefSchema3).default([]), - renderManifests: exports_external4.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema3 = exports_external4.enum(["local", "package", "provider", "url"]); -var RenderImportSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - kind: RenderImportKindSchema3, - specifier: exports_external4.string().min(1), - path: RelativeProjectPathSchema3.optional(), - packageName: exports_external4.string().min(1).optional(), - uri: UriSchema3.optional(), - provider: ProjectIntegrationKindSchema3.optional(), - schemaId: SchemaIdSchema3.optional(), - integrity: HashStringSchema3.optional(), - resourceRef: ResourcePointerSchema3.optional(), - optional: exports_external4.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema3 = exports_external4.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - title: exports_external4.string().min(1), - kind: RenderViewKindSchema3, - default: exports_external4.boolean().default(false), - entry: RelativeProjectPathSchema3.optional(), - imports: exports_external4.array(RenderImportSchema3).default([]), - panelRefs: exports_external4.array(ResourcePointerSchema3).default([]), - dataRefs: exports_external4.array(ResourcePointerSchema3).default([]), - layout: MetadataSchema3.optional() -}).strict(); -var RenderManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.renderManifest).extend({ - projectId: ProjectSlugSchema3, - name: exports_external4.string().min(1), - version: exports_external4.string().min(1), - manifestPath: RelativeProjectPathSchema3.default(".hasna/project/dashboard.render.json"), - renderer: exports_external4.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external4.array(RenderViewSchema3).min(1), - imports: exports_external4.array(RenderImportSchema3).default([]), - theme: MetadataSchema3.optional(), - compatibility: exports_external4.object({ - minProjectsVersion: exports_external4.string().min(1).optional(), - minContractsVersion: exports_external4.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema3 = exports_external4.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema3 = exports_external4.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - label: exports_external4.string().min(1), - value: exports_external4.union([exports_external4.string(), exports_external4.number(), exports_external4.boolean()]), - unit: exports_external4.string().min(1).optional(), - status: exports_external4.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]) -}).strict(); -var ProjectPanelItemSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - title: exports_external4.string().min(1), - summary: exports_external4.string().min(1).optional(), - status: exports_external4.string().min(1).optional(), - priority: exports_external4.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema3.optional(), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - metadata: MetadataSchema3.optional() -}).strict(); -var ProjectRenderFragmentSchema3 = exports_external4.object({ - renderer: exports_external4.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external4.string().min(1).optional(), - entry: RelativeProjectPathSchema3.optional(), - imports: exports_external4.array(RenderImportSchema3).default([]), - spec: MetadataSchema3.default({}) -}).strict(); -var ProjectPanelSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectPanel).extend({ - projectId: ProjectSlugSchema3, - provider: exports_external4.object({ - kind: ProjectIntegrationKindSchema3, - id: exports_external4.string().min(1), - name: exports_external4.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - externalId: NonEmptyStringSchema3.optional() - }).strict(), - kind: ProjectPanelKindSchema3, - title: exports_external4.string().min(1), - summary: exports_external4.string().min(1).optional(), - state: ProjectPanelStateSchema3.default("ready"), - stateReason: exports_external4.string().min(1).optional(), - generatedAt: TimestampSchema3, - freshness: exports_external4.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external4.array(ProjectPanelMetricSchema3).default([]), - items: exports_external4.array(ProjectPanelItemSchema3).default([]), - actions: exports_external4.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - renderFragment: ProjectRenderFragmentSchema3.optional(), - warnings: exports_external4.array(exports_external4.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectSnapshot).extend({ - projectId: ProjectSlugSchema3, - generatedAt: TimestampSchema3, - status: ContractStatusSchema3.default("unknown"), - manifestRef: ResourcePointerSchema3, - renderManifestRef: ResourcePointerSchema3.optional(), - panels: exports_external4.array(ProjectPanelSchema3).default([]), - contextPacks: exports_external4.array(ContextPackSchema3).default([]), - proofBundleRefs: exports_external4.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - warnings: exports_external4.array(exports_external4.string().min(1)).default([]), - freshness: exports_external4.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - kind: exports_external4.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external4.boolean().default(true), - command: exports_external4.string().min(1).optional(), - expected: exports_external4.string().min(1).optional(), - timeoutMs: exports_external4.number().int().positive().optional(), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema3 = contractBaseSchema3(SCHEMA_IDS3.validationPlan).extend({ - objective: exports_external4.string().min(1), - subject: ResourcePointerSchema3.optional(), - checks: exports_external4.array(ValidationCheckSchema3).min(1), - verifier: ActorPointerSchema3.optional(), - requiredEvidenceKinds: exports_external4.array(EvidenceKindSchema3).default([]) -}).strict(); -var ScaffoldTypeSchema3 = exports_external4.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema3 = exports_external4.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema3 = exports_external4.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema3 = exports_external4.object({ - key: exports_external4.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external4.string().min(1), - required: exports_external4.boolean().default(false), - ["secret"]: exports_external4.boolean().default(false), - group: exports_external4.string().min(1).optional(), - default: exports_external4.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema3 = exports_external4.object({ - name: exports_external4.string().min(1), - command: exports_external4.string().min(1), - description: exports_external4.string().min(1).optional(), - required: exports_external4.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema3 = exports_external4.object({ - packageManager: exports_external4.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external4.array(exports_external4.string().min(1)).default([]), - requiredFiles: exports_external4.array(exports_external4.string().min(1)).default([]), - requiredDirectories: exports_external4.array(exports_external4.string().min(1)).default([]), - optionalDirectories: exports_external4.array(exports_external4.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.scaffoldManifest).extend({ - name: exports_external4.string().min(1), - version: exports_external4.string().min(1), - summary: exports_external4.string().min(1), - type: ScaffoldTypeSchema3, - status: ScaffoldStatusSchema3.default("draft"), - capabilities: exports_external4.array(ScaffoldCapabilitySchema3).default([]), - techStack: exports_external4.array(exports_external4.string().min(1)).default([]), - tags: TagsSchema3, - source: ResourcePointerSchema3.optional(), - output: ScaffoldOutputShapeSchema3, - env: exports_external4.array(ScaffoldEnvVarSchema3).default([]), - scripts: exports_external4.array(ScaffoldScriptSchema3).default([]), - validationChecks: exports_external4.array(ValidationCheckSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema3 = exports_external4.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema3 = contractBaseSchema3(SCHEMA_IDS3.scaffoldInstallRecord).extend({ - scaffoldId: exports_external4.string().min(1), - scaffoldVersion: exports_external4.string().min(1).optional(), - manifestRef: ResourcePointerSchema3.optional(), - target: ResourcePointerSchema3, - status: ScaffoldInstallStatusSchema3, - installedAt: TimestampSchema3.optional(), - installer: ActorPointerSchema3.optional(), - packageManager: exports_external4.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema3.optional(), - generatedFiles: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - proofBundleRefs: exports_external4.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema3 = exports_external4.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema3 = exports_external4.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema3 = exports_external4.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema3 = exports_external4.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema3 = NonEmptyStringSchema3.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema3 = exports_external4.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema3 = exports_external4.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema3 = exports_external4.object({ - transport: exports_external4.enum(["http", "stdio"]).default("http"), - bin: exports_external4.string().min(1).optional(), - url: UriSchema3.optional() -}).strict(); -var AppHttpSurfaceSchema3 = exports_external4.object({ - healthPath: exports_external4.string().min(1).default("/health"), - port: exports_external4.number().int().positive().optional(), - baseUrl: UriSchema3.optional() -}).strict(); -var AppSurfacesSchema3 = exports_external4.object({ - bins: exports_external4.array(exports_external4.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema3.optional(), - http: AppHttpSurfaceSchema3.optional() -}).strict(); -var AppSchema3 = contractBaseSchema3(SCHEMA_IDS3.app).extend({ - appId: AppIdSchema3, - npmName: NpmPackageNameSchema3, - repoFolder: AppIdSchema3, - githubUrl: GithubUrlSchema3, - projectSlug: ProjectSlugSchema3, - surfaces: AppSurfacesSchema3.default({}), - lifecycle: AppLifecycleSchema3, - releaseChannel: ReleaseChannelSchema3.default("stable"), - summary: exports_external4.string().min(1).optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema3 = exports_external4.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema3 = contractBaseSchema3(SCHEMA_IDS3.release).extend({ - appId: AppIdSchema3, - package: NpmPackageNameSchema3, - version: SemverSchema3, - gitSha: GitShaSchema3, - publishedAt: TimestampSchema3, - publishPath: PublishPathSchema3, - changelogRef: ResourcePointerSchema3.optional(), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema3 = exports_external4.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema3 = exports_external4.object({ - cliVersion: exports_external4.string().min(1).optional(), - mcpHealth: exports_external4.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema3 = contractBaseSchema3(SCHEMA_IDS3.rolloutRecord).extend({ - appId: AppIdSchema3, - package: NpmPackageNameSchema3, - version: SemverSchema3, - machine: NonEmptyStringSchema3, - action: RolloutActionSchema3, - result: ContractStatusSchema3, - verifiedBy: RolloutVerificationSchema3.optional(), - at: TimestampSchema3, - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema3 = exports_external4.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema3 = exports_external4.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema3 = exports_external4.object({ - channel: AnnouncementChannelKindSchema3, - status: AnnouncementDeliveryStatusSchema3, - deliveredAt: TimestampSchema3.optional(), - detail: exports_external4.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema3 = contractBaseSchema3(SCHEMA_IDS3.announcement).extend({ - campaignId: NonEmptyStringSchema3, - appId: AppIdSchema3.optional(), - releaseRef: ResourcePointerSchema3.optional(), - channels: exports_external4.array(AnnouncementChannelSchema3).min(1), - audienceRef: ResourcePointerSchema3, - sentAt: TimestampSchema3 -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema3 = exports_external4.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema3 = exports_external4.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema3 = exports_external4.union([exports_external4.string(), exports_external4.number(), exports_external4.boolean()]); -var AudiencePredicateSchema3 = exports_external4.object({ - kind: AudiencePredicateKindSchema3, - key: exports_external4.string().min(1).optional(), - op: AudiencePredicateOpSchema3.default("eq"), - value: AudiencePredicateValueSchema3.optional(), - values: exports_external4.array(AudiencePredicateValueSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema3 = exports_external4.object({ - match: exports_external4.enum(["all", "any"]).default("all"), - predicates: exports_external4.array(AudiencePredicateSchema3).min(1) -}).strict(); -var ConsentPolicySchema3 = exports_external4.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema3 = contractBaseSchema3(SCHEMA_IDS3.audience).extend({ - audienceId: AppIdSchema3, - name: NonEmptyStringSchema3, - definition: AudienceDefinitionSchema3, - consentPolicy: ConsentPolicySchema3, - suppressionSyncedAt: OptionalTimestampSchema3 -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES3 = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema3 = exports_external4.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - provider: AppCloudProviderSchema3, - kind: exports_external4.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external4.string().min(1), - region: exports_external4.string().min(1).optional(), - accountId: exports_external4.string().min(1).optional(), - uri: UriSchema3.optional(), - machineScoped: exports_external4.boolean().default(false) -}).strict(); -var AppCloudManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.appCloudManifest).extend({ - packageName: exports_external4.string().min(1), - packageVersion: exports_external4.string().min(1).optional(), - appId: exports_external4.string().min(1), - repository: ResourcePointerSchema3.optional(), - storageMode: exports_external4.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external4.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external4.array(AppCloudResourceSchema3).default([]), - localCache: exports_external4.object({ - path: exports_external4.string().min(1).optional(), - pullMode: exports_external4.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external4.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external4.array(exports_external4.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES3]), - dependencies: exports_external4.array(exports_external4.string().min(1)).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES3, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES3) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema3 = exports_external4.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema3 = exports_external4.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - kind: NoCloudCheckKindSchema3, - severity: NoCloudFindingSeveritySchema3, - path: exports_external4.string().min(1).optional(), - packageName: exports_external4.string().min(1).optional(), - pattern: exports_external4.string().min(1), - message: exports_external4.string().min(1), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict(); -var NoCloudCheckResultSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - kind: NoCloudCheckKindSchema3, - status: ContractStatusSchema3, - target: exports_external4.string().min(1), - command: exports_external4.string().min(1).optional(), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - findings: exports_external4.array(NoCloudFindingSchema3).default([]) -}).strict(); -var NoCloudEvidencePackSchema3 = contractBaseSchema3(SCHEMA_IDS3.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema3, - packageName: exports_external4.string().min(1).optional(), - packageVersion: exports_external4.string().min(1).optional(), - generatedBy: ActorPointerSchema3.optional(), - scanMode: exports_external4.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema3, - verdict: exports_external4.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema3.optional(), - checks: exports_external4.array(NoCloudCheckResultSchema3).min(1), - findings: exports_external4.array(NoCloudFindingSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check2) => check2.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check2) => check2.status !== "succeeded")) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check2) => check2.status === "failed")) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check2, index) => { - const checkBlockingFindings = check2.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check2.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema3 = exports_external4.object({ - checkId: exports_external4.string().min(1), - status: ContractStatusSchema3, - summary: exports_external4.string().min(1).optional(), - startedAt: OptionalTimestampSchema3, - finishedAt: OptionalTimestampSchema3, - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict(); -var ProofBundleSchema3 = contractBaseSchema3(SCHEMA_IDS3.proofBundle).extend({ - subject: ResourcePointerSchema3, - validationPlanRef: ResourcePointerSchema3.optional(), - status: ContractStatusSchema3, - verdict: exports_external4.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external4.array(ProofCheckResultSchema3).default([]), - verifier: ActorPointerSchema3.optional(), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - residualRisks: exports_external4.array(exports_external4.string().min(1)).default([]), - freshness: exports_external4.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check2, index) => { - if (check2.status !== "succeeded") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check2) => check2.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check2) => check2.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema3 = contractBaseSchema3(SCHEMA_IDS3.workRun).extend({ - objective: exports_external4.string().min(1), - status: ContractStatusSchema3, - actor: ActorPointerSchema3, - traceId: exports_external4.string().min(1).optional(), - startedAt: OptionalTimestampSchema3, - finishedAt: OptionalTimestampSchema3, - constraints: exports_external4.array(exports_external4.string().min(1)).default([]), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - decisions: exports_external4.array(DecisionEnvelopeSchema3).default([]), - costEstimates: exports_external4.array(CostEstimateSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - validationPlanRefs: exports_external4.array(ResourcePointerSchema3).default([]), - proofBundleRefs: exports_external4.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses3.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - at: TimestampSchema3, - kind: exports_external4.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external4.string().min(1), - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]), - costEstimate: CostEstimateSchema3.optional() -}).strict(); -var AgentTrajectorySchema3 = contractBaseSchema3(SCHEMA_IDS3.agentTrajectory).extend({ - actor: ActorPointerSchema3, - workRunRef: ResourcePointerSchema3.optional(), - events: exports_external4.array(TrajectoryEventSchema3).default([]), - outcome: exports_external4.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema3.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION3 = "v1"; -var RepoClassSchema3 = exports_external4.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES3 = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema3 = exports_external4.enum(DEPLOYMENT_MODES3); -var ServiceSurfaceStatusSchema3 = exports_external4.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema3 = exports_external4.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema3 = exports_external4.object({ - method: exports_external4.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external4.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external4.boolean().default(false), - description: exports_external4.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema3 = exports_external4.object({ - id: exports_external4.string().min(1), - kind: exports_external4.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external4.boolean().default(true), - command: exports_external4.string().min(1).optional(), - evidenceRef: EvidencePointerSchema3.optional(), - status: exports_external4.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external4.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema3 = exports_external4.object({ - name: exports_external4.string().min(1), - status: ServiceSurfaceStatusSchema3, - bin: exports_external4.string().min(1).optional(), - mcpBin: exports_external4.string().min(1).optional(), - authMode: ServiceAuthModeSchema3, - deploymentModes: exports_external4.array(DeploymentModeSchema3).min(1), - health: ServiceEndpointSchema3.optional(), - readiness: ServiceEndpointSchema3.optional(), - version: ServiceEndpointSchema3.optional(), - apiBasePath: exports_external4.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external4.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external4.string().min(1).optional(), - readinessGates: exports_external4.array(DeploymentReadinessGateSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES3 = ["local", "cloud"]; -var StorageModeSchema3 = exports_external4.enum(STORAGE_MODES3); -var DEPRECATED_STORAGE_MODE_ALIASES2 = ["remote", "hybrid", "self_hosted"]; -var AppNameSchema3 = exports_external4.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES3 = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName3(name) { - return ALLOWED_BIN_SUFFIXES3.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor3(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema3 = exports_external4.object({ - mode: StorageModeSchema3, - envPrefix: exports_external4.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external4.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external4.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external4.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema3 = exports_external4.object({ - $schema: exports_external4.string().min(1).optional(), - schema: exports_external4.literal(SCHEMA_IDS3.serviceContract), - name: AppNameSchema3, - class: RepoClassSchema3, - contractVersion: exports_external4.literal(SERVICE_CONTRACT_VERSION3), - kitVersion: exports_external4.string().min(1), - description: exports_external4.string().min(1).optional(), - bins: exports_external4.array(exports_external4.string().min(1)).default([]), - storage: StorageContractSchema3.optional(), - deploymentModes: exports_external4.array(DeploymentModeSchema3).default(["local"]), - serviceSurfaces: exports_external4.array(ServiceSurfaceSchema3).default([]), - metadata: MetadataSchema3.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName3(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor3(value.name)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor3(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna//.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } +var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); +function createHasnaHttpTransport(options) { + const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init)); + const base = toV1BaseUrl(options.baseUrl); + const timeoutMs = options.timeoutMs ?? 30000; + const sleep = options.sleepImpl ?? defaultSleep; + const defaultRetry = options.retry; + function resolveRetry(callRetry) { + const chosen = callRetry !== undefined ? callRetry : defaultRetry; + if (chosen === false) + return null; + const r = chosen ?? {}; + return { + retries: r.retries ?? 2, + baseDelayMs: r.baseDelayMs ?? 200, + maxDelayMs: r.maxDelayMs ?? 2000, + retryStatuses: r.retryStatuses ?? [...DEFAULT_RETRY_STATUSES] + }; } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); + async function once(method, rel, url2, body, opts, credential) { + assertNoAuthorityOverrideHeaders(options.headers, "transport"); + assertNoAuthorityOverrideHeaders(opts.headers, "request"); + const headers = { + "x-api-key": credential.apiKey, + Authorization: `Bearer ${credential.apiKey}`, + Accept: "application/json", + ...options.headers ?? {}, + ...opts.headers ?? {} + }; + if (opts.idempotencyKey) + headers["Idempotency-Key"] = opts.idempotencyKey; + const init = { + method, + headers, + redirect: "manual" + }; + if (body !== undefined) { + headers["Content-Type"] = "application/json"; + init.body = JSON.stringify(body); } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external4.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); + const controller = new AbortController; + const onAbort = () => controller.abort(); + if (opts.signal) { + if (opts.signal.aborted) + controller.abort(); + else + opts.signal.addEventListener("abort", onAbort, { once: true }); } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); + const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? timeoutMs); + init.signal = controller.signal; + let response; + try { + response = await fetchImpl(url2, init); + } catch (error51) { + const err = error51 instanceof Error ? error51 : new Error(String(error51)); + if (opts.signal?.aborted) + return { ok: false, retryable: false, error: err }; + return { ok: false, retryable: true, error: err }; + } finally { + clearTimeout(timer); + if (opts.signal) + opts.signal.removeEventListener("abort", onAbort); } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); + const text = await response.text(); + let parsed = undefined; + if (text.length > 0) { + try { + parsed = JSON.parse(text); + } catch { + parsed = text; + } } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); + if (!response.ok) { + if (response.status >= 300 && response.status < 400) { + return { + ok: false, + retryable: false, + error: new HasnaHttpError(method, rel, response.status, parsed) + }; + } + if (response.status === 401 || response.status === 403) { + return { + ok: false, + retryable: false, + error: new HasnaHttpError(method, rel, response.status, parsed, { + source: credential.source, + tier: credential.tier, + guidance: authFailureGuidance(credential) + }) + }; } + const retry = resolveRetry(opts.retry); + const retryable = retry ? retry.retryStatuses.includes(response.status) : false; + return { ok: false, retryable, error: new HasnaHttpError(method, rel, response.status, parsed) }; } + return { ok: true, value: parsed }; } -}); -var HealthResponseSchema3 = exports_external4.object({ - status: exports_external4.enum(["ok", "degraded", "unavailable"]), - version: exports_external4.string().min(1), - mode: StorageModeSchema3 -}).strict(); -var ReadyResponseSchema3 = exports_external4.object({ - ready: exports_external4.boolean(), - reason: exports_external4.string().min(1).optional() -}).strict(); -var VersionResponseSchema3 = exports_external4.object({ - version: exports_external4.string().min(1) -}).strict(); -var CommsSeveritySchema3 = exports_external4.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema3 = exports_external4.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (..)"); -var COMMS_SEVERITY_TAGS3 = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema3 = exports_external4.enum(COMMS_SEVERITY_TAGS3); -var CommsScopeSchema3 = exports_external4.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsEventEnvelope).extend({ - type: CommsEventTypeSchema3, - severity: CommsSeveritySchema3, - scope: CommsScopeSchema3, - summary: exports_external4.string().min(1).optional(), - source: ActorPointerSchema3.optional(), - affected_packages: exports_external4.array(NonEmptyStringSchema3).default([]), - affected_machines: exports_external4.array(NonEmptyStringSchema3).default([]), - action_required: exports_external4.boolean().default(false), - ack_by: TimestampSchema3.optional(), - dedupe_key: NonEmptyStringSchema3, - resourceRefs: exports_external4.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external4.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); + async function request(method, path, body, opts = {}) { + const upper = method.toUpperCase(); + const rel = appendQuery(path.startsWith("/") ? path : `/${path}`, opts.query); + const url2 = `${base}${rel}`; + const retry = resolveRetry(opts.retry); + const methodRetryable = IDEMPOTENT_METHODS.has(upper) || Boolean(opts.idempotencyKey); + const maxAttempts = retry && methodRetryable ? retry.retries + 1 : 1; + const credential = currentCredential(options.name, options.apiKey); + let last = null; + for (let attempt = 1;attempt <= maxAttempts; attempt++) { + const result = await once(upper, rel, url2, body, opts, credential); + if (result.ok) + return result.value; + last = result; + const canRetry = retry !== null && methodRetryable && result.retryable && attempt < maxAttempts; + if (!canRetry) + break; + const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1)); + const jitter = Math.floor(Math.random() * (backoff / 2 + 1)); + await sleep(backoff + jitter); + } + throw last.error; } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); + return { + baseUrl: base, + request, + get: (path, opts) => request("GET", path, undefined, opts), + post: (path, body, opts) => request("POST", path, body, opts), + put: (path, body, opts) => request("PUT", path, body, opts), + patch: (path, body, opts) => request("PATCH", path, body, opts), + del: (path, body, opts) => request("DELETE", path, body, opts) + }; +} +function createClientTransport(name, env = process.env, overrides) { + const credentialOptions = overrides?.credentials; + const resolution = resolveClientTransport(name, env, { ...credentialOptions ? { credentials: credentialOptions } : {} }); + if (resolution.misconfigured) { + throw new Error(resolution.warning ?? `Client for '${name}' is misconfigured for the API client.`); } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); + if (resolution.transport === "sqlite" || !resolution.baseUrl) { + return { transport: "sqlite", client: null, resolution }; } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); + const credentialProvider = () => { + const resolved = resolveCredential(name, env, credentialOptions); + if (!resolved) { + throw new Error(`Client for '${name}' resolved to the http transport but no API key is available any more. ` + `Looked at ${credentialDiskSourcesForMessage(name, env)}, then the environment. ` + `A credential file that was removed after this client was built is the usual cause.`); } + return resolved; + }; + return { + transport: "http", + client: createHasnaHttpTransport({ + name, + baseUrl: resolution.baseUrl, + apiKey: credentialProvider, + ...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {}, + ...overrides?.headers ? { headers: overrides.headers } : {}, + ...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {}, + ...overrides?.retry !== undefined ? { retry: overrides.retry } : {}, + ...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {} + }), + resolution + }; +} +function resourcePath(resource) { + const trimmed = resource.replace(/^\/+|\/+$/g, ""); + if (!trimmed) + throw new Error("resource must be a non-empty path segment"); + return `/${trimmed}`; +} +function entityPath(resource, id) { + if (id === undefined || id === null || `${id}`.length === 0) { + throw new Error("id must be a non-empty string"); } -}); -var CommsChannelClassSchema3 = exports_external4.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema3 = exports_external4.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema3 = NonEmptyStringSchema3.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"); -var CommsChannelMetadataSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsChannelMetadata).extend({ - class: CommsChannelClassSchema3, - noise: CommsChannelNoiseSchema3.optional(), - owner: NonEmptyStringSchema3.optional(), - until: CommsUntilHorizonSchema3.optional(), - successor: NonEmptyStringSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); + return `${resourcePath(resource)}/${encodeURIComponent(String(id))}`; +} +function newIdempotencyKey() { + const g = globalThis; + if (g.crypto?.randomUUID) + return g.crypto.randomUUID(); + return `idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`; +} +function extractItems(raw) { + if (Array.isArray(raw)) + return raw; + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["items", "data", "results", "rows", "records"]) { + if (Array.isArray(obj[key])) + return obj[key]; } } -}); -var COMMS_SEVERITY_TAG_INFO3 = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema3, - envelope: CommsEventEnvelopeSchema3 -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO3[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); + return []; +} +function extractTotal(raw) { + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["total", "count", "totalCount", "total_count"]) { + if (typeof obj[key] === "number") + return obj[key]; + } } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); + return null; +} +function extractCursor(raw) { + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["cursor", "nextCursor", "next_cursor", "next"]) { + if (typeof obj[key] === "string") + return obj[key]; + } } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO3)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external4.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] + return null; +} +function createHasnaStorageClient(name, transport) { + return { + name, + baseUrl: transport.baseUrl, + transport, + async list(resource, options = {}) { + const raw = await transport.get(resourcePath(resource), options); + return { + items: extractItems(raw), + total: extractTotal(raw), + cursor: extractCursor(raw), + raw + }; + }, + async get(resource, id, options = {}) { + try { + return await transport.get(entityPath(resource, id), options); + } catch (error51) { + if (error51 instanceof HasnaHttpError && error51.status === 404) + return null; + throw error51; + } + }, + async create(resource, body, options = {}) { + const { idempotencyKey, ...rest } = options; + return transport.post(resourcePath(resource), body, { + ...rest, + idempotencyKey: idempotencyKey ?? newIdempotencyKey() }); + }, + async update(resource, id, patch, options = {}) { + const { method = "PATCH", idempotencyKey, ...rest } = options; + const call = method === "PUT" ? transport.put : transport.patch; + return call(entityPath(resource, id), patch, { ...rest, ...idempotencyKey ? { idempotencyKey } : {} }); + }, + async delete(resource, id, options = {}) { + try { + await transport.del(entityPath(resource, id), undefined, options); + } catch (error51) { + if (error51 instanceof HasnaHttpError && error51.status === 404) + return; + throw error51; + } } + }; +} +function resolveStorageClient(name, env = process.env, overrides) { + const wired = createClientTransport(name, env, overrides); + if (wired.transport === "http") { + return { transport: "http", client: createHasnaStorageClient(name, wired.client) }; } -}); -var ContractSchemaRegistry3 = { - [SCHEMA_IDS3.actorRef]: ActorRefSchema3, - [SCHEMA_IDS3.resourceRef]: ResourceRefSchema3, - [SCHEMA_IDS3.evidenceRef]: EvidenceRefSchema3, - [SCHEMA_IDS3.workRun]: WorkRunSchema3, - [SCHEMA_IDS3.decisionEnvelope]: DecisionEnvelopeSchema3, - [SCHEMA_IDS3.costEstimate]: CostEstimateSchema3, - [SCHEMA_IDS3.capabilityCard]: CapabilityCardSchema3, - [SCHEMA_IDS3.providerLiveModeStandard]: ProviderLiveModeStandardSchema3, - [SCHEMA_IDS3.contextPack]: ContextPackSchema3, - [SCHEMA_IDS3.integrationRef]: IntegrationRefSchema3, - [SCHEMA_IDS3.projectManifest]: ProjectManifestSchema3, - [SCHEMA_IDS3.projectPanel]: ProjectPanelSchema3, - [SCHEMA_IDS3.projectSnapshot]: ProjectSnapshotSchema3, - [SCHEMA_IDS3.renderManifest]: RenderManifestSchema3, - [SCHEMA_IDS3.agentTrajectory]: AgentTrajectorySchema3, - [SCHEMA_IDS3.validationPlan]: ValidationPlanSchema3, - [SCHEMA_IDS3.proofBundle]: ProofBundleSchema3, - [SCHEMA_IDS3.scaffoldManifest]: ScaffoldManifestSchema3, - [SCHEMA_IDS3.scaffoldInstallRecord]: ScaffoldInstallRecordSchema3, - [SCHEMA_IDS3.appCloudManifest]: AppCloudManifestSchema3, - [SCHEMA_IDS3.noCloudEvidencePack]: NoCloudEvidencePackSchema3, - [SCHEMA_IDS3.serviceContract]: ServiceContractManifestSchema3, - [SCHEMA_IDS3.commsEventEnvelope]: CommsEventEnvelopeSchema3, - [SCHEMA_IDS3.commsChannelMetadata]: CommsChannelMetadataSchema3, - [SCHEMA_IDS3.commsMessageMetadata]: CommsMessageMetadataSchema3, - [SCHEMA_IDS3.app]: AppSchema3, - [SCHEMA_IDS3.release]: ReleaseSchema3, - [SCHEMA_IDS3.rolloutRecord]: RolloutRecordSchema3, - [SCHEMA_IDS3.announcement]: AnnouncementSchema3, - [SCHEMA_IDS3.audience]: AudienceSchema3 -}; + return { transport: "sqlite", client: null }; +} + +// node_modules/@hasna/contracts/dist/client/transport.js +function envToken2(name) { + return name.toUpperCase().replace(/-/g, "_"); +} +function clientTransportEnvKeys2(name) { + const envSegment = envToken2(name); + return { + modeKeys: [ + `HASNA_${envSegment}_STORAGE_MODE`, + `HASNA_${envSegment}_MODE`, + `${envSegment}_STORAGE_MODE`, + `${envSegment}_MODE` + ], + apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], + apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] + }; +} +var MAX_CREDENTIAL_FILE_BYTES2 = 64 * 1024; +var INSPECT_CUSTOM2 = Symbol.for("nodejs.util.inspect.custom"); +var DEPRECATION_REGISTRY2 = Symbol.for("hasna:contracts:credentialDeprecationNotices"); +var IDEMPOTENT_METHODS2 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); +var AUTHORITY_OVERRIDE_HEADERS2 = new Set([ + "host", + ":authority", + "forwarded", + "x-forwarded-host", + "x-original-host" +]); + +// node_modules/@hasna/contracts/dist/mode.js function normalizeStorageMode2(value) { const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES2.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); } // src/generated/storage-kit/mode.ts -var DEPRECATED_STORAGE_MODE_ALIASES3 = [ - "remote", - "hybrid", - "self_hosted" -]; function normalizeStorageMode3(value) { const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES3.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); } // src/generated/storage-kit/pool.ts import pg from "pg"; @@ -33814,7 +16290,7 @@ function assertOutboundRequestAllowed(input, env = process.env) { } if (isLoopbackHostname(url2.hostname)) return; - throw new KnowledgeNetworkGuardError(`knowledge: refused a non-loopback ${url2.protocol.replace(":", "")} request while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). This process resolved to the cloud backend under test, which means a " + "read or write was about to leave the machine and reach the live store. Select the mode explicitly " + `(${"HASNA_KNOWLEDGE_STORAGE_MODE"}=local) or point the API URL at 127.0.0.1 for a hermetic test.`, { scheme: url2.protocol.replace(":", ""), port: url2.port }); + throw new KnowledgeNetworkGuardError(`knowledge: refused a non-loopback ${url2.protocol.replace(":", "")} request while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). This process resolved to the cloud backend under test, which means a " + "read or write was about to leave the machine and reach the live store. Select the mode explicitly " + `(${"HASNA_KNOWLEDGE_STORAGE_MODE"}=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`, { scheme: url2.protocol.replace(":", ""), port: url2.port }); } var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); var MAX_GUARDED_REDIRECTS = 5; @@ -33886,33 +16362,30 @@ function resolveKnowledgeModeSelection(env = process.env) { throw new Error(`knowledge: ${name}=${value} is not a valid mode. ${message}`); } const warnings = []; - if (normalized.deprecatedAlias) { - warnings.push(`Deprecated mode '${normalized.deprecatedAlias}' from ${name} is treated as 'cloud'. Prefer ${canonicalModeKey}=cloud.`); - } if (name !== canonicalModeKey) { warnings.push(`Using alias env ${name}; the canonical key is ${canonicalModeKey}.`); } - if (normalized.mode === "local" && pointers.length > 0) { - warnings.push(`${name}=local pins the on-box store; ${pointers.join(", ")} are set but ignored.`); + if (normalized.mode === "sqlite" && pointers.length > 0) { + warnings.push(`${name}=sqlite pins the on-box store; ${pointers.join(", ")} are set but ignored.`); } return { mode: normalized.mode, source: { kind: "env", name, value }, pointer_env_present: pointers, - pointer_ignored: normalized.mode === "local" && pointers.length > 0, + pointer_ignored: normalized.mode === "sqlite" && pointers.length > 0, warning: warnings.length > 0 ? warnings.join(" ") : null }; } return { - mode: "local", + mode: "sqlite", source: { kind: "default", name: null, value: null }, pointer_env_present: pointers, pointer_ignored: pointers.length > 0, - warning: pointers.length > 0 ? `${pointers.join(", ")} are set but do NOT select a backend: mode is local by default. ` + `Set ${canonicalModeKey}=cloud to route reads and writes to the API, or unset those vars to silence this note.` : null + warning: pointers.length > 0 ? `${pointers.join(", ")} are set but do NOT select a backend: mode is sqlite by default. ` + `Set ${canonicalModeKey}=postgres to route reads and writes to the API, or unset those vars to silence this note.` : null }; } -var SERVER_MODE_CANDIDATES = ["postgres", "cloud", "self_hosted"]; -var LOCAL_MODE_CANDIDATES = ["sqlite", "local"]; +var SERVER_MODE_CANDIDATES = ["postgres"]; +var LOCAL_MODE_CANDIDATES = ["sqlite"]; var derivedTokenCache = new Map; function deriveToken(candidates, normalize, constantName) { const useCache = normalize === normalizeStorageMode2; @@ -33938,7 +16411,7 @@ function localStorageMode(normalize = normalizeStorageMode2) { return deriveToken(LOCAL_MODE_CANDIDATES, normalize, "LOCAL_MODE_CANDIDATES"); } function contractsStorageModeFor(mode2, normalize = normalizeStorageMode2) { - return mode2 === "cloud" ? serverStorageMode(normalize) : localStorageMode(normalize); + return mode2 === "postgres" ? serverStorageMode(normalize) : localStorageMode(normalize); } function pinnedTransportEnv(env, mode2) { return { ...env, [KNOWLEDGE_MODE_ENV_KEYS[0]]: contractsStorageModeFor(mode2) }; @@ -33948,7 +16421,7 @@ class HalfConfiguredKnowledgeClientError extends Error { code = "knowledge_mode_unset_with_api_url"; constructor(urlKeysPresent) { const canonical = KNOWLEDGE_MODE_ENV_KEYS[0]; - super(`knowledge: ${urlKeysPresent.join(", ")} names an API store, but no mode variable says to use it, ` + "so this command would silently read and write the on-box store instead. " + `Set ${canonical}=cloud to use the API, or ${canonical}=local to confirm you want the on-box store. ` + `Run 'knowledge mode' to see the full resolution.`); + super(`knowledge: ${urlKeysPresent.join(", ")} names an API store, but no mode variable says to use it, ` + "so this command would silently read and write the on-box store instead. " + `Set ${canonical}=postgres to use the API, or ${canonical}=sqlite to confirm you want the on-box store. ` + `Run 'knowledge mode' to see the full resolution.`); this.name = "HalfConfiguredKnowledgeClientError"; } } @@ -34089,17 +16562,17 @@ function isNotFound(error51) { return Boolean(error51 && typeof error51 === "object" && error51.status === 404); } function resolveKnowledgeCloudStore(env = process.env) { - if (resolveKnowledgeModeSelection(env).mode !== "cloud") + if (resolveKnowledgeModeSelection(env).mode !== "postgres") return null; - const resolved = resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "cloud"), transportOverrides(env)); - if (resolved.transport !== "cloud-http") + const resolved = resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "postgres"), transportOverrides(env)); + if (resolved.transport !== "http") return null; return wrap(resolved.client); } function isKnowledgeApiMode(env = process.env) { - if (resolveKnowledgeModeSelection(env).mode !== "cloud") + if (resolveKnowledgeModeSelection(env).mode !== "postgres") return false; - return resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "cloud"), transportOverrides(env)).transport === "cloud-http"; + return resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "postgres"), transportOverrides(env)).transport === "http"; } async function fetchAllCloudItems(store) { const pageSize = 200; @@ -34767,13 +17240,13 @@ import { fsyncSync, lstatSync, openSync, - readFileSync as readFileSync2, + readFileSync as readFileSync3, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs"; import { randomUUID } from "crypto"; -import { basename, dirname as dirname2, join as join2 } from "path"; +import { basename, dirname as dirname2, join as join3 } from "path"; function defaultStorePath() { return workspaceForHome(globalKnowledgeHome()).jsonStorePath; } @@ -34815,7 +17288,7 @@ function writeJsonFile(path, value) { chmodSync2(path, 384); } function readStoreFileForImport(path) { - const value = JSON.parse(readFileSync2(path, "utf8")); + const value = JSON.parse(readFileSync3(path, "utf8")); if (!value || typeof value !== "object" || !Array.isArray(value.items)) { return { store: { items: [] }, skippedInvalid: 0 }; } @@ -34907,18 +17380,18 @@ function importLegacyGlobalStoreUnlocked(options = {}) { return result; const suffix = `${timestampForPath(now)}-${randomUUID().slice(0, 8)}`; if (canonicalExisted) { - result.backup_path = join2(workspace.exportsDir, `legacy-open-knowledge-db-before-import-${suffix}.json`); + result.backup_path = join3(workspace.exportsDir, `legacy-open-knowledge-db-before-import-${suffix}.json`); writeJsonFile(result.backup_path, canonicalStore); } writeJsonFile(canonicalPath, merged); - result.report_path = join2(workspace.runsDir, `legacy-open-knowledge-import-${suffix}.json`); + result.report_path = join3(workspace.runsDir, `legacy-open-knowledge-import-${suffix}.json`); writeJsonFile(result.report_path, result); return result; } function loadStoreIfExists(path) { if (!existsSync2(path)) return { exists: false, items: [] }; - const raw = readFileSync2(path, "utf8"); + const raw = readFileSync3(path, "utf8"); const parsed = JSON.parse(raw); if (!parsed || !Array.isArray(parsed.items)) { return { exists: true, items: [] }; @@ -34951,7 +17424,7 @@ function syncParentDir(path) { var heldLockPaths = new Set; function writeFileAtomic(path, contents) { ensureParentDir(path); - const tmp = join2(dirname2(path), `.${basename(path)}.tmp.${randomUUID()}`); + const tmp = join3(dirname2(path), `.${basename(path)}.tmp.${randomUUID()}`); let fd = null; try { fd = openSync(tmp, "wx", 384); @@ -34991,7 +17464,7 @@ function processIsAlive(pid) { } function lockIsStale(path, now) { try { - const raw = readFileSync2(path, "utf8"); + const raw = readFileSync3(path, "utf8"); const lock = JSON.parse(raw); if (typeof lock.ts === "number") { return now - lock.ts > LOCK_STALE_MS && !processIsAlive(lock.pid); @@ -35077,7 +17550,7 @@ function acquireLock(lockPath2, ownerId) { function releaseLock(lockPath2, ownerId) { try { if (existsSync2(lockPath2)) { - const lock = JSON.parse(readFileSync2(lockPath2, "utf8")); + const lock = JSON.parse(readFileSync3(lockPath2, "utf8")); if (lock.owner === ownerId) { unlinkSync(lockPath2); } @@ -35086,7 +17559,7 @@ function releaseLock(lockPath2, ownerId) { } function loadStore(path) { ensureStore(path); - const raw = readFileSync2(path, "utf8"); + const raw = readFileSync3(path, "utf8"); const parsed = JSON.parse(raw); if (!parsed || !Array.isArray(parsed.items)) { return { items: [] }; @@ -35126,7 +17599,7 @@ class VersionHistoryUnsupportedError extends Error { location; code = "version_history_unsupported"; constructor(location) { - super("Version history is not kept by the local JSON knowledge store " + `(${location}). It has no version line, so an empty history here would be a claim, not a measurement. ` + "Entry versioning lives in the Postgres-backed store: point this CLI at it " + "(HASNA_KNOWLEDGE_STORAGE_MODE=cloud plus the API url/key) and re-run."); + super("Version history is not kept by the local JSON knowledge store " + `(${location}). It has no version line, so an empty history here would be a claim, not a measurement. ` + "Entry versioning lives in the Postgres-backed store: point this CLI at it " + "(HASNA_KNOWLEDGE_STORAGE_MODE=postgres plus the API url/key) and re-run."); this.location = location; this.name = "VersionHistoryUnsupportedError"; } @@ -35356,8 +17829,8 @@ function revisionIdForSourceRef(uri) { } // src/artifact-store.ts -import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, statSync, writeFileSync as writeFileSync3 } from "fs"; -import { dirname as dirname3, join as join3, relative, sep } from "path"; +import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync4, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs"; +import { dirname as dirname3, join as join4, relative, sep } from "path"; import { pathToFileURL } from "url"; function normalizeArtifactKey(key) { const raw = key.replace(/\\/g, "/").trim(); @@ -35400,22 +17873,22 @@ class LocalArtifactStore { } async put(entry) { const key = normalizeArtifactKey(entry.key); - const path = join3(this.root, key); + const path = join4(this.root, key); assertInside(this.root, path); mkdirSync2(dirname3(path), { recursive: true, mode: 448 }); writeFileSync3(path, entry.body, { mode: 384 }); chmodSync3(path, 384); - return { key, uri: pathToFileURL(path).href, modified_at: statSync(path).mtime.toISOString() }; + return { key, uri: pathToFileURL(path).href, modified_at: statSync2(path).mtime.toISOString() }; } async getText(key) { const normalizedKey = normalizeArtifactKey(key); - const path = join3(this.root, normalizedKey); + const path = join4(this.root, normalizedKey); assertInside(this.root, path); - return readFileSync3(path, "utf8"); + return readFileSync4(path, "utf8"); } async exists(key) { const normalizedKey = normalizeArtifactKey(key); - const path = join3(this.root, normalizedKey); + const path = join4(this.root, normalizedKey); assertInside(this.root, path); return existsSync4(path); } @@ -35522,9 +17995,9 @@ function createArtifactStore(config2, workspace) { // src/service.ts import { createHash as createHash19 } from "crypto"; import { spawnSync as spawnSync2 } from "child_process"; -import { existsSync as existsSync14, readFileSync as readFileSync12 } from "fs"; +import { existsSync as existsSync14, readFileSync as readFileSync13 } from "fs"; import { hostname as hostname5 } from "os"; -import { join as join8, resolve as resolve5 } from "path"; +import { join as join9, resolve as resolve5 } from "path"; // src/app-wiki.ts import { createHash as createHash6, randomUUID as randomUUID4 } from "crypto"; @@ -35532,13 +18005,13 @@ import { createHash as createHash6, randomUUID as randomUUID4 } from "crypto"; // src/storage-contract.ts import { createHash, randomUUID as randomUUID2 } from "crypto"; import { existsSync as existsSync6, readdirSync } from "fs"; -import { join as join5 } from "path"; +import { join as join6 } from "path"; import { pathToFileURL as pathToFileURL2 } from "url"; // src/auth.ts -import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs"; +import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync5, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs"; import { homedir as homedir2 } from "os"; -import { dirname as dirname4, join as join4 } from "path"; +import { dirname as dirname4, join as join5 } from "path"; var DEFAULT_KNOWLEDGE_API_URL = "https://knowledge.md"; function normalizeKnowledgeApiOrigin(apiUrl) { const url2 = new URL(apiUrl); @@ -35558,8 +18031,8 @@ function normalizeKnowledgeApiOrigin(apiUrl) { function knowledgeAuthPath(env = process.env) { if (env.HASNA_KNOWLEDGE_AUTH_PATH) return env.HASNA_KNOWLEDGE_AUTH_PATH; - const root = env.HASNA_KNOWLEDGE_AUTH_DIR ?? join4(homedir2(), ".hasna", "knowledge"); - return join4(root, "auth.json"); + const root = env.HASNA_KNOWLEDGE_AUTH_DIR ?? join5(homedir2(), ".hasna", "knowledge"); + return join5(root, "auth.json"); } function resolveKnowledgeApiUrl(config2, env = process.env) { return normalizeKnowledgeApiOrigin(env.KNOWLEDGE_API_URL ?? config2?.hosted?.api_url ?? DEFAULT_KNOWLEDGE_API_URL); @@ -35569,7 +18042,7 @@ function getKnowledgeAuth(env = process.env) { const path = knowledgeAuthPath(env); if (!existsSync5(path)) return null; - const parsed = JSON.parse(readFileSync4(path, "utf8")); + const parsed = JSON.parse(readFileSync5(path, "utf8")); return typeof parsed.api_key === "string" && parsed.api_key.length > 0 ? parsed : null; } catch { return null; @@ -35664,9 +18137,9 @@ var FORBIDDEN_WORKSPACE_FILES = [ ]; function forbiddenWorkspaceFilesPresent(workspace) { const present = []; - if (existsSync6(join5(workspace.home, "cloud.env"))) + if (existsSync6(join6(workspace.home, "cloud.env"))) present.push("cloud.env"); - if (existsSync6(join5(workspace.home, "migration-exports"))) + if (existsSync6(join6(workspace.home, "migration-exports"))) present.push("migration-exports"); if (existsSync6(workspace.home)) { for (const entry of readdirSync(workspace.home)) { @@ -35954,12 +18427,12 @@ function withProvenance(metadata, provenance) { // src/source-ingest.ts import { createHash as createHash5 } from "crypto"; -import { existsSync as existsSync8, readFileSync as readFileSync6 } from "fs"; +import { existsSync as existsSync8, readFileSync as readFileSync7 } from "fs"; import { basename as basename3 } from "path"; // src/manifest-ingest.ts import { createHash as createHash4 } from "crypto"; -import { existsSync as existsSync7, readFileSync as readFileSync5 } from "fs"; +import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs"; import { basename as basename2 } from "path"; // src/safety.ts @@ -36523,7 +18996,7 @@ async function readManifestInput(input, config2, safetyPolicy, maxInputBytes = D const text = input.startsWith("s3://") ? await readS3Text(input, config2, safetyPolicy) : (() => { if (!existsSync7(input)) throw new Error(`Manifest not found: ${input}`); - return readFileSync5(input, "utf8"); + return readFileSync6(input, "utf8"); })(); const bytes = Buffer.byteLength(text); if (bytes > maxInputBytes) { @@ -37140,7 +19613,7 @@ async function readDirectSourceText(parsed, config2, safetyPolicy) { if (parsed.kind === "file") { if (!existsSync8(parsed.path)) throw new Error(`Source file not found: ${parsed.path}`); - const text = readFileSync6(parsed.path, "utf8"); + const text = readFileSync7(parsed.path, "utf8"); return { text, contentSource: "file", @@ -37976,7 +20449,7 @@ function recordProviderUsage(db, input) { import { createHash as createHash8 } from "crypto"; // src/search.ts -import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs"; +import { existsSync as existsSync9, readFileSync as readFileSync8 } from "fs"; // src/embeddings.ts import { createHash as createHash7 } from "crypto"; @@ -38561,7 +21034,7 @@ function readLegacyItems(path) { if (!path || !existsSync9(path)) return []; try { - const parsed = JSON.parse(readFileSync7(path, "utf8")); + const parsed = JSON.parse(readFileSync8(path, "utf8")); if (!parsed || !Array.isArray(parsed.items)) return []; return parsed.items.filter((item) => { @@ -40064,7 +22537,7 @@ import { randomUUID as randomUUID8 } from "crypto"; // src/sync.ts import { createHash as createHash10, randomUUID as randomUUID7 } from "crypto"; -import { existsSync as existsSync10, readFileSync as readFileSync8 } from "fs"; +import { existsSync as existsSync10, readFileSync as readFileSync9 } from "fs"; import { hostname as hostname3 } from "os"; import { fileURLToPath as fileURLToPath2 } from "url"; import { extname, relative as relative3, resolve as resolve3, sep as sep3 } from "path"; @@ -40869,7 +23342,7 @@ function createKnowledgeSyncBundle(options) { if (!isTextArtifact(row.content_type, key)) { warnings.push(`artifact_content_not_embedded_binary:${row.id}`); } else { - const text = readFileSync8(path, "utf8"); + const text = readFileSync9(path, "utf8"); const redactedText = redactPrivateRefs(text); if (redactedText !== text) warnings.push(`artifact_content_redacted:${row.id}`); @@ -42163,7 +24636,7 @@ async function proposeKnowledgeSyncConflictResolutionWithAi(options) { // src/outbox-consume.ts import { createHash as createHash11, randomUUID as randomUUID9 } from "crypto"; -import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs"; +import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs"; import { basename as basename4 } from "path"; function stableId6(prefix, value) { return `${prefix}_${createHash11("sha256").update(value).digest("hex").slice(0, 20)}`; @@ -42310,7 +24783,7 @@ async function readOutboxInput(input, config2, safetyPolicy) { return readS3Text3(input, config2, safetyPolicy); if (!existsSync11(input)) throw new Error(`Outbox not found: ${input}`); - return readFileSync9(input, "utf8"); + return readFileSync10(input, "utf8"); } function mergeJson(existing, patch) { let base = {}; @@ -44363,8 +26836,8 @@ async function refreshEmbeddingIndex(options) { // src/rules-provenance.ts import { createHash as createHash14 } from "crypto"; -import { existsSync as existsSync12, lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync10, statSync as statSync2 } from "fs"; -import { basename as basename5, extname as extname2, join as join6, relative as relative4, resolve as resolve4, sep as sep4 } from "path"; +import { existsSync as existsSync12, lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync11, statSync as statSync3 } from "fs"; +import { basename as basename5, extname as extname2, join as join7, relative as relative4, resolve as resolve4, sep as sep4 } from "path"; import { pathToFileURL as pathToFileURL3 } from "url"; var DEFAULT_MAX_ITEMS2 = 100; var DEFAULT_EVIDENCE_LIMIT = 25; @@ -44562,7 +27035,7 @@ function collectFiles(root, skipped) { const basePath = resolve4(root, entry.base); if (!existsSync12(basePath)) continue; - const rootStats = statSync2(basePath); + const rootStats = statSync3(basePath); if (rootStats.isFile()) { const rel = basename5(basePath); if (entry.spec.include(rel)) { @@ -44593,7 +27066,7 @@ function walkRuleDirectory(input) { if (input.depth > input.maxDepth) return; for (const dirent of readdirSync2(input.basePath, { withFileTypes: true })) { - const absPath = join6(input.basePath, dirent.name); + const absPath = join7(input.basePath, dirent.name); const rel = relativePath(rootBasePath, absPath); if (dirent.isSymbolicLink()) continue; @@ -44709,7 +27182,7 @@ function prepareFileRecord(input) { }; return { evidence: evidence2, text: "", manifest: null }; } - const bytes = readFileSync10(sourcePath); + const bytes = readFileSync11(sourcePath); const rawText = bytes.toString("utf8"); const redacted = redactSecrets(rawText, input.safetyPolicy); const highSeverity = redacted.findings.some((finding) => finding.severity === "high"); @@ -45925,12 +28398,12 @@ import { lstatSync as lstatSync3, mkdirSync as mkdirSync4, readdirSync as readdirSync3, - readFileSync as readFileSync11, + readFileSync as readFileSync12, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync5 } from "fs"; -import { dirname as dirname5, join as join7, relative as relative5 } from "path"; +import { dirname as dirname5, join as join8, relative as relative5 } from "path"; function walkFiles(root, base = root) { if (!existsSync13(root)) return []; @@ -45939,7 +28412,7 @@ function walkFiles(root, base = root) { return [relative5(base, root) || "."]; if (!stat.isDirectory()) return []; - return readdirSync3(root).flatMap((entry) => walkFiles(join7(root, entry), base)).sort(); + return readdirSync3(root).flatMap((entry) => walkFiles(join8(root, entry), base)).sort(); } function hashFiles(root, files) { if (files.length === 0) @@ -45947,8 +28420,8 @@ function hashFiles(root, files) { const tree = createHash18("sha256"); let bytes = 0; for (const file2 of files) { - const path = join7(root, file2); - const body = readFileSync11(path); + const path = join8(root, file2); + const body = readFileSync12(path); const fileHash = createHash18("sha256").update(body).digest("hex"); bytes += body.byteLength; tree.update(file2); @@ -45961,7 +28434,7 @@ function hashFiles(root, files) { function jsonItemCount(path) { if (!existsSync13(path)) return null; - const parsed = JSON.parse(readFileSync11(path, "utf8")); + const parsed = JSON.parse(readFileSync12(path, "utf8")); return Array.isArray(parsed.items) ? parsed.items.length : null; } function sqliteSummary(path) { @@ -46016,7 +28489,7 @@ function isDefaultScaffold(workspace, summary) { if (!summary.files.includes("config.json")) return true; try { - return JSON.stringify(JSON.parse(readFileSync11(workspace.configPath, "utf8"))) === JSON.stringify(defaultKnowledgeConfig()); + return JSON.stringify(JSON.parse(readFileSync12(workspace.configPath, "utf8"))) === JSON.stringify(defaultKnowledgeConfig()); } catch { return false; } @@ -46044,7 +28517,7 @@ function itemShortId(item) { function readMergeStore(path) { if (!existsSync13(path)) return { items: [] }; - const parsed = JSON.parse(readFileSync11(path, "utf8")); + const parsed = JSON.parse(readFileSync12(path, "utf8")); if (!parsed || !Array.isArray(parsed.items)) { throw new Error(`Invalid knowledge JSON store shape at ${path}`); } @@ -46342,7 +28815,7 @@ function chmodOwnerOnlyTree(path) { if (!stat.isDirectory()) return; for (const entry of readdirSync3(path)) - chmodOwnerOnlyTree(join7(path, entry)); + chmodOwnerOnlyTree(join8(path, entry)); } function isRetainedTombstoneFile(file2) { return file2 === "TOMBSTONE.md" || file2 === "migration.json" || file2 === "knowledge.db" || file2 === "knowledge.db-shm" || file2 === "knowledge.db-wal" || file2 === "knowledge.db-journal"; @@ -46352,7 +28825,7 @@ function prepareLegacyTombstoneDirectory(home) { if (file2 === "TOMBSTONE.md" || file2 === "migration.json") continue; try { - rmSync(join7(home, file2), { recursive: true, force: false }); + rmSync(join8(home, file2), { recursive: true, force: false }); } catch (error51) { if (!isRetriableFsLock(error51) || !file2.startsWith("knowledge.db")) throw error51; @@ -46392,7 +28865,7 @@ function isMigrationTombstone(workspace, summary, currentHome) { if (summary.files.some((file2) => !isRetainedTombstoneFile(file2))) return false; try { - const metadata = JSON.parse(readFileSync11(join7(workspace.home, "migration.json"), "utf8")); + const metadata = JSON.parse(readFileSync12(join8(workspace.home, "migration.json"), "utf8")); return metadata.new_path === currentHome && typeof metadata.backup_path === "string"; } catch { return false; @@ -46444,7 +28917,7 @@ function migrateLegacyKnowledgeWorkspace(options) { current_home: options.current.home, legacy_home: options.legacy.home, backup_home: null, - tombstone_path: join7(options.legacy.home, "TOMBSTONE.md"), + tombstone_path: join8(options.legacy.home, "TOMBSTONE.md"), legacy_before: legacyBefore, current_before: currentBefore, backup_after: null, @@ -46472,7 +28945,7 @@ function migrateLegacyKnowledgeWorkspace(options) { current_home: options.current.home, legacy_home: options.legacy.home, backup_home: `${options.legacy.home}.backup-${migrationTimestamp(now)}`, - tombstone_path: join7(options.legacy.home, "TOMBSTONE.md"), + tombstone_path: join8(options.legacy.home, "TOMBSTONE.md"), legacy_before: legacyBefore, current_before: currentBefore, backup_after: null, @@ -46508,7 +28981,7 @@ function migrateLegacyKnowledgeWorkspace(options) { const currentAfter = summarizeWorkspaceTree(options.current); const legacyBeforeOutput = { ...backupAfter, path: options.legacy.home }; mkdirSync4(options.legacy.home, { recursive: true }); - const tombstonePath = join7(options.legacy.home, "TOMBSTONE.md"); + const tombstonePath = join8(options.legacy.home, "TOMBSTONE.md"); writeFileSync5(tombstonePath, [ "# Migrated OpenKnowledge Workspace", "", @@ -46522,7 +28995,7 @@ function migrateLegacyKnowledgeWorkspace(options) { ].join(` `), { mode: 384 }); chmodSync4(tombstonePath, 384); - const migrationJsonPath = join7(options.legacy.home, "migration.json"); + const migrationJsonPath = join8(options.legacy.home, "migration.json"); writeFileSync5(migrationJsonPath, `${JSON.stringify({ migrated_at: now.toISOString(), approved_by: options.approvedBy, @@ -46558,7 +29031,7 @@ function migrateLegacyKnowledgeWorkspace(options) { // src/service.ts function resolvePeerWorkspace(input) { const target = resolve5(input); - if (existsSync14(join8(target, "knowledge.db")) || existsSync14(join8(target, "config.json"))) { + if (existsSync14(join9(target, "knowledge.db")) || existsSync14(join9(target, "config.json"))) { return ensureKnowledgeWorkspace(target); } return ensureKnowledgeWorkspace(workspaceForHome(projectKnowledgeHome(target)).home); @@ -46899,7 +29372,7 @@ function readLegacyInventoryStore(path) { if (!existsSync14(path)) return { exists: false, read_error: null, items: [] }; try { - const parsed = JSON.parse(readFileSync12(path, "utf8")); + const parsed = JSON.parse(readFileSync13(path, "utf8")); if (!parsed || !Array.isArray(parsed.items)) { return { exists: true, read_error: "invalid_store_shape", items: [] }; } @@ -49090,7 +31563,6 @@ var STORAGE_TABLES = [ "knowledge_sync_table_clocks", "knowledge_sync_imports" ]; -var DEPRECATED_CLOUD_ALIASES = ["remote", "hybrid", "self_hosted"]; var KNOWLEDGE_STORAGE_MODE_ENV = "HASNA_KNOWLEDGE_STORAGE_MODE"; var KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV = "KNOWLEDGE_STORAGE_MODE"; function readEnv(name) { @@ -49099,12 +31571,10 @@ function readEnv(name) { } function normalizeStorageMode4(value) { const normalized = value?.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return "local"; - if (normalized === "cloud") - return "cloud"; - if (normalized && DEPRECATED_CLOUD_ALIASES.includes(normalized)) - return "cloud"; + if (normalized === "sqlite") + return "sqlite"; + if (normalized === "postgres" || normalized === "postgresql") + return "postgres"; return; } function openScopedDb(options = {}) { @@ -49120,7 +31590,7 @@ function getStorageMode() { const mode2 = normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_ENV)) ?? normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV)); if (mode2) return mode2; - return "local"; + return "sqlite"; } function getStorageStatus(options = {}) { const local = openScopedDb(options); @@ -50735,7 +33205,7 @@ function buildServer() { }, async ({ file: file2, store_path, scope }) => { if (!existsSync15(file2)) return errorText(`File not found: ${file2}`); - const imported = JSON.parse(readFileSync13(file2, "utf8")); + const imported = JSON.parse(readFileSync14(file2, "utf8")); if (!imported || !Array.isArray(imported.items)) return errorText('Invalid import file: expected {"items": [...]}'); const store = itemStoreFor(store_path, scope); diff --git a/bin/knowledge-serve.js b/bin/knowledge-serve.js index 9107aa4..e684258 100755 --- a/bin/knowledge-serve.js +++ b/bin/knowledge-serve.js @@ -6,9 +6,48 @@ import { readFileSync as readFileSync2 } from "fs"; // node_modules/@hasna/contracts/dist/auth/index.js import { createHash, createHmac, randomBytes, timingSafeEqual } from "crypto"; +var MAX_TENANT_ID_LENGTH = 64; +var TENANT_ID_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_TENANT_ID_LENGTH - 1}}$`); +var UUID_HEX = "[0-9a-fA-F]"; +var UUID_PATTERN = new RegExp(`^\\{?(?:${UUID_HEX}{8}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{12}|${UUID_HEX}{32})\\}?$`); +function isValidTenantId(value) { + return typeof value === "string" && TENANT_ID_PATTERN.test(value); +} +function isUuidTenantId(value) { + return typeof value === "string" && UUID_PATTERN.test(value); +} +function canonicalizeTenantId(value) { + if (!isUuidTenantId(value)) + return value; + const hex = value.replace(/[{}-]/g, "").toLowerCase(); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +function normalizeTenantId(value) { + const trimmed = typeof value === "string" ? value.trim() : ""; + const canonical = canonicalizeTenantId(trimmed); + if (!isValidTenantId(canonical)) { + throw new Error(`Invalid tenant id '${value}'. Expected 1-${MAX_TENANT_ID_LENGTH} characters matching ${TENANT_ID_PATTERN} (a UUID, ULID, slug, or prefixed id).`); + } + return canonical; +} +function tenantIdsEqual(left, right) { + const canonical = (value) => { + if (typeof value !== "string") + return null; + const folded = canonicalizeTenantId(value.trim()); + return isValidTenantId(folded) ? folded : null; + }; + const a = canonical(left); + const b = canonical(right); + return a !== null && b !== null && a === b; +} +function ownTenantId(source) { + return Object.hasOwn(source, "tid") ? source.tid : undefined; +} var API_KEY_TOKEN_VERSION = 1; var API_KEY_NAMESPACE = "hasna"; -var TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/; +var API_KEY_TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/; +var TOKEN_PATTERN = API_KEY_TOKEN_PATTERN; var DEFAULT_API_KEY_TTL_SECONDS = 90 * 24 * 60 * 60; function toBuffer(secret) { return typeof secret === "string" ? Buffer.from(secret, "utf8") : secret; @@ -37,6 +76,10 @@ function parseApiKey(token) { if (typeof claims !== "object" || claims === null || typeof claims.kid !== "string" || typeof claims.app !== "string" || !Array.isArray(claims.scopes)) { return null; } + const claimedTid = ownTenantId(claims); + if (claimedTid !== undefined && !isValidTenantId(claimedTid)) { + return null; + } return { app, body, sig, claims }; } function verifyApiKeyToken(token, options) { @@ -72,6 +115,28 @@ function verifyApiKeyToken(token, options) { if (claims.exp !== null && typeof claims.exp === "number" && now - leeway >= claims.exp) { return { ok: false, reason: "expired", message: "Token has expired." }; } + const verifiedTid = ownTenantId(claims); + const tid = verifiedTid === undefined ? null : canonicalizeTenantId(verifiedTid); + const tenantRequired = Boolean(options.requireTenant) || options.expectedTid !== undefined; + if (tenantRequired && tid === null) { + return { + ok: false, + reason: "tenant_required", + message: "Token carries no tenant id ('tid') and this service requires one.", + kid: claims.kid, + tid: null + }; + } + if (options.expectedTid !== undefined && !tenantIdsEqual(tid, options.expectedTid)) { + const expectationIsWellFormed = typeof options.expectedTid === "string" && isValidTenantId(options.expectedTid.trim()); + return { + ok: false, + reason: "tenant_mismatch", + message: expectationIsWellFormed ? "Token is for a different tenant than the one this service accepts." : "Token tenant cannot be checked: the expected tenant id is not a valid tenant id.", + kid: claims.kid, + tid + }; + } if (options.requiredScopes && options.requiredScopes.length > 0) { const granted = claims.scopes; const satisfies = (required) => granted.some((g) => { @@ -93,7 +158,7 @@ function verifyApiKeyToken(token, options) { } } } - return { ok: true, claims, kid: claims.kid, app }; + return { ok: true, claims, kid: claims.kid, app, tid }; } var DEFAULT_API_KEYS_TABLE = "api_keys"; function createTableSql(table) { @@ -119,6 +184,11 @@ function apiKeyMigrations(table = DEFAULT_API_KEYS_TABLE) { id: `hasna_auth_0002_${table}_indexes`, sql: `CREATE INDEX IF NOT EXISTS ${table}_app_idx ON ${table} (app); CREATE INDEX IF NOT EXISTS ${table}_token_hash_idx ON ${table} (token_hash);` + }, + { + id: `hasna_auth_0003_${table}_tenant`, + sql: `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS tid TEXT; + CREATE INDEX IF NOT EXISTS ${table}_tid_idx ON ${table} (tid);` } ]; } @@ -143,10 +213,12 @@ function parseScopes(value) { return []; } function rowToRecord(row) { + const tid = ownTenantId(row); return { kid: String(row.kid), app: String(row.app), agent: row.agent === null || row.agent === undefined ? null : String(row.agent), + tid: tid === null || tid === undefined ? null : String(tid), scopes: parseScopes(row.scopes), tokenHash: String(row.token_hash), issuedAt: toIso(row.issued_at) ?? new Date(0).toISOString(), @@ -177,12 +249,14 @@ class ApiKeyStore { } } async insert(input) { + const tid = ownTenantId(input); await this.client.execute(`INSERT INTO ${this.table} - (kid, app, agent, scopes, token_hash, issued_at, expires_at, created_by) - VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)`, [ + (kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, created_by) + VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9)`, [ input.kid, input.app, input.agent ?? null, + tid === undefined || tid === null ? null : normalizeTenantId(tid), JSON.stringify(input.scopes), input.tokenHash, input.issuedAt.toISOString(), @@ -196,6 +270,7 @@ class ApiKeyStore { kid: minted.kid, app: claims.app, agent: claims.agent ?? null, + tid: ownTenantId(claims) ?? null, scopes: claims.scopes, tokenHash: minted.tokenHash, issuedAt: new Date(claims.iat * 1000), @@ -253,11 +328,16 @@ class ApiKeyStore { params.push(options.app); clauses.push(`app = $${params.length}`); } + const tid = ownTenantId(options); + if (tid !== undefined) { + params.push(normalizeTenantId(tid)); + clauses.push(`tid = $${params.length}`); + } if (!options.includeRevoked) { clauses.push("revoked_at IS NULL"); } const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""; - const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`); + const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`, params); return rows.map(rowToRecord); } async revokedKids() { @@ -300,6 +380,9 @@ function verifyApiKey(options) { if (!options.signingSecret) { throw new Error("verifyApiKey requires a 'signingSecret'. Set it from HASNA__API_SIGNING_KEY."); } + if (options.expectedTid !== undefined && !isValidTenantId(options.expectedTid)) { + throw new Error(`verifyApiKey received an invalid 'expectedTid': '${options.expectedTid}'.`); + } const headerName = options.headerName ?? "x-api-key"; const scheme = options.scheme ?? "Bearer"; const clock = options.nowMs ?? (() => Date.now()); @@ -315,6 +398,17 @@ function verifyApiKey(options) { const path = context.path ?? null; const requiredScopes = [...options.requiredScopes ?? [], ...context.requiredScopes ?? []]; const at = new Date(clock()).toISOString(); + const perCallTid = Object.hasOwn(context, "expectedTid") ? context.expectedTid : undefined; + const expectedTid = perCallTid !== undefined ? perCallTid : options.expectedTid; + if (perCallTid !== undefined && options.expectedTid !== undefined && !tenantIdsEqual(perCallTid, options.expectedTid)) { + await emit({ outcome: "deny", app: options.app, kid: null, tid: null, reason: "tenant_mismatch", scopesRequired: requiredScopes, method, path, status: 403, at }); + return { + ok: false, + status: 403, + reason: "tenant_mismatch", + message: "This route addresses a tenant other than the one this service is pinned to." + }; + } const token = extractToken(headers, headerName, scheme); if (!token) { const decision = { @@ -323,7 +417,7 @@ function verifyApiKey(options) { reason: "missing_token", message: `Missing API key. Send it as '${headerName}: ' or 'Authorization: ${scheme} '.` }; - await emit({ outcome: "deny", app: options.app, kid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at }); + await emit({ outcome: "deny", app: options.app, kid: null, tid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at }); return decision; } const verified = verifyApiKeyToken(token, { @@ -331,17 +425,19 @@ function verifyApiKey(options) { expectedApp: options.app, nowMs: clock(), ...options.leewaySeconds !== undefined ? { leewaySeconds: options.leewaySeconds } : {}, + ...options.requireTenant !== undefined ? { requireTenant: options.requireTenant } : {}, + ...expectedTid !== undefined ? { expectedTid } : {}, requiredScopes }); if (!verified.ok) { - const status = verified.reason === "insufficient_scope" ? 403 : 401; - await emit({ outcome: "deny", app: options.app, kid: null, reason: verified.reason, scopesRequired: requiredScopes, method, path, status, at }); + const status = verified.reason === "insufficient_scope" || verified.reason === "tenant_mismatch" || verified.reason === "tenant_required" ? 403 : 401; + await emit({ outcome: "deny", app: options.app, kid: verified.kid ?? null, tid: ownTenantId(verified) ?? null, reason: verified.reason, scopesRequired: requiredScopes, method, path, status, at }); return { ok: false, status, reason: verified.reason, message: verified.message }; } if (options.isRevoked) { const revoked = await options.isRevoked(verified.kid); if (revoked) { - await emit({ outcome: "deny", app: options.app, kid: verified.kid, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at }); + await emit({ outcome: "deny", app: options.app, kid: verified.kid, tid: verified.tid, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at }); return { ok: false, status: 401, reason: "revoked", message: "API key has been revoked." }; } } @@ -350,30 +446,24 @@ function verifyApiKey(options) { app: verified.app, scopes: verified.claims.scopes, agent: verified.claims.agent ?? null, + tid: verified.tid, claims: verified.claims }; - await emit({ outcome: "allow", app: options.app, kid: verified.kid, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at }); + await emit({ outcome: "allow", app: options.app, kid: verified.kid, tid: verified.tid, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at }); return { ok: true, status: 200, principal }; } return { authenticate, app: options.app }; } +var MAX_FLEET_TOKEN_TTL_SECONDS = 24 * 60 * 60; // src/generated/storage-kit/mode.ts -var DEPRECATED_STORAGE_MODE_ALIASES = [ - "remote", - "hybrid", - "self_hosted" -]; function normalizeStorageMode(value) { const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); } function envToken(name) { return name.toUpperCase().replace(/-/g, "_"); @@ -401,21 +491,17 @@ function resolveStorageMode(name, env = process.env) { const modeHit = firstEnv(env, modeKeys); if (!modeHit) { return { - mode: "local", - source: "default", - deprecatedAlias: null, + mode: databaseUrlPresent ? "postgres" : "sqlite", + source: databaseUrlPresent ? databaseUrlSource : "default", databaseUrlPresent, databaseUrlSource, warning: null }; } - const { mode, deprecatedAlias } = normalizeStorageMode(modeHit.value); + const { mode } = normalizeStorageMode(modeHit.value); const warnings = []; - if (deprecatedAlias) { - warnings.push(`Deprecated storage mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Set ${modeKeys[0]}=cloud instead.`); - } - if (mode === "cloud" && !databaseUrlPresent) { - warnings.push(`cloud mode needs ${databaseUrlKeys[0]} (PURE REMOTE: reads and writes go to cloud Postgres).`); + if (mode === "postgres" && !databaseUrlPresent) { + warnings.push(`postgres storage needs ${databaseUrlKeys[0]} (reads and writes go to PostgreSQL).`); } if (modeHit.key !== modeKeys[0]) { warnings.push(`Using alias env ${modeHit.key}; the canonical key is ${modeKeys[0]}.`); @@ -423,7 +509,6 @@ function resolveStorageMode(name, env = process.env) { return { mode, source: modeHit.key, - deprecatedAlias, databaseUrlPresent, databaseUrlSource, warning: warnings.length > 0 ? warnings.join(" ") : null @@ -470,11 +555,11 @@ function loadCaBundle(options) { } function resolveTlsConfig(connectionString, options = {}) { const mode = sslModeFromConnectionString(connectionString); - if (mode === "disable") { + if (mode === "disable" || mode === "prefer") { return; } const ca = loadCaBundle(options); - if (mode === "prefer" || mode === "require") { + if (mode === "require") { return ca ? { rejectUnauthorized: false, ca } : { rejectUnauthorized: false }; } if (!ca) { @@ -556,15 +641,15 @@ function createPgPool(options) { config.application_name = options.applicationName; return new pg.Pool(config); } -function createCloudPoolFromEnv(appName, options = {}) { +function createServerPoolFromEnv(appName, options = {}) { const env = options.env ?? process.env; const resolution = resolveStorageMode(appName, env); - if (resolution.mode !== "cloud") { - throw new Error(`createCloudPoolFromEnv requires ${appName} storage mode 'cloud', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=cloud.`); + if (resolution.mode !== "postgres") { + throw new Error(`createServerPoolFromEnv requires ${appName} storage mode 'postgres', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=postgres.`); } const connectionString = resolveDatabaseUrl(appName, env); if (!connectionString) { - throw new Error(`cloud mode for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); + throw new Error(`postgres storage for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); } const pool = createPgPool({ connectionString, @@ -584,7 +669,7 @@ function createCloudPoolFromEnv(appName, options = {}) { // src/db/remote-storage.ts var KNOWLEDGE_APP_NAME = "knowledge"; function createKnowledgeCloudClient() { - return createCloudPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; + return createServerPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; } // src/registry-contract.ts @@ -1154,7 +1239,7 @@ function parseExpectedVersion(req, body) { } function createServeHandler(deps) { const repo = new NoteRepo(deps.client); - const mode2 = "cloud"; + const mode2 = "postgres"; const authOrThrow = async (req, requiredScopes) => { const url = new URL(req.url); const decision = await deps.verifier.authenticate(req.headers, { @@ -1305,7 +1390,7 @@ async function startKnowledgeServe(options = {}) { throw new Error("knowledge-serve requires the Bun runtime (Bun.serve unavailable)."); } const server = BunGlobal.serve({ port, hostname, fetch: handler }); - console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=cloud, version=${version})`); + console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=postgres, version=${version})`); return { port: server.port, hostname, diff --git a/bin/knowledge.js b/bin/knowledge.js index 47f4092..1d60a0b 100755 --- a/bin/knowledge.js +++ b/bin/knowledge.js @@ -1,104 +1,105 @@ #!/usr/bin/env bun // @bun -var AA=Object.create;var{getPrototypeOf:bA,defineProperty:BY,getOwnPropertyNames:wA}=Object;var gA=Object.prototype.hasOwnProperty;function kA($){return this[$]}var IA,fA,CA=($,_,J)=>{var U=$!=null&&typeof $==="object";if(U){var W=_?IA??=new WeakMap:fA??=new WeakMap,X=W.get($);if(X)return X}J=$!=null?AA(bA($)):{};let G=_||!$||!$.__esModule?BY(J,"default",{value:$,enumerable:!0}):J;for(let Y of wA($))if(!gA.call(G,Y))BY(G,Y,{get:kA.bind($,Y),enumerable:!0});if(U)W.set($,G);return G};var t0=($,_)=>()=>(_||$((_={exports:{}}).exports,_),_.exports);var PA=($)=>$;function TA($,_){this[$]=PA.bind(null,_)}var e6=($,_)=>{for(var J in _)BY($,J,{get:_[J],enumerable:!0,configurable:!0,set:TA.bind(_,J)})};var x=($,_)=>()=>($&&(_=$($=0)),_);var i$=import.meta.require;function M($,_,J){function U(Y,Q){if(!Y._zod)Object.defineProperty(Y,"_zod",{value:{def:Q,constr:G,traits:new Set},enumerable:!1});if(Y._zod.traits.has($))return;Y._zod.traits.add($),_(Y,Q);let q=G.prototype,L=Object.keys(q);for(let N=0;N{if(J?.Parent&&Y instanceof J.Parent)return!0;return Y?._zod?.traits?.has($)}}),Object.defineProperty(G,"name",{value:$}),G}function V_($){if($)Object.assign(T1,$);return T1}var QR,O8,L8,O4,S1,T1;var Z1=x(()=>{O8=Object.freeze({status:"aborted"});L8=Symbol("zod_brand");O4=class O4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};S1=class S1 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(QR=globalThis).__zod_globalConfig??(QR.__zod_globalConfig={});T1=globalThis.__zod_globalConfig});var C={};e6(C,{unwrapMessage:()=>PU,uint8ArrayToHex:()=>Em,uint8ArrayToBase64url:()=>Km,uint8ArrayToBase64:()=>jR,stringifyPrimitive:()=>I,slugify:()=>Qq,shallowClone:()=>zq,safeExtend:()=>Lm,required:()=>Nm,randomString:()=>Ym,propertyKeyTypes:()=>ZU,promiseAllObject:()=>Gm,primitiveTypes:()=>jq,prefixIssues:()=>p_,pick:()=>jm,partial:()=>Hm,parsedType:()=>f,optionalKeys:()=>Dq,omit:()=>Dm,objectClone:()=>Wm,numKeys:()=>Qm,nullish:()=>k0,normalizeParams:()=>y,mergeDefs:()=>i4,merge:()=>Bm,jsonStringifyReplacer:()=>nJ,joinValues:()=>b,issue:()=>iJ,isPlainObject:()=>f0,isObject:()=>v1,hexToUint8Array:()=>Fm,getSizableOrigin:()=>vU,getParsedType:()=>qm,getLengthableOrigin:()=>yU,getEnumValues:()=>TU,getElementAtPath:()=>Xm,floatSafeRemainder:()=>Yq,finalizeIssue:()=>n_,extend:()=>Om,explicitlyAborted:()=>Bq,escapeRegex:()=>V6,esc:()=>B8,defineLazy:()=>Z$,createTransparentProxy:()=>zm,cloneDef:()=>Um,clone:()=>T_,cleanRegex:()=>SU,cleanEnum:()=>Vm,captureStackTrace:()=>H8,cached:()=>cJ,base64urlToUint8Array:()=>Rm,base64ToUint8Array:()=>zR,assignProp:()=>I0,assertNotEqual:()=>eh,assertNever:()=>_m,assertIs:()=>$m,assertEqual:()=>sh,assert:()=>Jm,allowsEval:()=>qq,aborted:()=>C0,NUMBER_FORMAT_RANGES:()=>Oq,Class:()=>DR,BIGINT_FORMAT_RANGES:()=>Lq});function sh($){return $}function eh($){return $}function $m($){}function _m($){throw Error("Unexpected value in exhaustive check")}function Jm($){}function TU($){let _=Object.values($).filter((U)=>typeof U==="number");return Object.entries($).filter(([U,W])=>_.indexOf(+U)===-1).map(([U,W])=>W)}function b($,_="|"){return $.map((J)=>I(J)).join(_)}function nJ($,_){if(typeof _==="bigint")return _.toString();return _}function cJ($){return{get value(){{let J=$();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function k0($){return $===null||$===void 0}function SU($){let _=$.startsWith("^")?1:0,J=$.endsWith("$")?$.length-1:$.length;return $.slice(_,J)}function Yq($,_){let J=$/_,U=Math.round(J),W=Number.EPSILON*Math.max(Math.abs(J),1);if(Math.abs(J-U)J?.[U],$)}function Gm($){let _=Object.keys($),J=_.map((U)=>$[U]);return Promise.all(J).then((U)=>{let W={};for(let X=0;X<_.length;X++)W[_[X]]=U[X];return W})}function Ym($=10){let J="";for(let U=0;U<$;U++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function B8($){return JSON.stringify($)}function Qq($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function v1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function f0($){if(v1($)===!1)return!1;let _=$.constructor;if(_===void 0)return!0;if(typeof _!=="function")return!0;let J=_.prototype;if(v1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function zq($){if(f0($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function Qm($){let _=0;for(let J in $)if(Object.prototype.hasOwnProperty.call($,J))_++;return _}function V6($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T_($,_,J){let U=new $._zod.constr(_??$._zod.def);if(!_||J?.parent)U._zod.parent=$;return U}function y($){let _=$;if(!_)return{};if(typeof _==="string")return{error:()=>_};if(_?.message!==void 0){if(_?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");_.error=_.message}if(delete _.message,typeof _.error==="string")return{..._,error:()=>_.error};return _}function zm($){let _;return new Proxy({},{get(J,U,W){return _??(_=$()),Reflect.get(_,U,W)},set(J,U,W,X){return _??(_=$()),Reflect.set(_,U,W,X)},has(J,U){return _??(_=$()),Reflect.has(_,U)},deleteProperty(J,U){return _??(_=$()),Reflect.deleteProperty(_,U)},ownKeys(J){return _??(_=$()),Reflect.ownKeys(_)},getOwnPropertyDescriptor(J,U){return _??(_=$()),Reflect.getOwnPropertyDescriptor(_,U)},defineProperty(J,U,W){return _??(_=$()),Reflect.defineProperty(_,U,W)}})}function I($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function Dq($){return Object.keys($).filter((_)=>{return $[_]._zod.optin==="optional"&&$[_]._zod.optout==="optional"})}function jm($,_){let J=$._zod.def,U=J.checks;if(U&&U.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let X=i4($._zod.def,{get shape(){let G={};for(let Y in _){if(!(Y in J.shape))throw Error(`Unrecognized key: "${Y}"`);if(!_[Y])continue;G[Y]=J.shape[Y]}return I0(this,"shape",G),G},checks:[]});return T_($,X)}function Dm($,_){let J=$._zod.def,U=J.checks;if(U&&U.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let X=i4($._zod.def,{get shape(){let G={...$._zod.def.shape};for(let Y in _){if(!(Y in J.shape))throw Error(`Unrecognized key: "${Y}"`);if(!_[Y])continue;delete G[Y]}return I0(this,"shape",G),G},checks:[]});return T_($,X)}function Om($,_){if(!f0(_))throw Error("Invalid input to extend: expected a plain object");let J=$._zod.def.checks;if(J&&J.length>0){let X=$._zod.def.shape;for(let G in _)if(Object.getOwnPropertyDescriptor(X,G)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let W=i4($._zod.def,{get shape(){let X={...$._zod.def.shape,..._};return I0(this,"shape",X),X}});return T_($,W)}function Lm($,_){if(!f0(_))throw Error("Invalid input to safeExtend: expected a plain object");let J=i4($._zod.def,{get shape(){let U={...$._zod.def.shape,..._};return I0(this,"shape",U),U}});return T_($,J)}function Bm($,_){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let J=i4($._zod.def,{get shape(){let U={...$._zod.def.shape,..._._zod.def.shape};return I0(this,"shape",U),U},get catchall(){return _._zod.def.catchall},checks:_._zod.def.checks??[]});return T_($,J)}function Hm($,_,J){let W=_._zod.def.checks;if(W&&W.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let G=i4(_._zod.def,{get shape(){let Y=_._zod.def.shape,Q={...Y};if(J)for(let q in J){if(!(q in Y))throw Error(`Unrecognized key: "${q}"`);if(!J[q])continue;Q[q]=$?new $({type:"optional",innerType:Y[q]}):Y[q]}else for(let q in Y)Q[q]=$?new $({type:"optional",innerType:Y[q]}):Y[q];return I0(this,"shape",Q),Q},checks:[]});return T_(_,G)}function Nm($,_,J){let U=i4(_._zod.def,{get shape(){let W=_._zod.def.shape,X={...W};if(J)for(let G in J){if(!(G in X))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;X[G]=new $({type:"nonoptional",innerType:W[G]})}else for(let G in W)X[G]=new $({type:"nonoptional",innerType:W[G]});return I0(this,"shape",X),X}});return T_(_,U)}function C0($,_=0){if($.aborted===!0)return!0;for(let J=_;J<$.issues.length;J++)if($.issues[J]?.continue!==!0)return!0;return!1}function Bq($,_=0){if($.aborted===!0)return!0;for(let J=_;J<$.issues.length;J++)if($.issues[J]?.continue===!1)return!0;return!1}function p_($,_){return _.map((J)=>{var U;return(U=J).path??(U.path=[]),J.path.unshift($),J})}function PU($){return typeof $==="string"?$:$?.message}function n_($,_,J){let U=$.message?$.message:PU($.inst?._zod.def?.error?.($))??PU(_?.error?.($))??PU(J.customError?.($))??PU(J.localeError?.($))??"Invalid input",{inst:W,continue:X,input:G,...Y}=$;if(Y.path??(Y.path=[]),Y.message=U,_?.reportInput)Y.input=G;return Y}function vU($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function yU($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function f($){let _=typeof $;switch(_){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let J=$;if(J&&Object.getPrototypeOf(J)!==Object.prototype&&"constructor"in J&&J.constructor)return J.constructor.name}}return _}function iJ(...$){let[_,J,U]=$;if(typeof _==="string")return{message:_,code:"custom",input:J,inst:U};return{..._}}function Vm($){return Object.entries($).filter(([_,J])=>{return Number.isNaN(Number.parseInt(_,10))}).map((_)=>_[1])}function zR($){let _=atob($),J=new Uint8Array(_.length);for(let U=0;U<_.length;U++)J[U]=_.charCodeAt(U);return J}function jR($){let _="";for(let J=0;J<$.length;J++)_+=String.fromCharCode($[J]);return btoa(_)}function Rm($){let _=$.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-_.length%4)%4);return zR(_+J)}function Km($){return jR($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Fm($){let _=$.replace(/^0x/,"");if(_.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(_.length/2);for(let U=0;U<_.length;U+=2)J[U/2]=Number.parseInt(_.slice(U,U+2),16);return J}function Em($){return Array.from($).map((_)=>_.toString(16).padStart(2,"0")).join("")}class DR{constructor(...$){}}var qR,H8,qq,qm=($)=>{let _=typeof $;switch(_){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${_}`)}},ZU,jq,Oq,Lq;var e=x(()=>{Z1();qR=Symbol("evaluating");H8="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};qq=cJ(()=>{if(T1.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});ZU=new Set(["string","number","symbol"]),jq=new Set(["string","number","bigint","boolean","symbol","undefined"]);Oq={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Lq={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function lJ($,_=(J)=>J.message){let J={},U=[];for(let W of $.issues)if(W.path.length>0)J[W.path[0]]=J[W.path[0]]||[],J[W.path[0]].push(_(W));else U.push(_(W));return{formErrors:U,fieldErrors:J}}function rJ($,_=(J)=>J.message){let J={_errors:[]},U=(W,X=[])=>{for(let G of W.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((Y)=>U({issues:Y},[...X,...G.path]));else if(G.code==="invalid_key")U({issues:G.issues},[...X,...G.path]);else if(G.code==="invalid_element")U({issues:G.issues},[...X,...G.path]);else{let Y=[...X,...G.path];if(Y.length===0)J._errors.push(_(G));else{let Q=J,q=0;while(qJ.message){let J={errors:[]},U=(W,X=[])=>{var G,Y;for(let Q of W.issues)if(Q.code==="invalid_union"&&Q.errors.length)Q.errors.map((q)=>U({issues:q},[...X,...Q.path]));else if(Q.code==="invalid_key")U({issues:Q.issues},[...X,...Q.path]);else if(Q.code==="invalid_element")U({issues:Q.issues},[...X,...Q.path]);else{let q=[...X,...Q.path];if(q.length===0){J.errors.push(_(Q));continue}let L=J,N=0;while(Ntypeof U==="object"?U.key:U);for(let U of J)if(typeof U==="number")_.push(`[${U}]`);else if(typeof U==="symbol")_.push(`[${JSON.stringify(String(U))}]`);else if(/[^\w$]/.test(U))_.push(`[${JSON.stringify(U)}]`);else{if(_.length)_.push(".");_.push(U)}return _.join("")}function V8($){let _=[],J=[...$.issues].sort((U,W)=>(U.path??[]).length-(W.path??[]).length);for(let U of J)if(_.push(`\u2716 ${U.message}`),U.path?.length)_.push(` \u2192 at ${LR(U.path)}`);return _.join(` -`)}var OR=($,_)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:_,enumerable:!1}),$.message=JSON.stringify(_,nJ,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},hU,o_;var Hq=x(()=>{Z1();e();hU=M("$ZodError",OR),o_=M("$ZodError",OR,{Parent:Error})});var pJ=($)=>(_,J,U,W)=>{let X=U?{...U,async:!1}:{async:!1},G=_._zod.run({value:J,issues:[]},X);if(G instanceof Promise)throw new O4;if(G.issues.length){let Y=new(W?.Err??$)(G.issues.map((Q)=>n_(Q,X,V_())));throw H8(Y,W?.callee),Y}return G.value},R8,oJ=($)=>async(_,J,U,W)=>{let X=U?{...U,async:!0}:{async:!0},G=_._zod.run({value:J,issues:[]},X);if(G instanceof Promise)G=await G;if(G.issues.length){let Y=new(W?.Err??$)(G.issues.map((Q)=>n_(Q,X,V_())));throw H8(Y,W?.callee),Y}return G.value},K8,tJ=($)=>(_,J,U)=>{let W=U?{...U,async:!1}:{async:!1},X=_._zod.run({value:J,issues:[]},W);if(X instanceof Promise)throw new O4;return X.issues.length?{success:!1,error:new($??hU)(X.issues.map((G)=>n_(G,W,V_())))}:{success:!0,data:X.value}},Nq,aJ=($)=>async(_,J,U)=>{let W=U?{...U,async:!0}:{async:!0},X=_._zod.run({value:J,issues:[]},W);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new $(X.issues.map((G)=>n_(G,W,V_())))}:{success:!0,data:X.value}},Vq,F8=($)=>(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return pJ($)(_,J,W)},Am,E8=($)=>(_,J,U)=>{return pJ($)(_,J,U)},bm,M8=($)=>async(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return oJ($)(_,J,W)},wm,A8=($)=>async(_,J,U)=>{return oJ($)(_,J,U)},gm,b8=($)=>(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return tJ($)(_,J,W)},km,w8=($)=>(_,J,U)=>{return tJ($)(_,J,U)},Im,g8=($)=>async(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return aJ($)(_,J,W)},fm,k8=($)=>async(_,J,U)=>{return aJ($)(_,J,U)},Cm;var Rq=x(()=>{Z1();Hq();e();R8=pJ(o_),K8=oJ(o_),Nq=tJ(o_),Vq=aJ(o_),Am=F8(o_),bm=E8(o_),wm=M8(o_),gm=A8(o_),km=b8(o_),Im=w8(o_),fm=g8(o_),Cm=k8(o_)});var t_={};e6(t_,{xid:()=>Mq,uuid7:()=>Zm,uuid6:()=>Sm,uuid4:()=>Tm,uuid:()=>y1,uppercase:()=>pq,unicodeEmail:()=>BR,undefined:()=>lq,ulid:()=>Eq,time:()=>mq,string:()=>uq,sha512_hex:()=>Jx,sha512_base64url:()=>Ux,sha512_base64:()=>Wx,sha384_hex:()=>em,sha384_base64url:()=>_x,sha384_base64:()=>$x,sha256_hex:()=>tm,sha256_base64url:()=>sm,sha256_base64:()=>am,sha1_hex:()=>rm,sha1_base64url:()=>om,sha1_base64:()=>pm,rfc5322Email:()=>ym,number:()=>mU,null:()=>iq,nanoid:()=>bq,md5_hex:()=>cm,md5_base64url:()=>lm,md5_base64:()=>im,mac:()=>Pq,lowercase:()=>rq,ksuid:()=>Aq,ipv6:()=>Cq,ipv4:()=>fq,integer:()=>nq,idnEmail:()=>hm,httpProtocol:()=>vq,html5Email:()=>vm,hostname:()=>um,hex:()=>nm,guid:()=>gq,extendedDuration:()=>Pm,emoji:()=>Iq,email:()=>kq,e164:()=>yq,duration:()=>wq,domain:()=>dm,datetime:()=>xq,date:()=>hq,cuid2:()=>Fq,cuid:()=>Kq,cidrv6:()=>Sq,cidrv4:()=>Tq,browserEmail:()=>mm,boolean:()=>cq,bigint:()=>dq,base64url:()=>I8,base64:()=>Zq});function Iq(){return new RegExp(xm,"u")}function NR($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function mq($){return new RegExp(`^${NR($)}$`)}function xq($){let _=NR({precision:$.precision}),J=["Z"];if($.local)J.push("");if($.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${_}(?:${J.join("|")})`;return new RegExp(`^${HR}T(?:${U})$`)}function xU($,_){return new RegExp(`^[A-Za-z0-9+/]{${$}}${_}$`)}function uU($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var Kq,Fq,Eq,Mq,Aq,bq,wq,Pm,gq,y1=($)=>{if(!$)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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Tm,Sm,Zm,kq,vm,ym,BR,hm,mm,xm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",fq,Cq,Pq=($)=>{let _=V6($??":");return new RegExp(`^(?:[0-9A-F]{2}${_}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${_}){5}[0-9a-f]{2}$`)},Tq,Sq,Zq,I8,um,dm,vq,yq,HR="(?:(?:\\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])))",hq,uq=($)=>{let _=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${_}$`)},dq,nq,mU,cq,iq,lq,rq,pq,nm,cm,im,lm,rm,pm,om,tm,am,sm,em,$x,_x,Jx,Wx,Ux;var f8=x(()=>{e();Kq=/^[cC][0-9a-z]{6,}$/,Fq=/^[0-9a-z]+$/,Eq=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Mq=/^[0-9a-vA-V]{20}$/,Aq=/^[A-Za-z0-9]{27}$/,bq=/^[a-zA-Z0-9_-]{21}$/,wq=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Pm=/^[-+]?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)?)??$/,gq=/^([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})$/,Tm=y1(4),Sm=y1(6),Zm=y1(7),kq=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vm=/^[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])?)*$/,ym=/^(([^<>()\[\]\\.,;:\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,}))$/,BR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,hm=BR,mm=/^[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])?)*$/;fq=/^(?:(?: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])$/,Cq=/^(([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}|:))$/,Tq=/^((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])$/,Sq=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zq=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,I8=/^[A-Za-z0-9_-]*$/,um=/^(?=.{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])?)*\.?$/,dm=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,vq=/^https?$/,yq=/^\+[1-9]\d{6,14}$/,hq=new RegExp(`^${HR}$`);dq=/^-?\d+n?$/,nq=/^-?\d+$/,mU=/^-?\d+(?:\.\d+)?$/,cq=/^(?:true|false)$/i,iq=/^null$/i,lq=/^undefined$/i,rq=/^[^A-Z]*$/,pq=/^[^a-z]*$/,nm=/^[0-9a-fA-F]*$/;cm=/^[0-9a-fA-F]{32}$/,im=xU(22,"=="),lm=uU(22),rm=/^[0-9a-fA-F]{40}$/,pm=xU(27,"="),om=uU(27),tm=/^[0-9a-fA-F]{64}$/,am=xU(43,"="),sm=uU(43),em=/^[0-9a-fA-F]{96}$/,$x=xU(64,""),_x=uU(64),Jx=/^[0-9a-fA-F]{128}$/,Wx=xU(86,"=="),Ux=uU(86)});function VR($,_,J){if($.issues.length)_.issues.push(...p_(J,$.issues))}var X_,RR,C8,P8,oq,tq,aq,sq,eq,$7,_7,J7,W7,sJ,U7,X7,G7,Y7,Q7,q7,z7,j7,D7;var T8=x(()=>{Z1();f8();e();X_=M("$ZodCheck",($,_)=>{var J;$._zod??($._zod={}),$._zod.def=_,(J=$._zod).onattach??(J.onattach=[])}),RR={number:"number",bigint:"bigint",object:"date"},C8=M("$ZodCheckLessThan",($,_)=>{X_.init($,_);let J=RR[typeof _.value];$._zod.onattach.push((U)=>{let W=U._zod.bag,X=(_.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(_.value{if(_.inclusive?U.value<=_.value:U.value<_.value)return;U.issues.push({origin:J,code:"too_big",maximum:typeof _.value==="object"?_.value.getTime():_.value,input:U.value,inclusive:_.inclusive,inst:$,continue:!_.abort})}}),P8=M("$ZodCheckGreaterThan",($,_)=>{X_.init($,_);let J=RR[typeof _.value];$._zod.onattach.push((U)=>{let W=U._zod.bag,X=(_.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(_.value>X)if(_.inclusive)W.minimum=_.value;else W.exclusiveMinimum=_.value}),$._zod.check=(U)=>{if(_.inclusive?U.value>=_.value:U.value>_.value)return;U.issues.push({origin:J,code:"too_small",minimum:typeof _.value==="object"?_.value.getTime():_.value,input:U.value,inclusive:_.inclusive,inst:$,continue:!_.abort})}}),oq=M("$ZodCheckMultipleOf",($,_)=>{X_.init($,_),$._zod.onattach.push((J)=>{var U;(U=J._zod.bag).multipleOf??(U.multipleOf=_.value)}),$._zod.check=(J)=>{if(typeof J.value!==typeof _.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%_.value===BigInt(0):Yq(J.value,_.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:_.value,input:J.value,inst:$,continue:!_.abort})}}),tq=M("$ZodCheckNumberFormat",($,_)=>{X_.init($,_),_.format=_.format||"float64";let J=_.format?.includes("int"),U=J?"int":"number",[W,X]=Oq[_.format];$._zod.onattach.push((G)=>{let Y=G._zod.bag;if(Y.format=_.format,Y.minimum=W,Y.maximum=X,J)Y.pattern=nq}),$._zod.check=(G)=>{let Y=G.value;if(J){if(!Number.isInteger(Y)){G.issues.push({expected:U,format:_.format,code:"invalid_type",continue:!1,input:Y,inst:$});return}if(!Number.isSafeInteger(Y)){if(Y>0)G.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:U,inclusive:!0,continue:!_.abort});else G.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:U,inclusive:!0,continue:!_.abort});return}}if(YX)G.issues.push({origin:"number",input:Y,code:"too_big",maximum:X,inclusive:!0,inst:$,continue:!_.abort})}}),aq=M("$ZodCheckBigIntFormat",($,_)=>{X_.init($,_);let[J,U]=Lq[_.format];$._zod.onattach.push((W)=>{let X=W._zod.bag;X.format=_.format,X.minimum=J,X.maximum=U}),$._zod.check=(W)=>{let X=W.value;if(XU)W.issues.push({origin:"bigint",input:X,code:"too_big",maximum:U,inclusive:!0,inst:$,continue:!_.abort})}}),sq=M("$ZodCheckMaxSize",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if(_.maximum{let W=U.value;if(W.size<=_.maximum)return;U.issues.push({origin:vU(W),code:"too_big",maximum:_.maximum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),eq=M("$ZodCheckMinSize",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(_.minimum>W)U._zod.bag.minimum=_.minimum}),$._zod.check=(U)=>{let W=U.value;if(W.size>=_.minimum)return;U.issues.push({origin:vU(W),code:"too_small",minimum:_.minimum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),$7=M("$ZodCheckSizeEquals",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.minimum=_.size,W.maximum=_.size,W.size=_.size}),$._zod.check=(U)=>{let W=U.value,X=W.size;if(X===_.size)return;let G=X>_.size;U.issues.push({origin:vU(W),...G?{code:"too_big",maximum:_.size}:{code:"too_small",minimum:_.size},inclusive:!0,exact:!0,input:U.value,inst:$,continue:!_.abort})}}),_7=M("$ZodCheckMaxLength",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if(_.maximum{let W=U.value;if(W.length<=_.maximum)return;let G=yU(W);U.issues.push({origin:G,code:"too_big",maximum:_.maximum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),J7=M("$ZodCheckMinLength",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(_.minimum>W)U._zod.bag.minimum=_.minimum}),$._zod.check=(U)=>{let W=U.value;if(W.length>=_.minimum)return;let G=yU(W);U.issues.push({origin:G,code:"too_small",minimum:_.minimum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),W7=M("$ZodCheckLengthEquals",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.minimum=_.length,W.maximum=_.length,W.length=_.length}),$._zod.check=(U)=>{let W=U.value,X=W.length;if(X===_.length)return;let G=yU(W),Y=X>_.length;U.issues.push({origin:G,...Y?{code:"too_big",maximum:_.length}:{code:"too_small",minimum:_.length},inclusive:!0,exact:!0,input:U.value,inst:$,continue:!_.abort})}}),sJ=M("$ZodCheckStringFormat",($,_)=>{var J,U;if(X_.init($,_),$._zod.onattach.push((W)=>{let X=W._zod.bag;if(X.format=_.format,_.pattern)X.patterns??(X.patterns=new Set),X.patterns.add(_.pattern)}),_.pattern)(J=$._zod).check??(J.check=(W)=>{if(_.pattern.lastIndex=0,_.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:_.format,input:W.value,..._.pattern?{pattern:_.pattern.toString()}:{},inst:$,continue:!_.abort})});else(U=$._zod).check??(U.check=()=>{})}),U7=M("$ZodCheckRegex",($,_)=>{sJ.init($,_),$._zod.check=(J)=>{if(_.pattern.lastIndex=0,_.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:_.pattern.toString(),inst:$,continue:!_.abort})}}),X7=M("$ZodCheckLowerCase",($,_)=>{_.pattern??(_.pattern=rq),sJ.init($,_)}),G7=M("$ZodCheckUpperCase",($,_)=>{_.pattern??(_.pattern=pq),sJ.init($,_)}),Y7=M("$ZodCheckIncludes",($,_)=>{X_.init($,_);let J=V6(_.includes),U=new RegExp(typeof _.position==="number"?`^.{${_.position}}${J}`:J);_.pattern=U,$._zod.onattach.push((W)=>{let X=W._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(U)}),$._zod.check=(W)=>{if(W.value.includes(_.includes,_.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:_.includes,input:W.value,inst:$,continue:!_.abort})}}),Q7=M("$ZodCheckStartsWith",($,_)=>{X_.init($,_);let J=new RegExp(`^${V6(_.prefix)}.*`);_.pattern??(_.pattern=J),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(U)=>{if(U.value.startsWith(_.prefix))return;U.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:_.prefix,input:U.value,inst:$,continue:!_.abort})}}),q7=M("$ZodCheckEndsWith",($,_)=>{X_.init($,_);let J=new RegExp(`.*${V6(_.suffix)}$`);_.pattern??(_.pattern=J),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(U)=>{if(U.value.endsWith(_.suffix))return;U.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:_.suffix,input:U.value,inst:$,continue:!_.abort})}});z7=M("$ZodCheckProperty",($,_)=>{X_.init($,_),$._zod.check=(J)=>{let U=_.schema._zod.run({value:J.value[_.property],issues:[]},{});if(U instanceof Promise)return U.then((W)=>VR(W,J,_.property));VR(U,J,_.property);return}}),j7=M("$ZodCheckMimeType",($,_)=>{X_.init($,_);let J=new Set(_.mime);$._zod.onattach.push((U)=>{U._zod.bag.mime=_.mime}),$._zod.check=(U)=>{if(J.has(U.value.type))return;U.issues.push({code:"invalid_value",values:_.mime,input:U.value.type,inst:$,continue:!_.abort})}}),D7=M("$ZodCheckOverwrite",($,_)=>{X_.init($,_),$._zod.check=(J)=>{J.value=_.tx(J.value)}})});class S8{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let J=$.split(` -`).filter((X)=>X),U=Math.min(...J.map((X)=>X.length-X.trimStart().length)),W=J.map((X)=>X.slice(U)).map((X)=>" ".repeat(this.indent*2)+X);for(let X of W)this.content.push(X)}compile(){let $=Function,_=this?.args,U=[...(this?.content??[""]).map((W)=>` ${W}`)];return new $(..._,U.join(` -`))}}var O7;var L7=x(()=>{O7={major:4,minor:4,patch:3}});function v7($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ZR($){if(!I8.test($))return!1;let _=$.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),J=_.padEnd(Math.ceil(_.length/4)*4,"=");return v7(J)}function vR($,_=null){try{let J=$.split(".");if(J.length!==3)return!1;let[U]=J;if(!U)return!1;let W=JSON.parse(atob(U));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&(!("alg"in W)||W.alg!==_))return!1;return!0}catch{return!1}}function FR($,_,J){if($.issues.length)_.issues.push(...p_(J,$.issues));_.value[J]=$.value}function h8($,_,J,U,W,X){let G=J in U;if($.issues.length){if(W&&X&&!G)return;_.issues.push(...p_(J,$.issues))}if(!G&&!W){if(!$.issues.length)_.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[J]});return}if($.value===void 0){if(G)_.value[J]=void 0}else _.value[J]=$.value}function yR($){let _=Object.keys($.shape);for(let U of _)if(!$.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${U}": expected a Zod schema`);let J=Dq($.shape);return{...$,keys:_,keySet:new Set(_),numKeys:_.length,optionalKeys:new Set(J)}}function hR($,_,J,U,W,X){let G=[],Y=W.keySet,Q=W.catchall._zod,q=Q.def.type,L=Q.optin==="optional",N=Q.optout==="optional";for(let R in _){if(R==="__proto__")continue;if(Y.has(R))continue;if(q==="never"){G.push(R);continue}let B=Q.run({value:_[R],issues:[]},U);if(B instanceof Promise)$.push(B.then((H)=>h8(H,J,R,_,L,N)));else h8(B,J,R,_,L,N)}if(G.length)J.issues.push({code:"unrecognized_keys",keys:G,input:_,inst:X});if(!$.length)return J;return Promise.all($).then(()=>{return J})}function ER($,_,J,U){for(let X of $)if(X.issues.length===0)return _.value=X.value,_;let W=$.filter((X)=>!C0(X));if(W.length===1)return _.value=W[0].value,W[0];return _.issues.push({code:"invalid_union",input:_.value,inst:J,errors:$.map((X)=>X.issues.map((G)=>n_(G,U,V_())))}),_}function MR($,_,J,U){let W=$.filter((X)=>X.issues.length===0);if(W.length===1)return _.value=W[0].value,_;if(W.length===0)_.issues.push({code:"invalid_union",input:_.value,inst:J,errors:$.map((X)=>X.issues.map((G)=>n_(G,U,V_())))});else _.issues.push({code:"invalid_union",input:_.value,inst:J,errors:[],inclusive:!1});return _}function B7($,_){if($===_)return{valid:!0,data:$};if($ instanceof Date&&_ instanceof Date&&+$===+_)return{valid:!0,data:$};if(f0($)&&f0(_)){let J=Object.keys(_),U=Object.keys($).filter((X)=>J.indexOf(X)!==-1),W={...$,..._};for(let X of U){let G=B7($[X],_[X]);if(!G.valid)return{valid:!1,mergeErrorPath:[X,...G.mergeErrorPath]};W[X]=G.data}return{valid:!0,data:W}}if(Array.isArray($)&&Array.isArray(_)){if($.length!==_.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let U=0;U<$.length;U++){let W=$[U],X=_[U],G=B7(W,X);if(!G.valid)return{valid:!1,mergeErrorPath:[U,...G.mergeErrorPath]};J.push(G.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function AR($,_,J){let U=new Map,W;for(let Y of _.issues)if(Y.code==="unrecognized_keys"){W??(W=Y);for(let Q of Y.keys){if(!U.has(Q))U.set(Q,{});U.get(Q).l=!0}}else $.issues.push(Y);for(let Y of J.issues)if(Y.code==="unrecognized_keys")for(let Q of Y.keys){if(!U.has(Q))U.set(Q,{});U.get(Q).r=!0}else $.issues.push(Y);let X=[...U].filter(([,Y])=>Y.l&&Y.r).map(([Y])=>Y);if(X.length&&W)$.issues.push({...W,keys:X});if(C0($))return $;let G=B7(_.value,J.value);if(!G.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(G.mergeErrorPath)}`);return $.value=G.data,$}function bR($,_){for(let J=$.length-1;J>=0;J--)if($[J]._zod[_]!=="optional")return J+1;return 0}function wR($,_,J){if($.issues.length)_.issues.push(...p_(J,$.issues));_.value[J]=$.value}function gR($,_,J,U,W){for(let X=0;X=W){_.value.length=X;break}_.issues.push(...p_(X,G.issues))}_.value[X]=G.value}for(let X=_.value.length-1;X>=U.length;X--)if(J[X]._zod.optout==="optional"&&_.value[X]===void 0)_.value.length=X;else break;return _}function kR($,_,J,U,W,X,G){if($.issues.length)if(ZU.has(typeof U))J.issues.push(...p_(U,$.issues));else J.issues.push({code:"invalid_key",origin:"map",input:W,inst:X,issues:$.issues.map((Y)=>n_(Y,G,V_()))});if(_.issues.length)if(ZU.has(typeof U))J.issues.push(...p_(U,_.issues));else J.issues.push({origin:"map",code:"invalid_element",input:W,inst:X,key:U,issues:_.issues.map((Y)=>n_(Y,G,V_()))});J.value.set($.value,_.value)}function IR($,_){if($.issues.length)_.issues.push(...$.issues);_.value.add($.value)}function fR($,_){if(_===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function CR($,_){if($.value===void 0)$.value=_.defaultValue;return $}function PR($,_){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:_});return $}function Z8($,_,J){if($.issues.length)return $.aborted=!0,$;return _._zod.run({value:$.value,issues:$.issues,fallback:$.fallback},J)}function v8($,_,J){if($.issues.length)return $.aborted=!0,$;if((J.direction||"forward")==="forward"){let W=_.transform($.value,$);if(W instanceof Promise)return W.then((X)=>y8($,X,_.out,J));return y8($,W,_.out,J)}else{let W=_.reverseTransform($.value,$);if(W instanceof Promise)return W.then((X)=>y8($,X,_.in,J));return y8($,W,_.in,J)}}function y8($,_,J,U){if($.issues.length)return $.aborted=!0,$;return J._zod.run({value:_,issues:$.issues},U)}function TR($){return $.value=Object.freeze($.value),$}function SR($,_,J,U){if(!$){let W={code:"custom",input:J,inst:U,path:[...U._zod.def.path??[]],continue:!U._zod.def.abort};if(U._zod.def.params)W.params=U._zod.def.params;_.issues.push(iJ(W))}}var R$,h1,J_,H7,N7,V7,R7,K7,F7,E7,M7,A7,b7,w7,g7,k7,I7,f7,C7,P7,T7,S7,Z7,y7,h7,m7,x7,u7,m8,d7,dU,x8,n7,c7,i7,l7,r7,p7,o7,t7,a7,s7,mR,e7,nU,$z,_z,Jz,u8,Wz,Uz,Xz,Gz,Yz,Qz,qz,d8,zz,jz,Dz,Oz,Lz,Bz,Hz,Nz,n8,cU,Vz,Rz,Kz,Fz,Ez,Mz,Az;var bz=x(()=>{T8();Z1();Rq();f8();e();L7();e();R$=M("$ZodType",($,_)=>{var J;$??($={}),$._zod.def=_,$._zod.bag=$._zod.bag||{},$._zod.version=O7;let U=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))U.unshift($);for(let W of U)for(let X of W._zod.onattach)X($);if(U.length===0)(J=$._zod).deferred??(J.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let W=(G,Y,Q)=>{let q=C0(G),L;for(let N of Y){if(N._zod.def.when){if(Bq(G))continue;if(!N._zod.def.when(G))continue}else if(q)continue;let R=G.issues.length,B=N._zod.check(G);if(B instanceof Promise&&Q?.async===!1)throw new O4;if(L||B instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await B,G.issues.length===R)return;if(!q)q=C0(G,R)});else{if(G.issues.length===R)continue;if(!q)q=C0(G,R)}}if(L)return L.then(()=>{return G});return G},X=(G,Y,Q)=>{if(C0(G))return G.aborted=!0,G;let q=W(Y,U,Q);if(q instanceof Promise){if(Q.async===!1)throw new O4;return q.then((L)=>$._zod.parse(L,Q))}return $._zod.parse(q,Q)};$._zod.run=(G,Y)=>{if(Y.skipChecks)return $._zod.parse(G,Y);if(Y.direction==="backward"){let q=$._zod.parse({value:G.value,issues:[]},{...Y,skipChecks:!0});if(q instanceof Promise)return q.then((L)=>{return X(L,G,Y)});return X(q,G,Y)}let Q=$._zod.parse(G,Y);if(Q instanceof Promise){if(Y.async===!1)throw new O4;return Q.then((q)=>W(q,U,Y))}return W(Q,U,Y)}}Z$($,"~standard",()=>({validate:(W)=>{try{let X=Nq($,W);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return Vq($,W).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}))}),h1=M("$ZodString",($,_)=>{R$.init($,_),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??uq($._zod.bag),$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=String(J.value)}catch(W){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:$}),J}}),J_=M("$ZodStringFormat",($,_)=>{sJ.init($,_),h1.init($,_)}),H7=M("$ZodGUID",($,_)=>{_.pattern??(_.pattern=gq),J_.init($,_)}),N7=M("$ZodUUID",($,_)=>{if(_.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[_.version];if(U===void 0)throw Error(`Invalid UUID version: "${_.version}"`);_.pattern??(_.pattern=y1(U))}else _.pattern??(_.pattern=y1());J_.init($,_)}),V7=M("$ZodEmail",($,_)=>{_.pattern??(_.pattern=kq),J_.init($,_)}),R7=M("$ZodURL",($,_)=>{J_.init($,_),$._zod.check=(J)=>{try{let U=J.value.trim();if(!_.normalize&&_.protocol?.source===vq.source){if(!/^https?:\/\//i.test(U)){J.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:J.value,inst:$,continue:!_.abort});return}}let W=new URL(U);if(_.hostname){if(_.hostname.lastIndex=0,!_.hostname.test(W.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_.hostname.source,input:J.value,inst:$,continue:!_.abort})}if(_.protocol){if(_.protocol.lastIndex=0,!_.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:_.protocol.source,input:J.value,inst:$,continue:!_.abort})}if(_.normalize)J.value=W.href;else J.value=U;return}catch(U){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:$,continue:!_.abort})}}}),K7=M("$ZodEmoji",($,_)=>{_.pattern??(_.pattern=Iq()),J_.init($,_)}),F7=M("$ZodNanoID",($,_)=>{_.pattern??(_.pattern=bq),J_.init($,_)}),E7=M("$ZodCUID",($,_)=>{_.pattern??(_.pattern=Kq),J_.init($,_)}),M7=M("$ZodCUID2",($,_)=>{_.pattern??(_.pattern=Fq),J_.init($,_)}),A7=M("$ZodULID",($,_)=>{_.pattern??(_.pattern=Eq),J_.init($,_)}),b7=M("$ZodXID",($,_)=>{_.pattern??(_.pattern=Mq),J_.init($,_)}),w7=M("$ZodKSUID",($,_)=>{_.pattern??(_.pattern=Aq),J_.init($,_)}),g7=M("$ZodISODateTime",($,_)=>{_.pattern??(_.pattern=xq(_)),J_.init($,_)}),k7=M("$ZodISODate",($,_)=>{_.pattern??(_.pattern=hq),J_.init($,_)}),I7=M("$ZodISOTime",($,_)=>{_.pattern??(_.pattern=mq(_)),J_.init($,_)}),f7=M("$ZodISODuration",($,_)=>{_.pattern??(_.pattern=wq),J_.init($,_)}),C7=M("$ZodIPv4",($,_)=>{_.pattern??(_.pattern=fq),J_.init($,_),$._zod.bag.format="ipv4"}),P7=M("$ZodIPv6",($,_)=>{_.pattern??(_.pattern=Cq),J_.init($,_),$._zod.bag.format="ipv6",$._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:$,continue:!_.abort})}}}),T7=M("$ZodMAC",($,_)=>{_.pattern??(_.pattern=Pq(_.delimiter)),J_.init($,_),$._zod.bag.format="mac"}),S7=M("$ZodCIDRv4",($,_)=>{_.pattern??(_.pattern=Tq),J_.init($,_)}),Z7=M("$ZodCIDRv6",($,_)=>{_.pattern??(_.pattern=Sq),J_.init($,_),$._zod.check=(J)=>{let U=J.value.split("/");try{if(U.length!==2)throw Error();let[W,X]=U;if(!X)throw Error();let G=Number(X);if(`${G}`!==X)throw Error();if(G<0||G>128)throw Error();new URL(`http://[${W}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:$,continue:!_.abort})}}});y7=M("$ZodBase64",($,_)=>{_.pattern??(_.pattern=Zq),J_.init($,_),$._zod.bag.contentEncoding="base64",$._zod.check=(J)=>{if(v7(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:$,continue:!_.abort})}});h7=M("$ZodBase64URL",($,_)=>{_.pattern??(_.pattern=I8),J_.init($,_),$._zod.bag.contentEncoding="base64url",$._zod.check=(J)=>{if(ZR(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:$,continue:!_.abort})}}),m7=M("$ZodE164",($,_)=>{_.pattern??(_.pattern=yq),J_.init($,_)});x7=M("$ZodJWT",($,_)=>{J_.init($,_),$._zod.check=(J)=>{if(vR(J.value,_.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:$,continue:!_.abort})}}),u7=M("$ZodCustomStringFormat",($,_)=>{J_.init($,_),$._zod.check=(J)=>{if(_.fn(J.value))return;J.issues.push({code:"invalid_format",format:_.format,input:J.value,inst:$,continue:!_.abort})}}),m8=M("$ZodNumber",($,_)=>{R$.init($,_),$._zod.pattern=$._zod.bag.pattern??mU,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=Number(J.value)}catch(G){}let W=J.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return J;let X=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:W,inst:$,...X?{received:X}:{}}),J}}),d7=M("$ZodNumberFormat",($,_)=>{tq.init($,_),m8.init($,_)}),dU=M("$ZodBoolean",($,_)=>{R$.init($,_),$._zod.pattern=cq,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=Boolean(J.value)}catch(X){}let W=J.value;if(typeof W==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:$}),J}}),x8=M("$ZodBigInt",($,_)=>{R$.init($,_),$._zod.pattern=dq,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=BigInt(J.value)}catch(W){}if(typeof J.value==="bigint")return J;return J.issues.push({expected:"bigint",code:"invalid_type",input:J.value,inst:$}),J}}),n7=M("$ZodBigIntFormat",($,_)=>{aq.init($,_),x8.init($,_)}),c7=M("$ZodSymbol",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W==="symbol")return J;return J.issues.push({expected:"symbol",code:"invalid_type",input:W,inst:$}),J}}),i7=M("$ZodUndefined",($,_)=>{R$.init($,_),$._zod.pattern=lq,$._zod.values=new Set([void 0]),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"undefined",code:"invalid_type",input:W,inst:$}),J}}),l7=M("$ZodNull",($,_)=>{R$.init($,_),$._zod.pattern=iq,$._zod.values=new Set([null]),$._zod.parse=(J,U)=>{let W=J.value;if(W===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:W,inst:$}),J}}),r7=M("$ZodAny",($,_)=>{R$.init($,_),$._zod.parse=(J)=>J}),p7=M("$ZodUnknown",($,_)=>{R$.init($,_),$._zod.parse=(J)=>J}),o7=M("$ZodNever",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:$}),J}}),t7=M("$ZodVoid",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"void",code:"invalid_type",input:W,inst:$}),J}}),a7=M("$ZodDate",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=new Date(J.value)}catch(Y){}let W=J.value,X=W instanceof Date;if(X&&!Number.isNaN(W.getTime()))return J;return J.issues.push({expected:"date",code:"invalid_type",input:W,...X?{received:"Invalid Date"}:{},inst:$}),J}});s7=M("$ZodArray",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!Array.isArray(W))return J.issues.push({expected:"array",code:"invalid_type",input:W,inst:$}),J;J.value=Array(W.length);let X=[];for(let G=0;GFR(q,J,G)));else FR(Q,J,G)}if(X.length)return Promise.all(X).then(()=>J);return J}});mR=M("$ZodObject",($,_)=>{if(R$.init($,_),!Object.getOwnPropertyDescriptor(_,"shape")?.get){let Y=_.shape;Object.defineProperty(_,"shape",{get:()=>{let Q={...Y};return Object.defineProperty(_,"shape",{value:Q}),Q}})}let U=cJ(()=>yR(_));Z$($._zod,"propValues",()=>{let Y=_.shape,Q={};for(let q in Y){let L=Y[q]._zod;if(L.values){Q[q]??(Q[q]=new Set);for(let N of L.values)Q[q].add(N)}}return Q});let W=v1,X=_.catchall,G;$._zod.parse=(Y,Q)=>{G??(G=U.value);let q=Y.value;if(!W(q))return Y.issues.push({expected:"object",code:"invalid_type",input:q,inst:$}),Y;Y.value={};let L=[],N=G.shape;for(let R of G.keys){let B=N[R],H=B._zod.optin==="optional",V=B._zod.optout==="optional",K=B._zod.run({value:q[R],issues:[]},Q);if(K instanceof Promise)L.push(K.then((E)=>h8(E,Y,R,q,H,V)));else h8(K,Y,R,q,H,V)}if(!X)return L.length?Promise.all(L).then(()=>Y):Y;return hR(L,q,Y,Q,U.value,$)}}),e7=M("$ZodObjectJIT",($,_)=>{mR.init($,_);let J=$._zod.parse,U=cJ(()=>yR(_)),W=(R)=>{let B=new S8(["shape","payload","ctx"]),H=U.value,V=(w)=>{let A=B8(w);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};B.write("const input = payload.value;");let K=Object.create(null),E=0;for(let w of H.keys)K[w]=`key_${E++}`;B.write("const newResult = {};");for(let w of H.keys){let A=K[w],g=B8(w),v=R[w],k=v?._zod?.optin==="optional",u=v?._zod?.optout==="optional";if(B.write(`const ${A} = ${V(w)};`),k&&u)B.write(` - if (${A}.issues.length) { - if (${g} in input) { - payload.issues = payload.issues.concat(${A}.issues.map(iss => ({ +var l8=Object.create;var{getPrototypeOf:t8,defineProperty:qN,getOwnPropertyNames:o8}=Object;var p8=Object.prototype.hasOwnProperty;function e8(_){return this[_]}var a8,s8,_Y=(_,$,g)=>{var U=_!=null&&typeof _==="object";if(U){var D=$?a8??=new WeakMap:s8??=new WeakMap,I=D.get(_);if(I)return I}g=_!=null?l8(t8(_)):{};let j=$||!_||!_.__esModule?qN(g,"default",{value:_,enumerable:!0}):g;for(let N of o8(_))if(!p8.call(j,N))qN(j,N,{get:e8.bind(_,N),enumerable:!0});if(U)D.set(_,j);return j};var e6=(_,$)=>()=>($||_(($={exports:{}}).exports,$),$.exports);var $Y=(_)=>_;function gY(_,$){this[_]=$Y.bind(null,$)}var r$=(_,$)=>{for(var g in $)qN(_,g,{get:$[g],enumerable:!0,configurable:!0,set:gY.bind($,g)})};var f=(_,$)=>()=>(_&&($=_(_=0)),$);var O_=import.meta.require;function Y(_,$,g){function U(N,O){if(!N._zod)Object.defineProperty(N,"_zod",{value:{def:O,constr:j,traits:new Set},enumerable:!1});if(N._zod.traits.has(_))return;N._zod.traits.add(_),$(N,O);let A=j.prototype,L=Object.keys(A);for(let z=0;z{if(g?.Parent&&N instanceof g.Parent)return!0;return N?._zod?.traits?.has(_)}}),Object.defineProperty(j,"name",{value:_}),j}function Z_(_){if(_)Object.assign(A4,_);return A4}var GX,XI,RI,x$,L4,A4;var J4=f(()=>{XI=Object.freeze({status:"aborted"});RI=Symbol("zod_brand");x$=class x$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};L4=class L4 extends Error{constructor(_){super(`Encountered unidirectional transform during encode: ${_}`);this.name="ZodEncodeError"}};(GX=globalThis).__zod_globalConfig??(GX.__zod_globalConfig={});A4=globalThis.__zod_globalConfig});var H={};r$(H,{unwrapMessage:()=>tg,uint8ArrayToHex:()=>PK,uint8ArrayToBase64url:()=>LK,uint8ArrayToBase64:()=>TX,stringifyPrimitive:()=>F,slugify:()=>yE,shallowClone:()=>cE,safeExtend:()=>IK,required:()=>EK,randomString:()=>aB,propertyKeyTypes:()=>eg,promiseAllObject:()=>eB,primitiveTypes:()=>nE,prefixIssues:()=>s_,pick:()=>gK,partial:()=>NK,parsedType:()=>M,optionalKeys:()=>dE,omit:()=>DK,objectClone:()=>tB,numKeys:()=>sB,nullish:()=>M6,normalizeParams:()=>C,mergeDefs:()=>D6,merge:()=>jK,jsonStringifyReplacer:()=>K0,joinValues:()=>B,issue:()=>F0,isPlainObject:()=>b6,isObject:()=>P4,hexToUint8Array:()=>JK,getSizableOrigin:()=>ag,getParsedType:()=>_K,getLengthableOrigin:()=>sg,getEnumValues:()=>og,getElementAtPath:()=>pB,floatSafeRemainder:()=>xE,finalizeIssue:()=>l_,extend:()=>UK,explicitlyAborted:()=>lE,escapeRegex:()=>P$,esc:()=>GI,defineLazy:()=>$_,createTransparentProxy:()=>$K,cloneDef:()=>oB,clone:()=>y_,cleanRegex:()=>pg,cleanEnum:()=>OK,captureStackTrace:()=>YI,cached:()=>V0,base64urlToUint8Array:()=>AK,base64ToUint8Array:()=>QX,assignProp:()=>Z6,assertNotEqual:()=>dB,assertNever:()=>iB,assertIs:()=>mB,assertEqual:()=>nB,assert:()=>lB,allowsEval:()=>hE,aborted:()=>H6,NUMBER_FORMAT_RANGES:()=>mE,Class:()=>qX,BIGINT_FORMAT_RANGES:()=>iE});function nB(_){return _}function dB(_){return _}function mB(_){}function iB(_){throw Error("Unexpected value in exhaustive check")}function lB(_){}function og(_){let $=Object.values(_).filter((U)=>typeof U==="number");return Object.entries(_).filter(([U,D])=>$.indexOf(+U)===-1).map(([U,D])=>D)}function B(_,$="|"){return _.map((g)=>F(g)).join($)}function K0(_,$){if(typeof $==="bigint")return $.toString();return $}function V0(_){return{get value(){{let g=_();return Object.defineProperty(this,"value",{value:g}),g}throw Error("cached value already set")}}}function M6(_){return _===null||_===void 0}function pg(_){let $=_.startsWith("^")?1:0,g=_.endsWith("$")?_.length-1:_.length;return _.slice($,g)}function xE(_,$){let g=_/$,U=Math.round(g),D=Number.EPSILON*Math.max(Math.abs(g),1);if(Math.abs(g-U)g?.[U],_)}function eB(_){let $=Object.keys(_),g=$.map((U)=>_[U]);return Promise.all(g).then((U)=>{let D={};for(let I=0;I<$.length;I++)D[$[I]]=U[I];return D})}function aB(_=10){let g="";for(let U=0;U<_;U++)g+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return g}function GI(_){return JSON.stringify(_)}function yE(_){return _.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function P4(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function b6(_){if(P4(_)===!1)return!1;let $=_.constructor;if($===void 0)return!0;if(typeof $!=="function")return!0;let g=$.prototype;if(P4(g)===!1)return!1;if(Object.prototype.hasOwnProperty.call(g,"isPrototypeOf")===!1)return!1;return!0}function cE(_){if(b6(_))return{..._};if(Array.isArray(_))return[..._];if(_ instanceof Map)return new Map(_);if(_ instanceof Set)return new Set(_);return _}function sB(_){let $=0;for(let g in _)if(Object.prototype.hasOwnProperty.call(_,g))$++;return $}function P$(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y_(_,$,g){let U=new _._zod.constr($??_._zod.def);if(!$||g?.parent)U._zod.parent=_;return U}function C(_){let $=_;if(!$)return{};if(typeof $==="string")return{error:()=>$};if($?.message!==void 0){if($?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");$.error=$.message}if(delete $.message,typeof $.error==="string")return{...$,error:()=>$.error};return $}function $K(_){let $;return new Proxy({},{get(g,U,D){return $??($=_()),Reflect.get($,U,D)},set(g,U,D,I){return $??($=_()),Reflect.set($,U,D,I)},has(g,U){return $??($=_()),Reflect.has($,U)},deleteProperty(g,U){return $??($=_()),Reflect.deleteProperty($,U)},ownKeys(g){return $??($=_()),Reflect.ownKeys($)},getOwnPropertyDescriptor(g,U){return $??($=_()),Reflect.getOwnPropertyDescriptor($,U)},defineProperty(g,U,D){return $??($=_()),Reflect.defineProperty($,U,D)}})}function F(_){if(typeof _==="bigint")return _.toString()+"n";if(typeof _==="string")return`"${_}"`;return`${_}`}function dE(_){return Object.keys(_).filter(($)=>{return _[$]._zod.optin==="optional"&&_[$]._zod.optout==="optional"})}function gK(_,$){let g=_._zod.def,U=g.checks;if(U&&U.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let I=D6(_._zod.def,{get shape(){let j={};for(let N in $){if(!(N in g.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;j[N]=g.shape[N]}return Z6(this,"shape",j),j},checks:[]});return y_(_,I)}function DK(_,$){let g=_._zod.def,U=g.checks;if(U&&U.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let I=D6(_._zod.def,{get shape(){let j={..._._zod.def.shape};for(let N in $){if(!(N in g.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;delete j[N]}return Z6(this,"shape",j),j},checks:[]});return y_(_,I)}function UK(_,$){if(!b6($))throw Error("Invalid input to extend: expected a plain object");let g=_._zod.def.checks;if(g&&g.length>0){let I=_._zod.def.shape;for(let j in $)if(Object.getOwnPropertyDescriptor(I,j)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let D=D6(_._zod.def,{get shape(){let I={..._._zod.def.shape,...$};return Z6(this,"shape",I),I}});return y_(_,D)}function IK(_,$){if(!b6($))throw Error("Invalid input to safeExtend: expected a plain object");let g=D6(_._zod.def,{get shape(){let U={..._._zod.def.shape,...$};return Z6(this,"shape",U),U}});return y_(_,g)}function jK(_,$){if(_._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let g=D6(_._zod.def,{get shape(){let U={..._._zod.def.shape,...$._zod.def.shape};return Z6(this,"shape",U),U},get catchall(){return $._zod.def.catchall},checks:$._zod.def.checks??[]});return y_(_,g)}function NK(_,$,g){let D=$._zod.def.checks;if(D&&D.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let j=D6($._zod.def,{get shape(){let N=$._zod.def.shape,O={...N};if(g)for(let A in g){if(!(A in N))throw Error(`Unrecognized key: "${A}"`);if(!g[A])continue;O[A]=_?new _({type:"optional",innerType:N[A]}):N[A]}else for(let A in N)O[A]=_?new _({type:"optional",innerType:N[A]}):N[A];return Z6(this,"shape",O),O},checks:[]});return y_($,j)}function EK(_,$,g){let U=D6($._zod.def,{get shape(){let D=$._zod.def.shape,I={...D};if(g)for(let j in g){if(!(j in I))throw Error(`Unrecognized key: "${j}"`);if(!g[j])continue;I[j]=new _({type:"nonoptional",innerType:D[j]})}else for(let j in D)I[j]=new _({type:"nonoptional",innerType:D[j]});return Z6(this,"shape",I),I}});return y_($,U)}function H6(_,$=0){if(_.aborted===!0)return!0;for(let g=$;g<_.issues.length;g++)if(_.issues[g]?.continue!==!0)return!0;return!1}function lE(_,$=0){if(_.aborted===!0)return!0;for(let g=$;g<_.issues.length;g++)if(_.issues[g]?.continue===!1)return!0;return!1}function s_(_,$){return $.map((g)=>{var U;return(U=g).path??(U.path=[]),g.path.unshift(_),g})}function tg(_){return typeof _==="string"?_:_?.message}function l_(_,$,g){let U=_.message?_.message:tg(_.inst?._zod.def?.error?.(_))??tg($?.error?.(_))??tg(g.customError?.(_))??tg(g.localeError?.(_))??"Invalid input",{inst:D,continue:I,input:j,...N}=_;if(N.path??(N.path=[]),N.message=U,$?.reportInput)N.input=j;return N}function ag(_){if(_ instanceof Set)return"set";if(_ instanceof Map)return"map";if(_ instanceof File)return"file";return"unknown"}function sg(_){if(Array.isArray(_))return"array";if(typeof _==="string")return"string";return"unknown"}function M(_){let $=typeof _;switch($){case"number":return Number.isNaN(_)?"nan":"number";case"object":{if(_===null)return"null";if(Array.isArray(_))return"array";let g=_;if(g&&Object.getPrototypeOf(g)!==Object.prototype&&"constructor"in g&&g.constructor)return g.constructor.name}}return $}function F0(..._){let[$,g,U]=_;if(typeof $==="string")return{message:$,code:"custom",input:g,inst:U};return{...$}}function OK(_){return Object.entries(_).filter(([$,g])=>{return Number.isNaN(Number.parseInt($,10))}).map(($)=>$[1])}function QX(_){let $=atob(_),g=new Uint8Array($.length);for(let U=0;U<$.length;U++)g[U]=$.charCodeAt(U);return g}function TX(_){let $="";for(let g=0;g<_.length;g++)$+=String.fromCharCode(_[g]);return btoa($)}function AK(_){let $=_.replace(/-/g,"+").replace(/_/g,"/"),g="=".repeat((4-$.length%4)%4);return QX($+g)}function LK(_){return TX(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function JK(_){let $=_.replace(/^0x/,"");if($.length%2!==0)throw Error("Invalid hex string length");let g=new Uint8Array($.length/2);for(let U=0;U<$.length;U+=2)g[U/2]=Number.parseInt($.slice(U,U+2),16);return g}function PK(_){return Array.from(_).map(($)=>$.toString(16).padStart(2,"0")).join("")}class qX{constructor(..._){}}var YX,YI,hE,_K=(_)=>{let $=typeof _;switch($){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(_)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(_))return"array";if(_===null)return"null";if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return"promise";if(typeof Map<"u"&&_ instanceof Map)return"map";if(typeof Set<"u"&&_ instanceof Set)return"set";if(typeof Date<"u"&&_ instanceof Date)return"date";if(typeof File<"u"&&_ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${$}`)}},eg,nE,mE,iE;var c=f(()=>{J4();YX=Symbol("evaluating");YI="captureStackTrace"in Error?Error.captureStackTrace:(..._)=>{};hE=V0(()=>{if(A4.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});eg=new Set(["string","number","symbol"]),nE=new Set(["string","number","bigint","boolean","symbol","undefined"]);mE={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},iE={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function M0(_,$=(g)=>g.message){let g={},U=[];for(let D of _.issues)if(D.path.length>0)g[D.path[0]]=g[D.path[0]]||[],g[D.path[0]].push($(D));else U.push($(D));return{formErrors:U,fieldErrors:g}}function Z0(_,$=(g)=>g.message){let g={_errors:[]},U=(D,I=[])=>{for(let j of D.issues)if(j.code==="invalid_union"&&j.errors.length)j.errors.map((N)=>U({issues:N},[...I,...j.path]));else if(j.code==="invalid_key")U({issues:j.issues},[...I,...j.path]);else if(j.code==="invalid_element")U({issues:j.issues},[...I,...j.path]);else{let N=[...I,...j.path];if(N.length===0)g._errors.push($(j));else{let O=g,A=0;while(Ag.message){let g={errors:[]},U=(D,I=[])=>{var j,N;for(let O of D.issues)if(O.code==="invalid_union"&&O.errors.length)O.errors.map((A)=>U({issues:A},[...I,...O.path]));else if(O.code==="invalid_key")U({issues:O.issues},[...I,...O.path]);else if(O.code==="invalid_element")U({issues:O.issues},[...I,...O.path]);else{let A=[...I,...O.path];if(A.length===0){g.errors.push($(O));continue}let L=g,z=0;while(ztypeof U==="object"?U.key:U);for(let U of g)if(typeof U==="number")$.push(`[${U}]`);else if(typeof U==="symbol")$.push(`[${JSON.stringify(String(U))}]`);else if(/[^\w$]/.test(U))$.push(`[${JSON.stringify(U)}]`);else{if($.length)$.push(".");$.push(U)}return $.join("")}function TI(_){let $=[],g=[..._.issues].sort((U,D)=>(U.path??[]).length-(D.path??[]).length);for(let U of g)if($.push(`\u2716 ${U.message}`),U.path?.length)$.push(` \u2192 at ${KX(U.path)}`);return $.join(` +`)}var BX=(_,$)=>{_.name="$ZodError",Object.defineProperty(_,"_zod",{value:_._zod,enumerable:!1}),Object.defineProperty(_,"issues",{value:$,enumerable:!1}),_.message=JSON.stringify($,K0,2),Object.defineProperty(_,"toString",{value:()=>_.message,enumerable:!1})},_D,_$;var tE=f(()=>{J4();c();_D=Y("$ZodError",BX),_$=Y("$ZodError",BX,{Parent:Error})});var b0=(_)=>($,g,U,D)=>{let I=U?{...U,async:!1}:{async:!1},j=$._zod.run({value:g,issues:[]},I);if(j instanceof Promise)throw new x$;if(j.issues.length){let N=new(D?.Err??_)(j.issues.map((O)=>l_(O,I,Z_())));throw YI(N,D?.callee),N}return j.value},qI,H0=(_)=>async($,g,U,D)=>{let I=U?{...U,async:!0}:{async:!0},j=$._zod.run({value:g,issues:[]},I);if(j instanceof Promise)j=await j;if(j.issues.length){let N=new(D?.Err??_)(j.issues.map((O)=>l_(O,I,Z_())));throw YI(N,D?.callee),N}return j.value},BI,k0=(_)=>($,g,U)=>{let D=U?{...U,async:!1}:{async:!1},I=$._zod.run({value:g,issues:[]},D);if(I instanceof Promise)throw new x$;return I.issues.length?{success:!1,error:new(_??_D)(I.issues.map((j)=>l_(j,D,Z_())))}:{success:!0,data:I.value}},oE,C0=(_)=>async($,g,U)=>{let D=U?{...U,async:!0}:{async:!0},I=$._zod.run({value:g,issues:[]},D);if(I instanceof Promise)I=await I;return I.issues.length?{success:!1,error:new _(I.issues.map((j)=>l_(j,D,Z_())))}:{success:!0,data:I.value}},pE,KI=(_)=>($,g,U)=>{let D=U?{...U,direction:"backward"}:{direction:"backward"};return b0(_)($,g,D)},SK,VI=(_)=>($,g,U)=>{return b0(_)($,g,U)},WK,FI=(_)=>async($,g,U)=>{let D=U?{...U,direction:"backward"}:{direction:"backward"};return H0(_)($,g,D)},XK,MI=(_)=>async($,g,U)=>{return H0(_)($,g,U)},RK,ZI=(_)=>($,g,U)=>{let D=U?{...U,direction:"backward"}:{direction:"backward"};return k0(_)($,g,D)},GK,bI=(_)=>($,g,U)=>{return k0(_)($,g,U)},YK,HI=(_)=>async($,g,U)=>{let D=U?{...U,direction:"backward"}:{direction:"backward"};return C0(_)($,g,D)},QK,kI=(_)=>async($,g,U)=>{return C0(_)($,g,U)},TK;var eE=f(()=>{J4();tE();c();qI=b0(_$),BI=H0(_$),oE=k0(_$),pE=C0(_$),SK=KI(_$),WK=VI(_$),XK=FI(_$),RK=MI(_$),GK=ZI(_$),YK=bI(_$),QK=HI(_$),TK=kI(_$)});var $$={};r$($$,{xid:()=>$2,uuid7:()=>VK,uuid6:()=>KK,uuid4:()=>BK,uuid:()=>z4,uppercase:()=>V2,unicodeEmail:()=>VX,undefined:()=>B2,ulid:()=>_2,time:()=>X2,string:()=>G2,sha512_hex:()=>lK,sha512_base64url:()=>oK,sha512_base64:()=>tK,sha384_hex:()=>dK,sha384_base64url:()=>iK,sha384_base64:()=>mK,sha256_hex:()=>hK,sha256_base64url:()=>nK,sha256_base64:()=>cK,sha1_hex:()=>uK,sha1_base64url:()=>yK,sha1_base64:()=>xK,rfc5322Email:()=>MK,number:()=>$D,null:()=>q2,nanoid:()=>D2,md5_hex:()=>vK,md5_base64url:()=>wK,md5_base64:()=>fK,mac:()=>A2,lowercase:()=>K2,ksuid:()=>g2,ipv6:()=>O2,ipv4:()=>E2,integer:()=>Q2,idnEmail:()=>ZK,httpProtocol:()=>z2,html5Email:()=>FK,hostname:()=>kK,hex:()=>rK,guid:()=>I2,extendedDuration:()=>qK,emoji:()=>N2,email:()=>j2,e164:()=>S2,duration:()=>U2,domain:()=>CK,datetime:()=>R2,date:()=>W2,cuid2:()=>sE,cuid:()=>aE,cidrv6:()=>J2,cidrv4:()=>L2,browserEmail:()=>bK,boolean:()=>T2,bigint:()=>Y2,base64url:()=>CI,base64:()=>P2});function N2(){return new RegExp(HK,"u")}function MX(_){return typeof _.precision==="number"?_.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":_.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${_.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function X2(_){return new RegExp(`^${MX(_)}$`)}function R2(_){let $=MX({precision:_.precision}),g=["Z"];if(_.local)g.push("");if(_.offset)g.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${$}(?:${g.join("|")})`;return new RegExp(`^${FX}T(?:${U})$`)}function gD(_,$){return new RegExp(`^[A-Za-z0-9+/]{${_}}${$}$`)}function DD(_){return new RegExp(`^[A-Za-z0-9_-]{${_}}$`)}var aE,sE,_2,$2,g2,D2,U2,qK,I2,z4=(_)=>{if(!_)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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${_}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},BK,KK,VK,j2,FK,MK,VX,ZK,bK,HK="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",E2,O2,A2=(_)=>{let $=P$(_??":");return new RegExp(`^(?:[0-9A-F]{2}${$}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${$}){5}[0-9a-f]{2}$`)},L2,J2,P2,CI,kK,CK,z2,S2,FX="(?:(?:\\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])))",W2,G2=(_)=>{let $=_?`[\\s\\S]{${_?.minimum??0},${_?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${$}$`)},Y2,Q2,$D,T2,q2,B2,K2,V2,rK,vK,fK,wK,uK,xK,yK,hK,cK,nK,dK,mK,iK,lK,tK,oK;var rI=f(()=>{c();aE=/^[cC][0-9a-z]{6,}$/,sE=/^[0-9a-z]+$/,_2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$2=/^[0-9a-vA-V]{20}$/,g2=/^[A-Za-z0-9]{27}$/,D2=/^[a-zA-Z0-9_-]{21}$/,U2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qK=/^[-+]?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)?)??$/,I2=/^([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})$/,BK=z4(4),KK=z4(6),VK=z4(7),j2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,FK=/^[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])?)*$/,MK=/^(([^<>()\[\]\\.,;:\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,}))$/,VX=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,ZK=VX,bK=/^[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])?)*$/;E2=/^(?:(?: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])$/,O2=/^(([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}|:))$/,L2=/^((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])$/,J2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,P2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,CI=/^[A-Za-z0-9_-]*$/,kK=/^(?=.{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])?)*\.?$/,CK=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,z2=/^https?$/,S2=/^\+[1-9]\d{6,14}$/,W2=new RegExp(`^${FX}$`);Y2=/^-?\d+n?$/,Q2=/^-?\d+$/,$D=/^-?\d+(?:\.\d+)?$/,T2=/^(?:true|false)$/i,q2=/^null$/i,B2=/^undefined$/i,K2=/^[^A-Z]*$/,V2=/^[^a-z]*$/,rK=/^[0-9a-fA-F]*$/;vK=/^[0-9a-fA-F]{32}$/,fK=gD(22,"=="),wK=DD(22),uK=/^[0-9a-fA-F]{40}$/,xK=gD(27,"="),yK=DD(27),hK=/^[0-9a-fA-F]{64}$/,cK=gD(43,"="),nK=DD(43),dK=/^[0-9a-fA-F]{96}$/,mK=gD(64,""),iK=DD(64),lK=/^[0-9a-fA-F]{128}$/,tK=gD(86,"=="),oK=DD(86)});function ZX(_,$,g){if(_.issues.length)$.issues.push(...s_(g,_.issues))}var Y_,bX,vI,fI,F2,M2,Z2,b2,H2,k2,C2,r2,v2,r0,f2,w2,u2,x2,y2,h2,c2,n2,d2;var wI=f(()=>{J4();rI();c();Y_=Y("$ZodCheck",(_,$)=>{var g;_._zod??(_._zod={}),_._zod.def=$,(g=_._zod).onattach??(g.onattach=[])}),bX={number:"number",bigint:"bigint",object:"date"},vI=Y("$ZodCheckLessThan",(_,$)=>{Y_.init(_,$);let g=bX[typeof $.value];_._zod.onattach.push((U)=>{let D=U._zod.bag,I=($.inclusive?D.maximum:D.exclusiveMaximum)??Number.POSITIVE_INFINITY;if($.value{if($.inclusive?U.value<=$.value:U.value<$.value)return;U.issues.push({origin:g,code:"too_big",maximum:typeof $.value==="object"?$.value.getTime():$.value,input:U.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),fI=Y("$ZodCheckGreaterThan",(_,$)=>{Y_.init(_,$);let g=bX[typeof $.value];_._zod.onattach.push((U)=>{let D=U._zod.bag,I=($.inclusive?D.minimum:D.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if($.value>I)if($.inclusive)D.minimum=$.value;else D.exclusiveMinimum=$.value}),_._zod.check=(U)=>{if($.inclusive?U.value>=$.value:U.value>$.value)return;U.issues.push({origin:g,code:"too_small",minimum:typeof $.value==="object"?$.value.getTime():$.value,input:U.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),F2=Y("$ZodCheckMultipleOf",(_,$)=>{Y_.init(_,$),_._zod.onattach.push((g)=>{var U;(U=g._zod.bag).multipleOf??(U.multipleOf=$.value)}),_._zod.check=(g)=>{if(typeof g.value!==typeof $.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof g.value==="bigint"?g.value%$.value===BigInt(0):xE(g.value,$.value)===0)return;g.issues.push({origin:typeof g.value,code:"not_multiple_of",divisor:$.value,input:g.value,inst:_,continue:!$.abort})}}),M2=Y("$ZodCheckNumberFormat",(_,$)=>{Y_.init(_,$),$.format=$.format||"float64";let g=$.format?.includes("int"),U=g?"int":"number",[D,I]=mE[$.format];_._zod.onattach.push((j)=>{let N=j._zod.bag;if(N.format=$.format,N.minimum=D,N.maximum=I,g)N.pattern=Q2}),_._zod.check=(j)=>{let N=j.value;if(g){if(!Number.isInteger(N)){j.issues.push({expected:U,format:$.format,code:"invalid_type",continue:!1,input:N,inst:_});return}if(!Number.isSafeInteger(N)){if(N>0)j.issues.push({input:N,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:U,inclusive:!0,continue:!$.abort});else j.issues.push({input:N,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:U,inclusive:!0,continue:!$.abort});return}}if(NI)j.issues.push({origin:"number",input:N,code:"too_big",maximum:I,inclusive:!0,inst:_,continue:!$.abort})}}),Z2=Y("$ZodCheckBigIntFormat",(_,$)=>{Y_.init(_,$);let[g,U]=iE[$.format];_._zod.onattach.push((D)=>{let I=D._zod.bag;I.format=$.format,I.minimum=g,I.maximum=U}),_._zod.check=(D)=>{let I=D.value;if(IU)D.issues.push({origin:"bigint",input:I,code:"too_big",maximum:U,inclusive:!0,inst:_,continue:!$.abort})}}),b2=Y("$ZodCheckMaxSize",(_,$)=>{var g;Y_.init(_,$),(g=_._zod.def).when??(g.when=(U)=>{let D=U.value;return!M6(D)&&D.size!==void 0}),_._zod.onattach.push((U)=>{let D=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let D=U.value;if(D.size<=$.maximum)return;U.issues.push({origin:ag(D),code:"too_big",maximum:$.maximum,inclusive:!0,input:D,inst:_,continue:!$.abort})}}),H2=Y("$ZodCheckMinSize",(_,$)=>{var g;Y_.init(_,$),(g=_._zod.def).when??(g.when=(U)=>{let D=U.value;return!M6(D)&&D.size!==void 0}),_._zod.onattach.push((U)=>{let D=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>D)U._zod.bag.minimum=$.minimum}),_._zod.check=(U)=>{let D=U.value;if(D.size>=$.minimum)return;U.issues.push({origin:ag(D),code:"too_small",minimum:$.minimum,inclusive:!0,input:D,inst:_,continue:!$.abort})}}),k2=Y("$ZodCheckSizeEquals",(_,$)=>{var g;Y_.init(_,$),(g=_._zod.def).when??(g.when=(U)=>{let D=U.value;return!M6(D)&&D.size!==void 0}),_._zod.onattach.push((U)=>{let D=U._zod.bag;D.minimum=$.size,D.maximum=$.size,D.size=$.size}),_._zod.check=(U)=>{let D=U.value,I=D.size;if(I===$.size)return;let j=I>$.size;U.issues.push({origin:ag(D),...j?{code:"too_big",maximum:$.size}:{code:"too_small",minimum:$.size},inclusive:!0,exact:!0,input:U.value,inst:_,continue:!$.abort})}}),C2=Y("$ZodCheckMaxLength",(_,$)=>{var g;Y_.init(_,$),(g=_._zod.def).when??(g.when=(U)=>{let D=U.value;return!M6(D)&&D.length!==void 0}),_._zod.onattach.push((U)=>{let D=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let D=U.value;if(D.length<=$.maximum)return;let j=sg(D);U.issues.push({origin:j,code:"too_big",maximum:$.maximum,inclusive:!0,input:D,inst:_,continue:!$.abort})}}),r2=Y("$ZodCheckMinLength",(_,$)=>{var g;Y_.init(_,$),(g=_._zod.def).when??(g.when=(U)=>{let D=U.value;return!M6(D)&&D.length!==void 0}),_._zod.onattach.push((U)=>{let D=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>D)U._zod.bag.minimum=$.minimum}),_._zod.check=(U)=>{let D=U.value;if(D.length>=$.minimum)return;let j=sg(D);U.issues.push({origin:j,code:"too_small",minimum:$.minimum,inclusive:!0,input:D,inst:_,continue:!$.abort})}}),v2=Y("$ZodCheckLengthEquals",(_,$)=>{var g;Y_.init(_,$),(g=_._zod.def).when??(g.when=(U)=>{let D=U.value;return!M6(D)&&D.length!==void 0}),_._zod.onattach.push((U)=>{let D=U._zod.bag;D.minimum=$.length,D.maximum=$.length,D.length=$.length}),_._zod.check=(U)=>{let D=U.value,I=D.length;if(I===$.length)return;let j=sg(D),N=I>$.length;U.issues.push({origin:j,...N?{code:"too_big",maximum:$.length}:{code:"too_small",minimum:$.length},inclusive:!0,exact:!0,input:U.value,inst:_,continue:!$.abort})}}),r0=Y("$ZodCheckStringFormat",(_,$)=>{var g,U;if(Y_.init(_,$),_._zod.onattach.push((D)=>{let I=D._zod.bag;if(I.format=$.format,$.pattern)I.patterns??(I.patterns=new Set),I.patterns.add($.pattern)}),$.pattern)(g=_._zod).check??(g.check=(D)=>{if($.pattern.lastIndex=0,$.pattern.test(D.value))return;D.issues.push({origin:"string",code:"invalid_format",format:$.format,input:D.value,...$.pattern?{pattern:$.pattern.toString()}:{},inst:_,continue:!$.abort})});else(U=_._zod).check??(U.check=()=>{})}),f2=Y("$ZodCheckRegex",(_,$)=>{r0.init(_,$),_._zod.check=(g)=>{if($.pattern.lastIndex=0,$.pattern.test(g.value))return;g.issues.push({origin:"string",code:"invalid_format",format:"regex",input:g.value,pattern:$.pattern.toString(),inst:_,continue:!$.abort})}}),w2=Y("$ZodCheckLowerCase",(_,$)=>{$.pattern??($.pattern=K2),r0.init(_,$)}),u2=Y("$ZodCheckUpperCase",(_,$)=>{$.pattern??($.pattern=V2),r0.init(_,$)}),x2=Y("$ZodCheckIncludes",(_,$)=>{Y_.init(_,$);let g=P$($.includes),U=new RegExp(typeof $.position==="number"?`^.{${$.position}}${g}`:g);$.pattern=U,_._zod.onattach.push((D)=>{let I=D._zod.bag;I.patterns??(I.patterns=new Set),I.patterns.add(U)}),_._zod.check=(D)=>{if(D.value.includes($.includes,$.position))return;D.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:$.includes,input:D.value,inst:_,continue:!$.abort})}}),y2=Y("$ZodCheckStartsWith",(_,$)=>{Y_.init(_,$);let g=new RegExp(`^${P$($.prefix)}.*`);$.pattern??($.pattern=g),_._zod.onattach.push((U)=>{let D=U._zod.bag;D.patterns??(D.patterns=new Set),D.patterns.add(g)}),_._zod.check=(U)=>{if(U.value.startsWith($.prefix))return;U.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:$.prefix,input:U.value,inst:_,continue:!$.abort})}}),h2=Y("$ZodCheckEndsWith",(_,$)=>{Y_.init(_,$);let g=new RegExp(`.*${P$($.suffix)}$`);$.pattern??($.pattern=g),_._zod.onattach.push((U)=>{let D=U._zod.bag;D.patterns??(D.patterns=new Set),D.patterns.add(g)}),_._zod.check=(U)=>{if(U.value.endsWith($.suffix))return;U.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:$.suffix,input:U.value,inst:_,continue:!$.abort})}});c2=Y("$ZodCheckProperty",(_,$)=>{Y_.init(_,$),_._zod.check=(g)=>{let U=$.schema._zod.run({value:g.value[$.property],issues:[]},{});if(U instanceof Promise)return U.then((D)=>ZX(D,g,$.property));ZX(U,g,$.property);return}}),n2=Y("$ZodCheckMimeType",(_,$)=>{Y_.init(_,$);let g=new Set($.mime);_._zod.onattach.push((U)=>{U._zod.bag.mime=$.mime}),_._zod.check=(U)=>{if(g.has(U.value.type))return;U.issues.push({code:"invalid_value",values:$.mime,input:U.value.type,inst:_,continue:!$.abort})}}),d2=Y("$ZodCheckOverwrite",(_,$)=>{Y_.init(_,$),_._zod.check=(g)=>{g.value=$.tx(g.value)}})});class uI{constructor(_=[]){if(this.content=[],this.indent=0,this)this.args=_}indented(_){this.indent+=1,_(this),this.indent-=1}write(_){if(typeof _==="function"){_(this,{execution:"sync"}),_(this,{execution:"async"});return}let g=_.split(` +`).filter((I)=>I),U=Math.min(...g.map((I)=>I.length-I.trimStart().length)),D=g.map((I)=>I.slice(U)).map((I)=>" ".repeat(this.indent*2)+I);for(let I of D)this.content.push(I)}compile(){let _=Function,$=this?.args,U=[...(this?.content??[""]).map((D)=>` ${D}`)];return new _(...$,U.join(` +`))}}var m2;var i2=f(()=>{m2={major:4,minor:4,patch:3}});function zO(_){if(_==="")return!0;if(/\s/.test(_))return!1;if(_.length%4!==0)return!1;try{return atob(_),!0}catch{return!1}}function iX(_){if(!CI.test(_))return!1;let $=_.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),g=$.padEnd(Math.ceil($.length/4)*4,"=");return zO(g)}function lX(_,$=null){try{let g=_.split(".");if(g.length!==3)return!1;let[U]=g;if(!U)return!1;let D=JSON.parse(atob(U));if("typ"in D&&D?.typ!=="JWT")return!1;if(!D.alg)return!1;if($&&(!("alg"in D)||D.alg!==$))return!1;return!0}catch{return!1}}function kX(_,$,g){if(_.issues.length)$.issues.push(...s_(g,_.issues));$.value[g]=_.value}function cI(_,$,g,U,D,I){let j=g in U;if(_.issues.length){if(D&&I&&!j)return;$.issues.push(...s_(g,_.issues))}if(!j&&!D){if(!_.issues.length)$.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[g]});return}if(_.value===void 0){if(j)$.value[g]=void 0}else $.value[g]=_.value}function tX(_){let $=Object.keys(_.shape);for(let U of $)if(!_.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${U}": expected a Zod schema`);let g=dE(_.shape);return{..._,keys:$,keySet:new Set($),numKeys:$.length,optionalKeys:new Set(g)}}function oX(_,$,g,U,D,I){let j=[],N=D.keySet,O=D.catchall._zod,A=O.def.type,L=O.optin==="optional",z=O.optout==="optional";for(let W in $){if(W==="__proto__")continue;if(N.has(W))continue;if(A==="never"){j.push(W);continue}let J=O.run({value:$[W],issues:[]},U);if(J instanceof Promise)_.push(J.then((P)=>cI(P,g,W,$,L,z)));else cI(J,g,W,$,L,z)}if(j.length)g.issues.push({code:"unrecognized_keys",keys:j,input:$,inst:I});if(!_.length)return g;return Promise.all(_).then(()=>{return g})}function CX(_,$,g,U){for(let I of _)if(I.issues.length===0)return $.value=I.value,$;let D=_.filter((I)=>!H6(I));if(D.length===1)return $.value=D[0].value,D[0];return $.issues.push({code:"invalid_union",input:$.value,inst:g,errors:_.map((I)=>I.issues.map((j)=>l_(j,U,Z_())))}),$}function rX(_,$,g,U){let D=_.filter((I)=>I.issues.length===0);if(D.length===1)return $.value=D[0].value,$;if(D.length===0)$.issues.push({code:"invalid_union",input:$.value,inst:g,errors:_.map((I)=>I.issues.map((j)=>l_(j,U,Z_())))});else $.issues.push({code:"invalid_union",input:$.value,inst:g,errors:[],inclusive:!1});return $}function l2(_,$){if(_===$)return{valid:!0,data:_};if(_ instanceof Date&&$ instanceof Date&&+_===+$)return{valid:!0,data:_};if(b6(_)&&b6($)){let g=Object.keys($),U=Object.keys(_).filter((I)=>g.indexOf(I)!==-1),D={..._,...$};for(let I of U){let j=l2(_[I],$[I]);if(!j.valid)return{valid:!1,mergeErrorPath:[I,...j.mergeErrorPath]};D[I]=j.data}return{valid:!0,data:D}}if(Array.isArray(_)&&Array.isArray($)){if(_.length!==$.length)return{valid:!1,mergeErrorPath:[]};let g=[];for(let U=0;U<_.length;U++){let D=_[U],I=$[U],j=l2(D,I);if(!j.valid)return{valid:!1,mergeErrorPath:[U,...j.mergeErrorPath]};g.push(j.data)}return{valid:!0,data:g}}return{valid:!1,mergeErrorPath:[]}}function vX(_,$,g){let U=new Map,D;for(let N of $.issues)if(N.code==="unrecognized_keys"){D??(D=N);for(let O of N.keys){if(!U.has(O))U.set(O,{});U.get(O).l=!0}}else _.issues.push(N);for(let N of g.issues)if(N.code==="unrecognized_keys")for(let O of N.keys){if(!U.has(O))U.set(O,{});U.get(O).r=!0}else _.issues.push(N);let I=[...U].filter(([,N])=>N.l&&N.r).map(([N])=>N);if(I.length&&D)_.issues.push({...D,keys:I});if(H6(_))return _;let j=l2($.value,g.value);if(!j.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(j.mergeErrorPath)}`);return _.value=j.data,_}function fX(_,$){for(let g=_.length-1;g>=0;g--)if(_[g]._zod[$]!=="optional")return g+1;return 0}function wX(_,$,g){if(_.issues.length)$.issues.push(...s_(g,_.issues));$.value[g]=_.value}function uX(_,$,g,U,D){for(let I=0;I=D){$.value.length=I;break}$.issues.push(...s_(I,j.issues))}$.value[I]=j.value}for(let I=$.value.length-1;I>=U.length;I--)if(g[I]._zod.optout==="optional"&&$.value[I]===void 0)$.value.length=I;else break;return $}function xX(_,$,g,U,D,I,j){if(_.issues.length)if(eg.has(typeof U))g.issues.push(...s_(U,_.issues));else g.issues.push({code:"invalid_key",origin:"map",input:D,inst:I,issues:_.issues.map((N)=>l_(N,j,Z_()))});if($.issues.length)if(eg.has(typeof U))g.issues.push(...s_(U,$.issues));else g.issues.push({origin:"map",code:"invalid_element",input:D,inst:I,key:U,issues:$.issues.map((N)=>l_(N,j,Z_()))});g.value.set(_.value,$.value)}function yX(_,$){if(_.issues.length)$.issues.push(..._.issues);$.value.add(_.value)}function hX(_,$){if($===void 0&&(_.issues.length||_.fallback))return{issues:[],value:void 0};return _}function cX(_,$){if(_.value===void 0)_.value=$.defaultValue;return _}function nX(_,$){if(!_.issues.length&&_.value===void 0)_.issues.push({code:"invalid_type",expected:"nonoptional",input:_.value,inst:$});return _}function xI(_,$,g){if(_.issues.length)return _.aborted=!0,_;return $._zod.run({value:_.value,issues:_.issues,fallback:_.fallback},g)}function yI(_,$,g){if(_.issues.length)return _.aborted=!0,_;if((g.direction||"forward")==="forward"){let D=$.transform(_.value,_);if(D instanceof Promise)return D.then((I)=>hI(_,I,$.out,g));return hI(_,D,$.out,g)}else{let D=$.reverseTransform(_.value,_);if(D instanceof Promise)return D.then((I)=>hI(_,I,$.in,g));return hI(_,D,$.in,g)}}function hI(_,$,g,U){if(_.issues.length)return _.aborted=!0,_;return g._zod.run({value:$,issues:_.issues},U)}function dX(_){return _.value=Object.freeze(_.value),_}function mX(_,$,g,U){if(!_){let D={code:"custom",input:g,inst:U,path:[...U._zod.def.path??[]],continue:!U._zod.def.abort};if(U._zod.def.params)D.params=U._zod.def.params;$.issues.push(F0(D))}}var l,S4,R_,t2,o2,p2,e2,a2,s2,_O,$O,gO,DO,UO,IO,jO,NO,EO,OO,AO,LO,JO,PO,SO,WO,XO,RO,GO,nI,YO,UD,dI,QO,TO,qO,BO,KO,VO,FO,MO,ZO,bO,pX,HO,ID,kO,CO,rO,mI,vO,fO,wO,uO,xO,yO,hO,iI,cO,nO,dO,mO,iO,lO,tO,oO,lI,jD,pO,eO,aO,sO,_A,$A,gA;var DA=f(()=>{wI();J4();eE();rI();c();i2();c();l=Y("$ZodType",(_,$)=>{var g;_??(_={}),_._zod.def=$,_._zod.bag=_._zod.bag||{},_._zod.version=m2;let U=[..._._zod.def.checks??[]];if(_._zod.traits.has("$ZodCheck"))U.unshift(_);for(let D of U)for(let I of D._zod.onattach)I(_);if(U.length===0)(g=_._zod).deferred??(g.deferred=[]),_._zod.deferred?.push(()=>{_._zod.run=_._zod.parse});else{let D=(j,N,O)=>{let A=H6(j),L;for(let z of N){if(z._zod.def.when){if(lE(j))continue;if(!z._zod.def.when(j))continue}else if(A)continue;let W=j.issues.length,J=z._zod.check(j);if(J instanceof Promise&&O?.async===!1)throw new x$;if(L||J instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await J,j.issues.length===W)return;if(!A)A=H6(j,W)});else{if(j.issues.length===W)continue;if(!A)A=H6(j,W)}}if(L)return L.then(()=>{return j});return j},I=(j,N,O)=>{if(H6(j))return j.aborted=!0,j;let A=D(N,U,O);if(A instanceof Promise){if(O.async===!1)throw new x$;return A.then((L)=>_._zod.parse(L,O))}return _._zod.parse(A,O)};_._zod.run=(j,N)=>{if(N.skipChecks)return _._zod.parse(j,N);if(N.direction==="backward"){let A=_._zod.parse({value:j.value,issues:[]},{...N,skipChecks:!0});if(A instanceof Promise)return A.then((L)=>{return I(L,j,N)});return I(A,j,N)}let O=_._zod.parse(j,N);if(O instanceof Promise){if(N.async===!1)throw new x$;return O.then((A)=>D(A,U,N))}return D(O,U,N)}}$_(_,"~standard",()=>({validate:(D)=>{try{let I=oE(_,D);return I.success?{value:I.data}:{issues:I.error?.issues}}catch(I){return pE(_,D).then((j)=>j.success?{value:j.data}:{issues:j.error?.issues})}},vendor:"zod",version:1}))}),S4=Y("$ZodString",(_,$)=>{l.init(_,$),_._zod.pattern=[..._?._zod.bag?.patterns??[]].pop()??G2(_._zod.bag),_._zod.parse=(g,U)=>{if($.coerce)try{g.value=String(g.value)}catch(D){}if(typeof g.value==="string")return g;return g.issues.push({expected:"string",code:"invalid_type",input:g.value,inst:_}),g}}),R_=Y("$ZodStringFormat",(_,$)=>{r0.init(_,$),S4.init(_,$)}),t2=Y("$ZodGUID",(_,$)=>{$.pattern??($.pattern=I2),R_.init(_,$)}),o2=Y("$ZodUUID",(_,$)=>{if($.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[$.version];if(U===void 0)throw Error(`Invalid UUID version: "${$.version}"`);$.pattern??($.pattern=z4(U))}else $.pattern??($.pattern=z4());R_.init(_,$)}),p2=Y("$ZodEmail",(_,$)=>{$.pattern??($.pattern=j2),R_.init(_,$)}),e2=Y("$ZodURL",(_,$)=>{R_.init(_,$),_._zod.check=(g)=>{try{let U=g.value.trim();if(!$.normalize&&$.protocol?.source===z2.source){if(!/^https?:\/\//i.test(U)){g.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:g.value,inst:_,continue:!$.abort});return}}let D=new URL(U);if($.hostname){if($.hostname.lastIndex=0,!$.hostname.test(D.hostname))g.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$.hostname.source,input:g.value,inst:_,continue:!$.abort})}if($.protocol){if($.protocol.lastIndex=0,!$.protocol.test(D.protocol.endsWith(":")?D.protocol.slice(0,-1):D.protocol))g.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:$.protocol.source,input:g.value,inst:_,continue:!$.abort})}if($.normalize)g.value=D.href;else g.value=U;return}catch(U){g.issues.push({code:"invalid_format",format:"url",input:g.value,inst:_,continue:!$.abort})}}}),a2=Y("$ZodEmoji",(_,$)=>{$.pattern??($.pattern=N2()),R_.init(_,$)}),s2=Y("$ZodNanoID",(_,$)=>{$.pattern??($.pattern=D2),R_.init(_,$)}),_O=Y("$ZodCUID",(_,$)=>{$.pattern??($.pattern=aE),R_.init(_,$)}),$O=Y("$ZodCUID2",(_,$)=>{$.pattern??($.pattern=sE),R_.init(_,$)}),gO=Y("$ZodULID",(_,$)=>{$.pattern??($.pattern=_2),R_.init(_,$)}),DO=Y("$ZodXID",(_,$)=>{$.pattern??($.pattern=$2),R_.init(_,$)}),UO=Y("$ZodKSUID",(_,$)=>{$.pattern??($.pattern=g2),R_.init(_,$)}),IO=Y("$ZodISODateTime",(_,$)=>{$.pattern??($.pattern=R2($)),R_.init(_,$)}),jO=Y("$ZodISODate",(_,$)=>{$.pattern??($.pattern=W2),R_.init(_,$)}),NO=Y("$ZodISOTime",(_,$)=>{$.pattern??($.pattern=X2($)),R_.init(_,$)}),EO=Y("$ZodISODuration",(_,$)=>{$.pattern??($.pattern=U2),R_.init(_,$)}),OO=Y("$ZodIPv4",(_,$)=>{$.pattern??($.pattern=E2),R_.init(_,$),_._zod.bag.format="ipv4"}),AO=Y("$ZodIPv6",(_,$)=>{$.pattern??($.pattern=O2),R_.init(_,$),_._zod.bag.format="ipv6",_._zod.check=(g)=>{try{new URL(`http://[${g.value}]`)}catch{g.issues.push({code:"invalid_format",format:"ipv6",input:g.value,inst:_,continue:!$.abort})}}}),LO=Y("$ZodMAC",(_,$)=>{$.pattern??($.pattern=A2($.delimiter)),R_.init(_,$),_._zod.bag.format="mac"}),JO=Y("$ZodCIDRv4",(_,$)=>{$.pattern??($.pattern=L2),R_.init(_,$)}),PO=Y("$ZodCIDRv6",(_,$)=>{$.pattern??($.pattern=J2),R_.init(_,$),_._zod.check=(g)=>{let U=g.value.split("/");try{if(U.length!==2)throw Error();let[D,I]=U;if(!I)throw Error();let j=Number(I);if(`${j}`!==I)throw Error();if(j<0||j>128)throw Error();new URL(`http://[${D}]`)}catch{g.issues.push({code:"invalid_format",format:"cidrv6",input:g.value,inst:_,continue:!$.abort})}}});SO=Y("$ZodBase64",(_,$)=>{$.pattern??($.pattern=P2),R_.init(_,$),_._zod.bag.contentEncoding="base64",_._zod.check=(g)=>{if(zO(g.value))return;g.issues.push({code:"invalid_format",format:"base64",input:g.value,inst:_,continue:!$.abort})}});WO=Y("$ZodBase64URL",(_,$)=>{$.pattern??($.pattern=CI),R_.init(_,$),_._zod.bag.contentEncoding="base64url",_._zod.check=(g)=>{if(iX(g.value))return;g.issues.push({code:"invalid_format",format:"base64url",input:g.value,inst:_,continue:!$.abort})}}),XO=Y("$ZodE164",(_,$)=>{$.pattern??($.pattern=S2),R_.init(_,$)});RO=Y("$ZodJWT",(_,$)=>{R_.init(_,$),_._zod.check=(g)=>{if(lX(g.value,$.alg))return;g.issues.push({code:"invalid_format",format:"jwt",input:g.value,inst:_,continue:!$.abort})}}),GO=Y("$ZodCustomStringFormat",(_,$)=>{R_.init(_,$),_._zod.check=(g)=>{if($.fn(g.value))return;g.issues.push({code:"invalid_format",format:$.format,input:g.value,inst:_,continue:!$.abort})}}),nI=Y("$ZodNumber",(_,$)=>{l.init(_,$),_._zod.pattern=_._zod.bag.pattern??$D,_._zod.parse=(g,U)=>{if($.coerce)try{g.value=Number(g.value)}catch(j){}let D=g.value;if(typeof D==="number"&&!Number.isNaN(D)&&Number.isFinite(D))return g;let I=typeof D==="number"?Number.isNaN(D)?"NaN":!Number.isFinite(D)?"Infinity":void 0:void 0;return g.issues.push({expected:"number",code:"invalid_type",input:D,inst:_,...I?{received:I}:{}}),g}}),YO=Y("$ZodNumberFormat",(_,$)=>{M2.init(_,$),nI.init(_,$)}),UD=Y("$ZodBoolean",(_,$)=>{l.init(_,$),_._zod.pattern=T2,_._zod.parse=(g,U)=>{if($.coerce)try{g.value=Boolean(g.value)}catch(I){}let D=g.value;if(typeof D==="boolean")return g;return g.issues.push({expected:"boolean",code:"invalid_type",input:D,inst:_}),g}}),dI=Y("$ZodBigInt",(_,$)=>{l.init(_,$),_._zod.pattern=Y2,_._zod.parse=(g,U)=>{if($.coerce)try{g.value=BigInt(g.value)}catch(D){}if(typeof g.value==="bigint")return g;return g.issues.push({expected:"bigint",code:"invalid_type",input:g.value,inst:_}),g}}),QO=Y("$ZodBigIntFormat",(_,$)=>{Z2.init(_,$),dI.init(_,$)}),TO=Y("$ZodSymbol",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value;if(typeof D==="symbol")return g;return g.issues.push({expected:"symbol",code:"invalid_type",input:D,inst:_}),g}}),qO=Y("$ZodUndefined",(_,$)=>{l.init(_,$),_._zod.pattern=B2,_._zod.values=new Set([void 0]),_._zod.parse=(g,U)=>{let D=g.value;if(typeof D>"u")return g;return g.issues.push({expected:"undefined",code:"invalid_type",input:D,inst:_}),g}}),BO=Y("$ZodNull",(_,$)=>{l.init(_,$),_._zod.pattern=q2,_._zod.values=new Set([null]),_._zod.parse=(g,U)=>{let D=g.value;if(D===null)return g;return g.issues.push({expected:"null",code:"invalid_type",input:D,inst:_}),g}}),KO=Y("$ZodAny",(_,$)=>{l.init(_,$),_._zod.parse=(g)=>g}),VO=Y("$ZodUnknown",(_,$)=>{l.init(_,$),_._zod.parse=(g)=>g}),FO=Y("$ZodNever",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{return g.issues.push({expected:"never",code:"invalid_type",input:g.value,inst:_}),g}}),MO=Y("$ZodVoid",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value;if(typeof D>"u")return g;return g.issues.push({expected:"void",code:"invalid_type",input:D,inst:_}),g}}),ZO=Y("$ZodDate",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{if($.coerce)try{g.value=new Date(g.value)}catch(N){}let D=g.value,I=D instanceof Date;if(I&&!Number.isNaN(D.getTime()))return g;return g.issues.push({expected:"date",code:"invalid_type",input:D,...I?{received:"Invalid Date"}:{},inst:_}),g}});bO=Y("$ZodArray",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value;if(!Array.isArray(D))return g.issues.push({expected:"array",code:"invalid_type",input:D,inst:_}),g;g.value=Array(D.length);let I=[];for(let j=0;jkX(A,g,j)));else kX(O,g,j)}if(I.length)return Promise.all(I).then(()=>g);return g}});pX=Y("$ZodObject",(_,$)=>{if(l.init(_,$),!Object.getOwnPropertyDescriptor($,"shape")?.get){let N=$.shape;Object.defineProperty($,"shape",{get:()=>{let O={...N};return Object.defineProperty($,"shape",{value:O}),O}})}let U=V0(()=>tX($));$_(_._zod,"propValues",()=>{let N=$.shape,O={};for(let A in N){let L=N[A]._zod;if(L.values){O[A]??(O[A]=new Set);for(let z of L.values)O[A].add(z)}}return O});let D=P4,I=$.catchall,j;_._zod.parse=(N,O)=>{j??(j=U.value);let A=N.value;if(!D(A))return N.issues.push({expected:"object",code:"invalid_type",input:A,inst:_}),N;N.value={};let L=[],z=j.shape;for(let W of j.keys){let J=z[W],P=J._zod.optin==="optional",S=J._zod.optout==="optional",X=J._zod.run({value:A[W],issues:[]},O);if(X instanceof Promise)L.push(X.then((G)=>cI(G,N,W,A,P,S)));else cI(X,N,W,A,P,S)}if(!I)return L.length?Promise.all(L).then(()=>N):N;return oX(L,A,N,O,U.value,_)}}),HO=Y("$ZodObjectJIT",(_,$)=>{pX.init(_,$);let g=_._zod.parse,U=V0(()=>tX($)),D=(W)=>{let J=new uI(["shape","payload","ctx"]),P=U.value,S=(K)=>{let Q=GI(K);return`shape[${Q}]._zod.run({ value: input[${Q}], issues: [] }, ctx)`};J.write("const input = payload.value;");let X=Object.create(null),G=0;for(let K of P.keys)X[K]=`key_${G++}`;J.write("const newResult = {};");for(let K of P.keys){let Q=X[K],T=GI(K),q=W[K],V=q?._zod?.optin==="optional",Z=q?._zod?.optout==="optional";if(J.write(`const ${Q} = ${S(K)};`),V&&Z)J.write(` + if (${Q}.issues.length) { + if (${T} in input) { + payload.issues = payload.issues.concat(${Q}.issues.map(iss => ({ ...iss, - path: iss.path ? [${g}, ...iss.path] : [${g}] + path: iss.path ? [${T}, ...iss.path] : [${T}] }))); } } - if (${A}.value === undefined) { - if (${g} in input) { - newResult[${g}] = undefined; + if (${Q}.value === undefined) { + if (${T} in input) { + newResult[${T}] = undefined; } } else { - newResult[${g}] = ${A}.value; + newResult[${T}] = ${Q}.value; } - `);else if(!k)B.write(` - const ${A}_present = ${g} in input; - if (${A}.issues.length) { - payload.issues = payload.issues.concat(${A}.issues.map(iss => ({ + `);else if(!V)J.write(` + const ${Q}_present = ${T} in input; + if (${Q}.issues.length) { + payload.issues = payload.issues.concat(${Q}.issues.map(iss => ({ ...iss, - path: iss.path ? [${g}, ...iss.path] : [${g}] + path: iss.path ? [${T}, ...iss.path] : [${T}] }))); } - if (!${A}_present && !${A}.issues.length) { + if (!${Q}_present && !${Q}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, - path: [${g}] + path: [${T}] }); } - if (${A}_present) { - if (${A}.value === undefined) { - newResult[${g}] = undefined; + if (${Q}_present) { + if (${Q}.value === undefined) { + newResult[${T}] = undefined; } else { - newResult[${g}] = ${A}.value; + newResult[${T}] = ${Q}.value; } } - `);else B.write(` - if (${A}.issues.length) { - payload.issues = payload.issues.concat(${A}.issues.map(iss => ({ + `);else J.write(` + if (${Q}.issues.length) { + payload.issues = payload.issues.concat(${Q}.issues.map(iss => ({ ...iss, - path: iss.path ? [${g}, ...iss.path] : [${g}] + path: iss.path ? [${T}, ...iss.path] : [${T}] }))); } - if (${A}.value === undefined) { - if (${g} in input) { - newResult[${g}] = undefined; + if (${Q}.value === undefined) { + if (${T} in input) { + newResult[${T}] = undefined; } } else { - newResult[${g}] = ${A}.value; + newResult[${T}] = ${Q}.value; } - `)}B.write("payload.value = newResult;"),B.write("return payload;");let F=B.compile();return(w,A)=>F(R,w,A)},X,G=v1,Y=!T1.jitless,q=Y&&qq.value,L=_.catchall,N;$._zod.parse=(R,B)=>{N??(N=U.value);let H=R.value;if(!G(H))return R.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),R;if(Y&&q&&B?.async===!1&&B.jitless!==!0){if(!X)X=W(_.shape);if(R=X(R,B),!L)return R;return hR([],H,R,B,N,$)}return J(R,B)}});nU=M("$ZodUnion",($,_)=>{R$.init($,_),Z$($._zod,"optin",()=>_.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),Z$($._zod,"optout",()=>_.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),Z$($._zod,"values",()=>{if(_.options.every((U)=>U._zod.values))return new Set(_.options.flatMap((U)=>Array.from(U._zod.values)));return}),Z$($._zod,"pattern",()=>{if(_.options.every((U)=>U._zod.pattern)){let U=_.options.map((W)=>W._zod.pattern);return new RegExp(`^(${U.map((W)=>SU(W.source)).join("|")})$`)}return});let J=_.options.length===1?_.options[0]._zod.run:null;$._zod.parse=(U,W)=>{if(J)return J(U,W);let X=!1,G=[];for(let Y of _.options){let Q=Y._zod.run({value:U.value,issues:[]},W);if(Q instanceof Promise)G.push(Q),X=!0;else{if(Q.issues.length===0)return Q;G.push(Q)}}if(!X)return ER(G,U,$,W);return Promise.all(G).then((Y)=>{return ER(Y,U,$,W)})}});$z=M("$ZodXor",($,_)=>{nU.init($,_),_.inclusive=!1;let J=_.options.length===1?_.options[0]._zod.run:null;$._zod.parse=(U,W)=>{if(J)return J(U,W);let X=!1,G=[];for(let Y of _.options){let Q=Y._zod.run({value:U.value,issues:[]},W);if(Q instanceof Promise)G.push(Q),X=!0;else G.push(Q)}if(!X)return MR(G,U,$,W);return Promise.all(G).then((Y)=>{return MR(Y,U,$,W)})}}),_z=M("$ZodDiscriminatedUnion",($,_)=>{_.inclusive=!1,nU.init($,_);let J=$._zod.parse;Z$($._zod,"propValues",()=>{let W={};for(let X of _.options){let G=X._zod.propValues;if(!G||Object.keys(G).length===0)throw Error(`Invalid discriminated union option at index "${_.options.indexOf(X)}"`);for(let[Y,Q]of Object.entries(G)){if(!W[Y])W[Y]=new Set;for(let q of Q)W[Y].add(q)}}return W});let U=cJ(()=>{let W=_.options,X=new Map;for(let G of W){let Y=G._zod.propValues?.[_.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${_.options.indexOf(G)}"`);for(let Q of Y){if(X.has(Q))throw Error(`Duplicate discriminator value "${String(Q)}"`);X.set(Q,G)}}return X});$._zod.parse=(W,X)=>{let G=W.value;if(!v1(G))return W.issues.push({code:"invalid_type",expected:"object",input:G,inst:$}),W;let Y=U.value.get(G?.[_.discriminator]);if(Y)return Y._zod.run(W,X);if(_.unionFallback||X.direction==="backward")return J(W,X);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:_.discriminator,options:Array.from(U.value.keys()),input:G,path:[_.discriminator],inst:$}),W}}),Jz=M("$ZodIntersection",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value,X=_.left._zod.run({value:W,issues:[]},U),G=_.right._zod.run({value:W,issues:[]},U);if(X instanceof Promise||G instanceof Promise)return Promise.all([X,G]).then(([Q,q])=>{return AR(J,Q,q)});return AR(J,X,G)}});u8=M("$ZodTuple",($,_)=>{R$.init($,_);let J=_.items;$._zod.parse=(U,W)=>{let X=U.value;if(!Array.isArray(X))return U.issues.push({input:X,inst:$,expected:"tuple",code:"invalid_type"}),U;U.value=[];let G=[],Y=bR(J,"optin"),Q=bR(J,"optout");if(!_.rest){if(X.lengthJ.length)U.issues.push({code:"too_big",maximum:J.length,inclusive:!0,input:X,inst:$,origin:"array"})}let q=Array(J.length);for(let L=0;L{q[L]=R}));else q[L]=N}if(_.rest){let L=J.length-1,N=X.slice(J.length);for(let R of N){L++;let B=_.rest._zod.run({value:R,issues:[]},W);if(B instanceof Promise)G.push(B.then((H)=>wR(H,U,L)));else wR(B,U,L)}}if(G.length)return Promise.all(G).then(()=>gR(q,U,J,X,Q));return gR(q,U,J,X,Q)}});Wz=M("$ZodRecord",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!f0(W))return J.issues.push({expected:"record",code:"invalid_type",input:W,inst:$}),J;let X=[],G=_.keyType._zod.values;if(G){J.value={};let Y=new Set;for(let q of G)if(typeof q==="string"||typeof q==="number"||typeof q==="symbol"){Y.add(typeof q==="number"?q.toString():q);let L=_.keyType._zod.run({value:q,issues:[]},U);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:L.issues.map((B)=>n_(B,U,V_())),input:q,path:[q],inst:$});continue}let N=L.value,R=_.valueType._zod.run({value:W[q],issues:[]},U);if(R instanceof Promise)X.push(R.then((B)=>{if(B.issues.length)J.issues.push(...p_(q,B.issues));J.value[N]=B.value}));else{if(R.issues.length)J.issues.push(...p_(q,R.issues));J.value[N]=R.value}}let Q;for(let q in W)if(!Y.has(q))Q=Q??[],Q.push(q);if(Q&&Q.length>0)J.issues.push({code:"unrecognized_keys",input:W,inst:$,keys:Q})}else{J.value={};for(let Y of Reflect.ownKeys(W)){if(Y==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(W,Y))continue;let Q=_.keyType._zod.run({value:Y,issues:[]},U);if(Q instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof Y==="string"&&mU.test(Y)&&Q.issues.length){let N=_.keyType._zod.run({value:Number(Y),issues:[]},U);if(N instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(N.issues.length===0)Q=N}if(Q.issues.length){if(_.mode==="loose")J.value[Y]=W[Y];else J.issues.push({code:"invalid_key",origin:"record",issues:Q.issues.map((N)=>n_(N,U,V_())),input:Y,path:[Y],inst:$});continue}let L=_.valueType._zod.run({value:W[Y],issues:[]},U);if(L instanceof Promise)X.push(L.then((N)=>{if(N.issues.length)J.issues.push(...p_(Y,N.issues));J.value[Q.value]=N.value}));else{if(L.issues.length)J.issues.push(...p_(Y,L.issues));J.value[Q.value]=L.value}}}if(X.length)return Promise.all(X).then(()=>J);return J}}),Uz=M("$ZodMap",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!(W instanceof Map))return J.issues.push({expected:"map",code:"invalid_type",input:W,inst:$}),J;let X=[];J.value=new Map;for(let[G,Y]of W){let Q=_.keyType._zod.run({value:G,issues:[]},U),q=_.valueType._zod.run({value:Y,issues:[]},U);if(Q instanceof Promise||q instanceof Promise)X.push(Promise.all([Q,q]).then(([L,N])=>{kR(L,N,J,G,W,$,U)}));else kR(Q,q,J,G,W,$,U)}if(X.length)return Promise.all(X).then(()=>J);return J}});Xz=M("$ZodSet",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!(W instanceof Set))return J.issues.push({input:W,inst:$,expected:"set",code:"invalid_type"}),J;let X=[];J.value=new Set;for(let G of W){let Y=_.valueType._zod.run({value:G,issues:[]},U);if(Y instanceof Promise)X.push(Y.then((Q)=>IR(Q,J)));else IR(Y,J)}if(X.length)return Promise.all(X).then(()=>J);return J}});Gz=M("$ZodEnum",($,_)=>{R$.init($,_);let J=TU(_.entries),U=new Set(J);$._zod.values=U,$._zod.pattern=new RegExp(`^(${J.filter((W)=>ZU.has(typeof W)).map((W)=>typeof W==="string"?V6(W):W.toString()).join("|")})$`),$._zod.parse=(W,X)=>{let G=W.value;if(U.has(G))return W;return W.issues.push({code:"invalid_value",values:J,input:G,inst:$}),W}}),Yz=M("$ZodLiteral",($,_)=>{if(R$.init($,_),_.values.length===0)throw Error("Cannot create literal schema with no valid values");let J=new Set(_.values);$._zod.values=J,$._zod.pattern=new RegExp(`^(${_.values.map((U)=>typeof U==="string"?V6(U):U?V6(U.toString()):String(U)).join("|")})$`),$._zod.parse=(U,W)=>{let X=U.value;if(J.has(X))return U;return U.issues.push({code:"invalid_value",values:_.values,input:X,inst:$}),U}}),Qz=M("$ZodFile",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(W instanceof File)return J;return J.issues.push({expected:"file",code:"invalid_type",input:W,inst:$}),J}}),qz=M("$ZodTransform",($,_)=>{R$.init($,_),$._zod.optin="optional",$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new S1($.constructor.name);let W=_.transform(J.value,J);if(U.async)return(W instanceof Promise?W:Promise.resolve(W)).then((G)=>{return J.value=G,J.fallback=!0,J});if(W instanceof Promise)throw new O4;return J.value=W,J.fallback=!0,J}});d8=M("$ZodOptional",($,_)=>{R$.init($,_),$._zod.optin="optional",$._zod.optout="optional",Z$($._zod,"values",()=>{return _.innerType._zod.values?new Set([..._.innerType._zod.values,void 0]):void 0}),Z$($._zod,"pattern",()=>{let J=_.innerType._zod.pattern;return J?new RegExp(`^(${SU(J.source)})?$`):void 0}),$._zod.parse=(J,U)=>{if(_.innerType._zod.optin==="optional"){let W=J.value,X=_.innerType._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>fR(G,W));return fR(X,W)}if(J.value===void 0)return J;return _.innerType._zod.run(J,U)}}),zz=M("$ZodExactOptional",($,_)=>{d8.init($,_),Z$($._zod,"values",()=>_.innerType._zod.values),Z$($._zod,"pattern",()=>_.innerType._zod.pattern),$._zod.parse=(J,U)=>{return _.innerType._zod.run(J,U)}}),jz=M("$ZodNullable",($,_)=>{R$.init($,_),Z$($._zod,"optin",()=>_.innerType._zod.optin),Z$($._zod,"optout",()=>_.innerType._zod.optout),Z$($._zod,"pattern",()=>{let J=_.innerType._zod.pattern;return J?new RegExp(`^(${SU(J.source)}|null)$`):void 0}),Z$($._zod,"values",()=>{return _.innerType._zod.values?new Set([..._.innerType._zod.values,null]):void 0}),$._zod.parse=(J,U)=>{if(J.value===null)return J;return _.innerType._zod.run(J,U)}}),Dz=M("$ZodDefault",($,_)=>{R$.init($,_),$._zod.optin="optional",Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);if(J.value===void 0)return J.value=_.defaultValue,J;let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>CR(X,_));return CR(W,_)}});Oz=M("$ZodPrefault",($,_)=>{R$.init($,_),$._zod.optin="optional",Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);if(J.value===void 0)J.value=_.defaultValue;return _.innerType._zod.run(J,U)}}),Lz=M("$ZodNonOptional",($,_)=>{R$.init($,_),Z$($._zod,"values",()=>{let J=_.innerType._zod.values;return J?new Set([...J].filter((U)=>U!==void 0)):void 0}),$._zod.parse=(J,U)=>{let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>PR(X,$));return PR(W,$)}});Bz=M("$ZodSuccess",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new S1("ZodSuccess");let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>{return J.value=X.issues.length===0,J});return J.value=W.issues.length===0,J}}),Hz=M("$ZodCatch",($,_)=>{R$.init($,_),$._zod.optin="optional",Z$($._zod,"optout",()=>_.innerType._zod.optout),Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>{if(J.value=X.value,X.issues.length)J.value=_.catchValue({...J,error:{issues:X.issues.map((G)=>n_(G,U,V_()))},input:J.value}),J.issues=[],J.fallback=!0;return J});if(J.value=W.value,W.issues.length)J.value=_.catchValue({...J,error:{issues:W.issues.map((X)=>n_(X,U,V_()))},input:J.value}),J.issues=[],J.fallback=!0;return J}}),Nz=M("$ZodNaN",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{if(typeof J.value!=="number"||!Number.isNaN(J.value))return J.issues.push({input:J.value,inst:$,expected:"nan",code:"invalid_type"}),J;return J}}),n8=M("$ZodPipe",($,_)=>{R$.init($,_),Z$($._zod,"values",()=>_.in._zod.values),Z$($._zod,"optin",()=>_.in._zod.optin),Z$($._zod,"optout",()=>_.out._zod.optout),Z$($._zod,"propValues",()=>_.in._zod.propValues),$._zod.parse=(J,U)=>{if(U.direction==="backward"){let X=_.out._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>Z8(G,_.in,U));return Z8(X,_.in,U)}let W=_.in._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>Z8(X,_.out,U));return Z8(W,_.out,U)}});cU=M("$ZodCodec",($,_)=>{R$.init($,_),Z$($._zod,"values",()=>_.in._zod.values),Z$($._zod,"optin",()=>_.in._zod.optin),Z$($._zod,"optout",()=>_.out._zod.optout),Z$($._zod,"propValues",()=>_.in._zod.propValues),$._zod.parse=(J,U)=>{if((U.direction||"forward")==="forward"){let X=_.in._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>v8(G,_,U));return v8(X,_,U)}else{let X=_.out._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>v8(G,_,U));return v8(X,_,U)}}});Vz=M("$ZodPreprocess",($,_)=>{n8.init($,_)}),Rz=M("$ZodReadonly",($,_)=>{R$.init($,_),Z$($._zod,"propValues",()=>_.innerType._zod.propValues),Z$($._zod,"values",()=>_.innerType._zod.values),Z$($._zod,"optin",()=>_.innerType?._zod?.optin),Z$($._zod,"optout",()=>_.innerType?._zod?.optout),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then(TR);return TR(W)}});Kz=M("$ZodTemplateLiteral",($,_)=>{R$.init($,_);let J=[];for(let U of _.parts)if(typeof U==="object"&&U!==null){if(!U._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...U._zod.traits].shift()}`);let W=U._zod.pattern instanceof RegExp?U._zod.pattern.source:U._zod.pattern;if(!W)throw Error(`Invalid template literal part: ${U._zod.traits}`);let X=W.startsWith("^")?1:0,G=W.endsWith("$")?W.length-1:W.length;J.push(W.slice(X,G))}else if(U===null||jq.has(typeof U))J.push(V6(`${U}`));else throw Error(`Invalid template literal part: ${U}`);$._zod.pattern=new RegExp(`^${J.join("")}$`),$._zod.parse=(U,W)=>{if(typeof U.value!=="string")return U.issues.push({input:U.value,inst:$,expected:"string",code:"invalid_type"}),U;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(U.value))return U.issues.push({input:U.value,inst:$,code:"invalid_format",format:_.format??"template_literal",pattern:$._zod.pattern.source}),U;return U}}),Fz=M("$ZodFunction",($,_)=>{return R$.init($,_),$._def=_,$._zod.def=_,$.implement=(J)=>{if(typeof J!=="function")throw Error("implement() must be called with a function");return function(...U){let W=$._def.input?R8($._def.input,U):U,X=Reflect.apply(J,this,W);if($._def.output)return R8($._def.output,X);return X}},$.implementAsync=(J)=>{if(typeof J!=="function")throw Error("implementAsync() must be called with a function");return async function(...U){let W=$._def.input?await K8($._def.input,U):U,X=await Reflect.apply(J,this,W);if($._def.output)return await K8($._def.output,X);return X}},$._zod.parse=(J,U)=>{if(typeof J.value!=="function")return J.issues.push({code:"invalid_type",expected:"function",input:J.value,inst:$}),J;if($._def.output&&$._def.output._zod.def.type==="promise")J.value=$.implementAsync(J.value);else J.value=$.implement(J.value);return J},$.input=(...J)=>{let U=$.constructor;if(Array.isArray(J[0]))return new U({type:"function",input:new u8({type:"tuple",items:J[0],rest:J[1]}),output:$._def.output});return new U({type:"function",input:J[0],output:$._def.output})},$.output=(J)=>{return new $.constructor({type:"function",input:$._def.input,output:J})},$}),Ez=M("$ZodPromise",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{return Promise.resolve(J.value).then((W)=>_.innerType._zod.run({value:W,issues:[]},U))}}),Mz=M("$ZodLazy",($,_)=>{R$.init($,_),Z$($._zod,"innerType",()=>{let J=_;if(!J._cachedInner)J._cachedInner=_.getter();return J._cachedInner}),Z$($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),Z$($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),Z$($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),Z$($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(J,U)=>{return $._zod.innerType._zod.run(J,U)}}),Az=M("$ZodCustom",($,_)=>{X_.init($,_),R$.init($,_),$._zod.parse=(J,U)=>{return J},$._zod.check=(J)=>{let U=J.value,W=_.fn(U);if(W instanceof Promise)return W.then((X)=>SR(X,J,U,$));SR(W,J,U,$);return}})});function wz(){return{localeError:Yx()}}var Yx=()=>{let $={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function _(W){return $[W]??null}let J={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${W.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${Y}`;return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${X}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${I(W.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${W.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${X} ${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${W.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${W.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${X} ${W.minimum.toString()} ${G.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${W.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${W.prefix}"`;if(X.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${X.suffix}"`;if(X.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${X.includes}"`;if(X.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${X.pattern}`;return`${J[X.format]??W.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${W.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${W.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${W.keys.length>1?"\u0629":""}: ${b(W.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${W.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${W.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var xR=x(()=>{e()});function gz(){return{localeError:Qx()}}var Qx=()=>{let $={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function _(W){return $[W]??null}let J={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${W.expected}, daxil olan ${Y}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${X}, daxil olan ${Y}`}case"invalid_value":if(W.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${I(W.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${W.origin??"d\u0259y\u0259r"} ${X}${W.maximum.toString()} ${G.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${W.origin??"d\u0259y\u0259r"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${X.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(X.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${X.suffix}" il\u0259 bitm\u0259lidir`;if(X.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${X.includes}" daxil olmal\u0131d\u0131r`;if(X.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${X.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${J[X.format]??W.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${W.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${W.keys.length>1?"lar":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${W.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var uR=x(()=>{e()});function dR($,_,J,U){let W=Math.abs($),X=W%10,G=W%100;if(G>=11&&G<=19)return U;if(X===1)return _;if(X>=2&&X<=4)return J;return U}function kz(){return{localeError:qx()}}var qx=()=>{let $={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function _(W){return $[W]??null}let J={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},U={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${W.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${Y}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${X}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${I(W.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Y=Number(W.maximum),Q=dR(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${G.verb} ${X}${W.maximum.toString()} ${Q}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Y=Number(W.minimum),Q=dR(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${G.verb} ${X}${W.minimum.toString()} ${Q}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${X.includes}"`;if(X.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${W.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${W.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${W.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var nR=x(()=>{e()});function Iz(){return{localeError:zx()}}var zx=()=>{let $={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${W.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${Y}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${X}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${I(W.values[0])}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${X}${W.minimum.toString()} ${G.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${X.pattern}`;let G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(X.format==="emoji")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="datetime")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="date")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(X.format==="time")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="duration")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${G} ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${W.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${W.keys.length>1?"\u043E\u0432\u0435":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${W.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var cR=x(()=>{e()});function fz(){return{localeError:jx()}}var jx=()=>{let $={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function _(W){return $[W]??null}let J={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${W.expected}, s'ha rebut ${Y}`;return`Tipus inv\xE0lid: s'esperava ${X}, s'ha rebut ${Y}`}case"invalid_value":if(W.values.length===1)return`Valor inv\xE0lid: s'esperava ${I(W.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${b(W.values," o ")}`;case"too_big":{let X=W.inclusive?"com a m\xE0xim":"menys de",G=_(W.origin);if(G)return`Massa gran: s'esperava que ${W.origin??"el valor"} contingu\xE9s ${X} ${W.maximum.toString()} ${G.unit??"elements"}`;return`Massa gran: s'esperava que ${W.origin??"el valor"} fos ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"com a m\xEDnim":"m\xE9s de",G=_(W.origin);if(G)return`Massa petit: s'esperava que ${W.origin} contingu\xE9s ${X} ${W.minimum.toString()} ${G.unit}`;return`Massa petit: s'esperava que ${W.origin} fos ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${X.prefix}"`;if(X.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${X.suffix}"`;if(X.format==="includes")return`Format inv\xE0lid: ha d'incloure "${X.includes}"`;if(X.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${X.pattern}`;return`Format inv\xE0lid per a ${J[X.format]??W.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${W.divisor}`;case"unrecognized_keys":return`Clau${W.keys.length>1?"s":""} no reconeguda${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${W.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${W.origin}`;default:return"Entrada inv\xE0lida"}}};var iR=x(()=>{e()});function Cz(){return{localeError:Dx()}}var Dx=()=>{let $={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function _(W){return $[W]??null}let J={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},U={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${W.expected}, obdr\u017Eeno ${Y}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${X}, obdr\u017Eeno ${Y}`}case"invalid_value":if(W.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${I(W.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${W.origin??"hodnota"} mus\xED m\xEDt ${X}${W.maximum.toString()} ${G.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${W.origin??"hodnota"} mus\xED b\xFDt ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${W.origin??"hodnota"} mus\xED m\xEDt ${X}${W.minimum.toString()} ${G.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${W.origin??"hodnota"} mus\xED b\xFDt ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${X.prefix}"`;if(X.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${X.suffix}"`;if(X.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${X.includes}"`;if(X.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${X.pattern}`;return`Neplatn\xFD form\xE1t ${J[X.format]??W.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${W.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${b(W.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${W.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${W.origin}`;default:return"Neplatn\xFD vstup"}}};var lR=x(()=>{e()});function Pz(){return{localeError:Ox()}}var Ox=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function _(W){return $[W]??null}let J={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ugyldigt input: forventede instanceof ${W.expected}, fik ${Y}`;return`Ugyldigt input: forventede ${X}, fik ${Y}`}case"invalid_value":if(W.values.length===1)return`Ugyldig v\xE6rdi: forventede ${I(W.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`For stor: forventede ${Y??"value"} ${G.verb} ${X} ${W.maximum.toString()} ${G.unit??"elementer"}`;return`For stor: forventede ${Y??"value"} havde ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`For lille: forventede ${Y} ${G.verb} ${X} ${W.minimum.toString()} ${G.unit}`;return`For lille: forventede ${Y} havde ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ugyldig streng: skal starte med "${X.prefix}"`;if(X.format==="ends_with")return`Ugyldig streng: skal ende med "${X.suffix}"`;if(X.format==="includes")return`Ugyldig streng: skal indeholde "${X.includes}"`;if(X.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${X.pattern}`;return`Ugyldig ${J[X.format]??W.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${W.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${W.origin}`;default:return"Ugyldigt input"}}};var rR=x(()=>{e()});function Tz(){return{localeError:Lx()}}var Lx=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function _(W){return $[W]??null}let J={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},U={nan:"NaN",number:"Zahl",array:"Array"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${W.expected}, erhalten ${Y}`;return`Ung\xFCltige Eingabe: erwartet ${X}, erhalten ${Y}`}case"invalid_value":if(W.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${I(W.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Zu gro\xDF: erwartet, dass ${W.origin??"Wert"} ${X}${W.maximum.toString()} ${G.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${W.origin??"Wert"} ${X}${W.maximum.toString()} ist`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Zu klein: erwartet, dass ${W.origin} ${X}${W.minimum.toString()} ${G.unit} hat`;return`Zu klein: erwartet, dass ${W.origin} ${X}${W.minimum.toString()} ist`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ung\xFCltiger String: muss mit "${X.prefix}" beginnen`;if(X.format==="ends_with")return`Ung\xFCltiger String: muss mit "${X.suffix}" enden`;if(X.format==="includes")return`Ung\xFCltiger String: muss "${X.includes}" enthalten`;if(X.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${X.pattern} entsprechen`;return`Ung\xFCltig: ${J[X.format]??W.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${W.divisor} sein`;case"unrecognized_keys":return`${W.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${W.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${W.origin}`;default:return"Ung\xFCltige Eingabe"}}};var pR=x(()=>{e()});function Sz(){return{localeError:Bx()}}var Bx=()=>{let $={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function _(W){return $[W]??null}let J={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(typeof W.expected==="string"&&/^[A-Z]/.test(W.expected))return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${W.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${Y}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${X}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${I(W.values[0])}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${X}${W.maximum.toString()} ${G.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${X}${W.minimum.toString()} ${G.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${X.prefix}"`;if(X.format==="ends_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${X.suffix}"`;if(X.format==="includes")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${X.includes}"`;if(X.format==="regex")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${X.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${J[X.format]??W.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${W.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${W.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${W.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${W.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${W.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var oR=x(()=>{e()});function iU(){return{localeError:Hx()}}var Hx=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function _(W){return $[W]??null}let J={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;return`Invalid input: expected ${X}, received ${Y}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${I(W.values[0])}`;return`Invalid option: expected one of ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${X}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Too small: expected ${W.origin} to have ${X}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Invalid string: must start with "${X.prefix}"`;if(X.format==="ends_with")return`Invalid string: must end with "${X.suffix}"`;if(X.format==="includes")return`Invalid string: must include "${X.includes}"`;if(X.format==="regex")return`Invalid string: must match pattern ${X.pattern}`;return`Invalid ${J[X.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":if(W.options&&Array.isArray(W.options)&&W.options.length>0)return`Invalid discriminator value. Expected ${W.options.map((G)=>`'${G}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};var Zz=x(()=>{e()});function vz(){return{localeError:Nx()}}var Nx=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function _(W){return $[W]??null}let J={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},U={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${W.expected}, ricevi\u011Dis ${Y}`;return`Nevalida enigo: atendi\u011Dis ${X}, ricevi\u011Dis ${Y}`}case"invalid_value":if(W.values.length===1)return`Nevalida enigo: atendi\u011Dis ${I(W.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Tro granda: atendi\u011Dis ke ${W.origin??"valoro"} havu ${X}${W.maximum.toString()} ${G.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${W.origin??"valoro"} havu ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Tro malgranda: atendi\u011Dis ke ${W.origin} havu ${X}${W.minimum.toString()} ${G.unit}`;return`Tro malgranda: atendi\u011Dis ke ${W.origin} estu ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${X.prefix}"`;if(X.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${X.suffix}"`;if(X.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${X.includes}"`;if(X.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${X.pattern}`;return`Nevalida ${J[X.format]??W.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${W.divisor}`;case"unrecognized_keys":return`Nekonata${W.keys.length>1?"j":""} \u015Dlosilo${W.keys.length>1?"j":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${W.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${W.origin}`;default:return"Nevalida enigo"}}};var tR=x(()=>{e()});function yz(){return{localeError:Vx()}}var Vx=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function _(W){return $[W]??null}let J={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${W.expected}, recibido ${Y}`;return`Entrada inv\xE1lida: se esperaba ${X}, recibido ${Y}`}case"invalid_value":if(W.values.length===1)return`Entrada inv\xE1lida: se esperaba ${I(W.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Demasiado grande: se esperaba que ${Y??"valor"} tuviera ${X}${W.maximum.toString()} ${G.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${Y??"valor"} fuera ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Demasiado peque\xF1o: se esperaba que ${Y} tuviera ${X}${W.minimum.toString()} ${G.unit}`;return`Demasiado peque\xF1o: se esperaba que ${Y} fuera ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${X.prefix}"`;if(X.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${X.suffix}"`;if(X.format==="includes")return`Cadena inv\xE1lida: debe incluir "${X.includes}"`;if(X.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${X.pattern}`;return`Inv\xE1lido ${J[X.format]??W.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${W.divisor}`;case"unrecognized_keys":return`Llave${W.keys.length>1?"s":""} desconocida${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${U[W.origin]??W.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${U[W.origin]??W.origin}`;default:return"Entrada inv\xE1lida"}}};var aR=x(()=>{e()});function hz(){return{localeError:Rx()}}var Rx=()=>{let $={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function _(W){return $[W]??null}let J={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${W.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${Y} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${X} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${Y} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(W.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${I(W.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${b(W.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${W.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${W.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} ${G.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${X.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(X.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${X.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(X.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${X.includes}" \u0628\u0627\u0634\u062F`;if(X.format==="regex")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${X.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${J[X.format]??W.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${W.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${W.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${b(W.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${W.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${W.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var sR=x(()=>{e()});function mz(){return{localeError:Kx()}}var Kx=()=>{let $={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function _(W){return $[W]??null}let J={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Virheellinen tyyppi: odotettiin instanceof ${W.expected}, oli ${Y}`;return`Virheellinen tyyppi: odotettiin ${X}, oli ${Y}`}case"invalid_value":if(W.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${I(W.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Liian suuri: ${G.subject} t\xE4ytyy olla ${X}${W.maximum.toString()} ${G.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Liian pieni: ${G.subject} t\xE4ytyy olla ${X}${W.minimum.toString()} ${G.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${X.prefix}"`;if(X.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${X.suffix}"`;if(X.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${X.includes}"`;if(X.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${X.pattern}`;return`Virheellinen ${J[X.format]??W.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${W.divisor} monikerta`;case"unrecognized_keys":return`${W.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${b(W.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};var eR=x(()=>{e()});function xz(){return{localeError:Fx()}}var Fx=()=>{let $={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function _(W){return $[W]??null}let J={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entr\xE9e invalide : instanceof ${W.expected} attendu, ${Y} re\xE7u`;return`Entr\xE9e invalide : ${X} attendu, ${Y} re\xE7u`}case"invalid_value":if(W.values.length===1)return`Entr\xE9e invalide : ${I(W.values[0])} attendu`;return`Option invalide : une valeur parmi ${b(W.values,"|")} attendue`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Trop grand : ${U[W.origin]??"valeur"} doit ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${U[W.origin]??"valeur"} doit \xEAtre ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Trop petit : ${U[W.origin]??"valeur"} doit ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Trop petit : ${U[W.origin]??"valeur"} doit \xEAtre ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${X.prefix}"`;if(X.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${X.suffix}"`;if(X.format==="includes")return`Cha\xEEne invalide : doit inclure "${X.includes}"`;if(X.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${X.pattern}`;return`${J[X.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${W.divisor}`;case"unrecognized_keys":return`Cl\xE9${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${b(W.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${W.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entr\xE9e invalide"}}};var $K=x(()=>{e()});function uz(){return{localeError:Ex()}}var Ex=()=>{let $={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function _(W){return $[W]??null}let J={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entr\xE9e invalide : attendu instanceof ${W.expected}, re\xE7u ${Y}`;return`Entr\xE9e invalide : attendu ${X}, re\xE7u ${Y}`}case"invalid_value":if(W.values.length===1)return`Entr\xE9e invalide : attendu ${I(W.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"\u2264":"<",G=_(W.origin);if(G)return`Trop grand : attendu que ${W.origin??"la valeur"} ait ${X}${W.maximum.toString()} ${G.unit}`;return`Trop grand : attendu que ${W.origin??"la valeur"} soit ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"\u2265":">",G=_(W.origin);if(G)return`Trop petit : attendu que ${W.origin} ait ${X}${W.minimum.toString()} ${G.unit}`;return`Trop petit : attendu que ${W.origin} soit ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${X.prefix}"`;if(X.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${X.suffix}"`;if(X.format==="includes")return`Cha\xEEne invalide : doit inclure "${X.includes}"`;if(X.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${X.pattern}`;return`${J[X.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${W.divisor}`;case"unrecognized_keys":return`Cl\xE9${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${b(W.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${W.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entr\xE9e invalide"}}};var _K=x(()=>{e()});function dz(){return{localeError:Mx()}}var Mx=()=>{let $={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},_={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},J=(q)=>q?$[q]:void 0,U=(q)=>{let L=J(q);if(L)return L.label;return q??$.unknown.label},W=(q)=>`\u05D4${U(q)}`,X=(q)=>{return(J(q)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},G=(q)=>{if(!q)return null;return _[q]??null},Y={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},Q={nan:"NaN"};return(q)=>{switch(q.code){case"invalid_type":{let L=q.expected,N=Q[L??""]??U(L),R=f(q.input),B=Q[R]??$[R]?.label??R;if(/^[A-Z]/.test(q.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${q.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${B}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${N}, \u05D4\u05EA\u05E7\u05D1\u05DC ${B}`}case"invalid_value":{if(q.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${I(q.values[0])}`;let L=q.values.map((B)=>I(B));if(q.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L[0]} \u05D0\u05D5 ${L[1]}`;let N=L[L.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L.slice(0,-1).join(", ")} \u05D0\u05D5 ${N}`}case"too_big":{let L=G(q.origin),N=W(q.origin??"value");if(q.origin==="string")return`${L?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${q.maximum.toString()} ${L?.unit??""} ${q.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(q.origin==="number"){let H=q.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${q.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${q.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${H}`}if(q.origin==="array"||q.origin==="set"){let H=q.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",V=q.inclusive?`${q.maximum} ${L?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${q.maximum} ${L?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${V}`.trim()}let R=q.inclusive?"<=":"<",B=X(q.origin??"value");if(L?.unit)return`${L.longLabel} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.maximum.toString()} ${L.unit}`;return`${L?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.maximum.toString()}`}case"too_small":{let L=G(q.origin),N=W(q.origin??"value");if(q.origin==="string")return`${L?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${q.minimum.toString()} ${L?.unit??""} ${q.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(q.origin==="number"){let H=q.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${q.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${q.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${H}`}if(q.origin==="array"||q.origin==="set"){let H=q.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(q.minimum===1&&q.inclusive){let K=q.origin==="set"?"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3":"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${K}`}let V=q.inclusive?`${q.minimum} ${L?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${q.minimum} ${L?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${V}`.trim()}let R=q.inclusive?">=":">",B=X(q.origin??"value");if(L?.unit)return`${L.shortLabel} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.minimum.toString()} ${L.unit}`;return`${L?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.minimum.toString()}`}case"invalid_format":{let L=q;if(L.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${L.prefix}"`;if(L.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${L.suffix}"`;if(L.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${L.includes}"`;if(L.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${L.pattern}`;let N=Y[L.format],R=N?.label??L.format,H=(N?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${R} \u05DC\u05D0 ${H}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${q.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${q.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${q.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${b(q.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${W(q.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var JK=x(()=>{e()});function nz(){return{localeError:Ax()}}var Ax=()=>{let $={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function _(W){return $[W]??null}let J={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},U={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${W.expected}, a primljeno je ${Y}`;return`Neispravan unos: o\u010Dekuje se ${X}, a primljeno je ${Y}`}case"invalid_value":if(W.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${I(W.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Preveliko: o\u010Dekivano da ${Y??"vrijednost"} ima ${X}${W.maximum.toString()} ${G.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${Y??"vrijednost"} bude ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Premalo: o\u010Dekivano da ${Y} ima ${X}${W.minimum.toString()} ${G.unit}`;return`Premalo: o\u010Dekivano da ${Y} bude ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${X.prefix}"`;if(X.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${X.suffix}"`;if(X.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${X.includes}"`;if(X.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${X.pattern}`;return`Neispravna ${J[X.format]??W.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${W.divisor}`;case"unrecognized_keys":return`Neprepoznat${W.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${b(W.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${U[W.origin]??W.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${U[W.origin]??W.origin}`;default:return"Neispravan unos"}}};var WK=x(()=>{e()});function cz(){return{localeError:bx()}}var bx=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function _(W){return $[W]??null}let J={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},U={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${W.expected}, a kapott \xE9rt\xE9k ${Y}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${X}, a kapott \xE9rt\xE9k ${Y}`}case"invalid_value":if(W.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${I(W.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`T\xFAl nagy: ${W.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${X}${W.maximum.toString()} ${G.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${W.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${W.origin} m\xE9rete t\xFAl kicsi ${X}${W.minimum.toString()} ${G.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${W.origin} t\xFAl kicsi ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\xC9rv\xE9nytelen string: "${X.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(X.format==="ends_with")return`\xC9rv\xE9nytelen string: "${X.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(X.format==="includes")return`\xC9rv\xE9nytelen string: "${X.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(X.format==="regex")return`\xC9rv\xE9nytelen string: ${X.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${J[X.format]??W.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${W.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${W.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${W.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var UK=x(()=>{e()});function XK($,_,J){return Math.abs($)===1?_:J}function eJ($){if(!$)return"";let _=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],J=$[$.length-1];return $+(_.includes(J)?"\u0576":"\u0568")}function iz(){return{localeError:wx()}}var wx=()=>{let $={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function _(W){return $[W]??null}let J={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},U={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${W.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${Y}`;return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${X}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${I(W.values[1])}`;return`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Y=Number(W.maximum),Q=XK(Y,G.unit.one,G.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${X}${W.maximum.toString()} ${Q}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Y=Number(W.minimum),Q=XK(Y,G.unit.one,G.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${X}${W.minimum.toString()} ${Q}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin)} \u056C\u056B\u0576\u056B ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${X.prefix}"-\u0578\u057E`;if(X.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${X.suffix}"-\u0578\u057E`;if(X.format==="includes")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${X.includes}"`;if(X.format==="regex")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${X.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${J[X.format]??W.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${W.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${W.keys.length>1?"\u0576\u0565\u0580":""}. ${b(W.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${eJ(W.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${eJ(W.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var GK=x(()=>{e()});function lz(){return{localeError:gx()}}var gx=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function _(W){return $[W]??null}let J={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input tidak valid: diharapkan instanceof ${W.expected}, diterima ${Y}`;return`Input tidak valid: diharapkan ${X}, diterima ${Y}`}case"invalid_value":if(W.values.length===1)return`Input tidak valid: diharapkan ${I(W.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Terlalu besar: diharapkan ${W.origin??"value"} memiliki ${X}${W.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: diharapkan ${W.origin??"value"} menjadi ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Terlalu kecil: diharapkan ${W.origin} memiliki ${X}${W.minimum.toString()} ${G.unit}`;return`Terlalu kecil: diharapkan ${W.origin} menjadi ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`String tidak valid: harus dimulai dengan "${X.prefix}"`;if(X.format==="ends_with")return`String tidak valid: harus berakhir dengan "${X.suffix}"`;if(X.format==="includes")return`String tidak valid: harus menyertakan "${X.includes}"`;if(X.format==="regex")return`String tidak valid: harus sesuai pola ${X.pattern}`;return`${J[X.format]??W.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${W.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${W.origin}`;default:return"Input tidak valid"}}};var YK=x(()=>{e()});function rz(){return{localeError:kx()}}var kx=()=>{let $={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function _(W){return $[W]??null}let J={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},U={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${Y} \xFEar sem \xE1 a\xF0 vera instanceof ${W.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${Y} \xFEar sem \xE1 a\xF0 vera ${X}`}case"invalid_value":if(W.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${I(W.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin??"gildi"} hafi ${X}${W.maximum.toString()} ${G.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin??"gildi"} s\xE9 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin} hafi ${X}${W.minimum.toString()} ${G.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin} s\xE9 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${X.prefix}"`;if(X.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${X.suffix}"`;if(X.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${X.includes}"`;if(X.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${X.pattern}`;return`Rangt ${J[X.format]??W.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${W.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${W.keys.length>1?"ir lyklar":"ur lykill"}: ${b(W.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${W.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${W.origin}`;default:return"Rangt gildi"}}};var QK=x(()=>{e()});function pz(){return{localeError:Ix()}}var Ix=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function _(W){return $[W]??null}let J={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"numero",array:"vettore"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input non valido: atteso instanceof ${W.expected}, ricevuto ${Y}`;return`Input non valido: atteso ${X}, ricevuto ${Y}`}case"invalid_value":if(W.values.length===1)return`Input non valido: atteso ${I(W.values[0])}`;return`Opzione non valida: atteso uno tra ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Troppo grande: ${W.origin??"valore"} deve avere ${X}${W.maximum.toString()} ${G.unit??"elementi"}`;return`Troppo grande: ${W.origin??"valore"} deve essere ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Troppo piccolo: ${W.origin} deve avere ${X}${W.minimum.toString()} ${G.unit}`;return`Troppo piccolo: ${W.origin} deve essere ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Stringa non valida: deve iniziare con "${X.prefix}"`;if(X.format==="ends_with")return`Stringa non valida: deve terminare con "${X.suffix}"`;if(X.format==="includes")return`Stringa non valida: deve includere "${X.includes}"`;if(X.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${X.pattern}`;return`Input non valido: ${J[X.format]??W.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${W.divisor}`;case"unrecognized_keys":return`Chiav${W.keys.length>1?"i":"e"} non riconosciut${W.keys.length>1?"e":"a"}: ${b(W.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${W.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${W.origin}`;default:return"Input non valido"}}};var qK=x(()=>{e()});function oz(){return{localeError:fx()}}var fx=()=>{let $={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function _(W){return $[W]??null}let J={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},U={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${W.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${Y}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${X}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${Y}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(W.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${I(W.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${b(W.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let X=W.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",G=_(W.origin);if(G)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${W.origin??"\u5024"}\u306F${W.maximum.toString()}${G.unit??"\u8981\u7D20"}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${W.origin??"\u5024"}\u306F${W.maximum.toString()}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let X=W.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",G=_(W.origin);if(G)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${W.origin}\u306F${W.minimum.toString()}${G.unit}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${W.origin}\u306F${W.minimum.toString()}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${X.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${J[X.format]??W.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${W.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${W.keys.length>1?"\u7FA4":""}: ${b(W.keys,"\u3001")}`;case"invalid_key":return`${W.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${W.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var zK=x(()=>{e()});function tz(){return{localeError:Cx()}}var Cx=()=>{let $={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function _(W){return $[W]??null}let J={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},U={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${W.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${Y}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${X}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${I(W.values[0])}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${b(W.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin} \u10D8\u10E7\u10DD\u10E1 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${X.prefix}"-\u10D8\u10D7`;if(X.format==="ends_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${X.suffix}"-\u10D8\u10D7`;if(X.format==="includes")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${X.includes}"-\u10E1`;if(X.format==="regex")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${X.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${W.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${W.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${W.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${W.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var jK=x(()=>{e()});function lU(){return{localeError:Px()}}var Px=()=>{let $={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function _(W){return $[W]??null}let J={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},U={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${W.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${Y}`;return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${X} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${I(W.values[0])}`;return`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${X} ${W.maximum.toString()} ${G.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin} ${X} ${W.minimum.toString()} ${G.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin} ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${X.prefix}"`;if(X.format==="ends_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${X.suffix}"`;if(X.format==="includes")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${X.includes}"`;if(X.format==="regex")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${X.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${W.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${b(W.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${W.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${W.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};var az=x(()=>{e()});function sz(){return lU()}var DK=x(()=>{az()});function ez(){return{localeError:Tx()}}var Tx=()=>{let $={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function _(W){return $[W]??null}let J={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${W.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${Y}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${X}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${Y}\uC785\uB2C8\uB2E4`}case"invalid_value":if(W.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${I(W.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${b(W.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let X=W.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",G=X==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",Y=_(W.origin),Q=Y?.unit??"\uC694\uC18C";if(Y)return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${W.maximum.toString()}${Q} ${X}${G}`;return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${W.maximum.toString()} ${X}${G}`}case"too_small":{let X=W.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",G=X==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",Y=_(W.origin),Q=Y?.unit??"\uC694\uC18C";if(Y)return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${W.minimum.toString()}${Q} ${X}${G}`;return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${W.minimum.toString()} ${X}${G}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${X.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${J[X.format]??W.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${W.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${b(W.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${W.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${W.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var OK=x(()=>{e()});function LK($){let _=Math.abs($),J=_%10,U=_%100;if(U>=11&&U<=19||J===0)return"many";if(J===1)return"one";return"few"}function $j(){return{localeError:Sx()}}var rU=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)},Sx=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function _(W,X,G,Y){let Q=$[W]??null;if(Q===null)return Q;return{unit:Q.unit[X],verb:Q.verb[Y][G?"inclusive":"notInclusive"]}}let J={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},U={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Gautas tipas ${Y}, o tik\u0117tasi - instanceof ${W.expected}`;return`Gautas tipas ${Y}, o tik\u0117tasi - ${X}`}case"invalid_value":if(W.values.length===1)return`Privalo b\u016Bti ${I(W.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${b(W.values,"|")} pasirinkim\u0173`;case"too_big":{let X=U[W.origin]??W.origin,G=_(W.origin,LK(Number(W.maximum)),W.inclusive??!1,"smaller");if(G?.verb)return`${rU(X??W.origin??"reik\u0161m\u0117")} ${G.verb} ${W.maximum.toString()} ${G.unit??"element\u0173"}`;let Y=W.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${rU(X??W.origin??"reik\u0161m\u0117")} turi b\u016Bti ${Y} ${W.maximum.toString()} ${G?.unit}`}case"too_small":{let X=U[W.origin]??W.origin,G=_(W.origin,LK(Number(W.minimum)),W.inclusive??!1,"bigger");if(G?.verb)return`${rU(X??W.origin??"reik\u0161m\u0117")} ${G.verb} ${W.minimum.toString()} ${G.unit??"element\u0173"}`;let Y=W.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${rU(X??W.origin??"reik\u0161m\u0117")} turi b\u016Bti ${Y} ${W.minimum.toString()} ${G?.unit}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${X.prefix}"`;if(X.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${X.suffix}"`;if(X.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${X.includes}"`;if(X.format==="regex")return`Eilut\u0117 privalo atitikti ${X.pattern}`;return`Neteisingas ${J[X.format]??W.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${W.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${W.keys.length>1?"i":"as"} rakt${W.keys.length>1?"ai":"as"}: ${b(W.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let X=U[W.origin]??W.origin;return`${rU(X??W.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var BK=x(()=>{e()});function _j(){return{localeError:Zx()}}var Zx=()=>{let $={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function _(W){return $[W]??null}let J={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},U={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${W.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${Y}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${X}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${Y}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${I(W.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin} \u0434\u0430 \u0438\u043C\u0430 ${X}${W.minimum.toString()} ${G.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${X.pattern}`;return`Invalid ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${W.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${W.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var HK=x(()=>{e()});function Jj(){return{localeError:vx()}}var vx=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function _(W){return $[W]??null}let J={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"nombor"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input tidak sah: dijangka instanceof ${W.expected}, diterima ${Y}`;return`Input tidak sah: dijangka ${X}, diterima ${Y}`}case"invalid_value":if(W.values.length===1)return`Input tidak sah: dijangka ${I(W.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Terlalu besar: dijangka ${W.origin??"nilai"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: dijangka ${W.origin??"nilai"} adalah ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Terlalu kecil: dijangka ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Terlalu kecil: dijangka ${W.origin} adalah ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`String tidak sah: mesti bermula dengan "${X.prefix}"`;if(X.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${X.suffix}"`;if(X.format==="includes")return`String tidak sah: mesti mengandungi "${X.includes}"`;if(X.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${X.pattern}`;return`${J[X.format]??W.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${b(W.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${W.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${W.origin}`;default:return"Input tidak sah"}}};var NK=x(()=>{e()});function Wj(){return{localeError:yx()}}var yx=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function _(W){return $[W]??null}let J={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},U={nan:"NaN",number:"getal"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ongeldige invoer: verwacht instanceof ${W.expected}, ontving ${Y}`;return`Ongeldige invoer: verwacht ${X}, ontving ${Y}`}case"invalid_value":if(W.values.length===1)return`Ongeldige invoer: verwacht ${I(W.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=W.origin==="date"?"laat":W.origin==="string"?"lang":"groot";if(G)return`Te ${Y}: verwacht dat ${W.origin??"waarde"} ${X}${W.maximum.toString()} ${G.unit??"elementen"} ${G.verb}`;return`Te ${Y}: verwacht dat ${W.origin??"waarde"} ${X}${W.maximum.toString()} is`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=W.origin==="date"?"vroeg":W.origin==="string"?"kort":"klein";if(G)return`Te ${Y}: verwacht dat ${W.origin} ${X}${W.minimum.toString()} ${G.unit} ${G.verb}`;return`Te ${Y}: verwacht dat ${W.origin} ${X}${W.minimum.toString()} is`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ongeldige tekst: moet met "${X.prefix}" beginnen`;if(X.format==="ends_with")return`Ongeldige tekst: moet op "${X.suffix}" eindigen`;if(X.format==="includes")return`Ongeldige tekst: moet "${X.includes}" bevatten`;if(X.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${X.pattern}`;return`Ongeldig: ${J[X.format]??W.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${W.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${W.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${W.origin}`;default:return"Ongeldige invoer"}}};var VK=x(()=>{e()});function Uj(){return{localeError:hx()}}var hx=()=>{let $={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function _(W){return $[W]??null}let J={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"tall",array:"liste"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ugyldig input: forventet instanceof ${W.expected}, fikk ${Y}`;return`Ugyldig input: forventet ${X}, fikk ${Y}`}case"invalid_value":if(W.values.length===1)return`Ugyldig verdi: forventet ${I(W.values[0])}`;return`Ugyldig valg: forventet en av ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`For stor(t): forventet ${W.origin??"value"} til \xE5 ha ${X}${W.maximum.toString()} ${G.unit??"elementer"}`;return`For stor(t): forventet ${W.origin??"value"} til \xE5 ha ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`For lite(n): forventet ${W.origin} til \xE5 ha ${X}${W.minimum.toString()} ${G.unit}`;return`For lite(n): forventet ${W.origin} til \xE5 ha ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${X.prefix}"`;if(X.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${X.suffix}"`;if(X.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${X.includes}"`;if(X.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${X.pattern}`;return`Ugyldig ${J[X.format]??W.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${W.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${W.origin}`;default:return"Ugyldig input"}}};var RK=x(()=>{e()});function Xj(){return{localeError:mx()}}var mx=()=>{let $={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function _(W){return $[W]??null}let J={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},U={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`F\xE2sit giren: umulan instanceof ${W.expected}, al\u0131nan ${Y}`;return`F\xE2sit giren: umulan ${X}, al\u0131nan ${Y}`}case"invalid_value":if(W.values.length===1)return`F\xE2sit giren: umulan ${I(W.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Fazla b\xFCy\xFCk: ${W.origin??"value"}, ${X}${W.maximum.toString()} ${G.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${W.origin??"value"}, ${X}${W.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Fazla k\xFC\xE7\xFCk: ${W.origin}, ${X}${W.minimum.toString()} ${G.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${W.origin}, ${X}${W.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`F\xE2sit metin: "${X.prefix}" ile ba\u015Flamal\u0131.`;if(X.format==="ends_with")return`F\xE2sit metin: "${X.suffix}" ile bitmeli.`;if(X.format==="includes")return`F\xE2sit metin: "${X.includes}" ihtiv\xE2 etmeli.`;if(X.format==="regex")return`F\xE2sit metin: ${X.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${J[X.format]??W.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${W.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${W.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var KK=x(()=>{e()});function Gj(){return{localeError:xx()}}var xx=()=>{let $={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function _(W){return $[W]??null}let J={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${W.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${Y} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${X} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${Y} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(W.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${I(W.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${b(W.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${W.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${W.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} \u0648\u064A`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} ${G.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} \u0648\u064A`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${X.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(X.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${X.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(X.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${X.includes}" \u0648\u0644\u0631\u064A`;if(X.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${X.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${J[X.format]??W.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${W.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${W.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${W.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${W.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var FK=x(()=>{e()});function Yj(){return{localeError:ux()}}var ux=()=>{let $={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function _(W){return $[W]??null}let J={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},U={nan:"NaN",number:"liczba",array:"tablica"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${W.expected}, otrzymano ${Y}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${X}, otrzymano ${Y}`}case"invalid_value":if(W.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${I(W.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${X}${W.maximum.toString()} ${G.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${X}${W.minimum.toString()} ${G.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${X.prefix}"`;if(X.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${X.suffix}"`;if(X.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${X.includes}"`;if(X.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${X.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${J[X.format]??W.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${W.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${W.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${W.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var EK=x(()=>{e()});function Qj(){return{localeError:dx()}}var dx=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function _(W){return $[W]??null}let J={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Tipo inv\xE1lido: esperado instanceof ${W.expected}, recebido ${Y}`;return`Tipo inv\xE1lido: esperado ${X}, recebido ${Y}`}case"invalid_value":if(W.values.length===1)return`Entrada inv\xE1lida: esperado ${I(W.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Muito grande: esperado que ${W.origin??"valor"} tivesse ${X}${W.maximum.toString()} ${G.unit??"elementos"}`;return`Muito grande: esperado que ${W.origin??"valor"} fosse ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Muito pequeno: esperado que ${W.origin} tivesse ${X}${W.minimum.toString()} ${G.unit}`;return`Muito pequeno: esperado que ${W.origin} fosse ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${X.prefix}"`;if(X.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${X.suffix}"`;if(X.format==="includes")return`Texto inv\xE1lido: deve incluir "${X.includes}"`;if(X.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${X.pattern}`;return`${J[X.format]??W.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${W.divisor}`;case"unrecognized_keys":return`Chave${W.keys.length>1?"s":""} desconhecida${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${W.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${W.origin}`;default:return"Campo inv\xE1lido"}}};var MK=x(()=>{e()});function qj(){return{localeError:nx()}}var nx=()=>{let $={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function _(W){return $[W]??null}let J={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},U={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;return`Intrare invalid\u0103: a\u0219teptat ${X}, primit ${Y}`}case"invalid_value":if(W.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${I(W.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Prea mare: a\u0219teptat ca ${W.origin??"valoarea"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${W.origin??"valoarea"} s\u0103 fie ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Prea mic: a\u0219teptat ca ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Prea mic: a\u0219teptat ca ${W.origin} s\u0103 fie ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${X.prefix}"`;if(X.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${X.suffix}"`;if(X.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${X.includes}"`;if(X.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${X.pattern}`;return`Format invalid: ${J[X.format]??W.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${W.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${b(W.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${W.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${W.origin}`;default:return"Intrare invalid\u0103"}}};var AK=x(()=>{e()});function bK($,_,J,U){let W=Math.abs($),X=W%10,G=W%100;if(G>=11&&G<=19)return U;if(X===1)return _;if(X>=2&&X<=4)return J;return U}function zj(){return{localeError:cx()}}var cx=()=>{let $={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${W.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${Y}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${X}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${I(W.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Y=Number(W.maximum),Q=bK(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${X}${W.maximum.toString()} ${Q}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Y=Number(W.minimum),Q=bK(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${X}${W.minimum.toString()} ${Q}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin} \u0431\u0443\u0434\u0435\u0442 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${W.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${W.keys.length>1?"\u0438":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${W.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};var wK=x(()=>{e()});function jj(){return{localeError:ix()}}var ix=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function _(W){return $[W]??null}let J={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},U={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${W.expected}, prejeto ${Y}`;return`Neveljaven vnos: pri\u010Dakovano ${X}, prejeto ${Y}`}case"invalid_value":if(W.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${I(W.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Preveliko: pri\u010Dakovano, da bo ${W.origin??"vrednost"} imelo ${X}${W.maximum.toString()} ${G.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${W.origin??"vrednost"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Premajhno: pri\u010Dakovano, da bo ${W.origin} imelo ${X}${W.minimum.toString()} ${G.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${X.prefix}"`;if(X.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${X.suffix}"`;if(X.format==="includes")return`Neveljaven niz: mora vsebovati "${X.includes}"`;if(X.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${X.pattern}`;return`Neveljaven ${J[X.format]??W.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${W.divisor}`;case"unrecognized_keys":return`Neprepoznan${W.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${b(W.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${W.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${W.origin}`;default:return"Neveljaven vnos"}}};var gK=x(()=>{e()});function Dj(){return{localeError:lx()}}var lx=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function _(W){return $[W]??null}let J={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},U={nan:"NaN",number:"antal",array:"lista"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${W.expected}, fick ${Y}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${X}, fick ${Y}`}case"invalid_value":if(W.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${I(W.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.maximum.toString()} ${G.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${W.origin??"v\xE4rdet"} att ha ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.minimum.toString()} ${G.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${X.prefix}"`;if(X.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${X.suffix}"`;if(X.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${X.includes}"`;if(X.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${X.pattern}"`;return`Ogiltig(t) ${J[X.format]??W.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${W.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${W.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var kK=x(()=>{e()});function Oj(){return{localeError:rx()}}var rx=()=>{let $={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function _(W){return $[W]??null}let J={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${W.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Y}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${X}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${I(W.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${b(W.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${X}${W.maximum.toString()} ${G.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${X}${W.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin} ${X}${W.minimum.toString()} ${G.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin} ${X}${W.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${X.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${W.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${W.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${W.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};var IK=x(()=>{e()});function Lj(){return{localeError:px()}}var px=()=>{let $={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function _(W){return $[W]??null}let J={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},U={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${W.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${Y}`;return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${X} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${I(W.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",G=_(W.origin);if(G)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.maximum.toString()} ${G.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",G=_(W.origin);if(G)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.minimum.toString()} ${G.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${X.prefix}"`;if(X.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${X.suffix}"`;if(X.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${X.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(X.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${X.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${W.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${b(W.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${W.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${W.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var fK=x(()=>{e()});function Bj(){return{localeError:ox()}}var ox=()=>{let $={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function _(W){return $[W]??null}let J={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${W.expected}, al\u0131nan ${Y}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${X}, al\u0131nan ${Y}`}case"invalid_value":if(W.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${I(W.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\xC7ok b\xFCy\xFCk: beklenen ${W.origin??"de\u011Fer"} ${X}${W.maximum.toString()} ${G.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${W.origin??"de\u011Fer"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ge\xE7ersiz metin: "${X.prefix}" ile ba\u015Flamal\u0131`;if(X.format==="ends_with")return`Ge\xE7ersiz metin: "${X.suffix}" ile bitmeli`;if(X.format==="includes")return`Ge\xE7ersiz metin: "${X.includes}" i\xE7ermeli`;if(X.format==="regex")return`Ge\xE7ersiz metin: ${X.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${J[X.format]??W.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${W.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${W.keys.length>1?"lar":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${W.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var CK=x(()=>{e()});function pU(){return{localeError:tx()}}var tx=()=>{let $={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${W.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${Y}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${X}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${I(W.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin} \u0431\u0443\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${W.keys.length>1?"\u0456":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${W.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};var Hj=x(()=>{e()});function Nj(){return pU()}var PK=x(()=>{Hj()});function Vj(){return{localeError:ax()}}var ax=()=>{let $={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function _(W){return $[W]??null}let J={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},U={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${W.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${Y} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${X} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${Y} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(W.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${I(W.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${b(W.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${W.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${W.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${X}${W.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${W.origin} \u06A9\u06D2 ${X}${W.minimum.toString()} ${G.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${W.origin} \u06A9\u0627 ${X}${W.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${X.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${W.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${W.keys.length>1?"\u0632":""}: ${b(W.keys,"\u060C ")}`;case"invalid_key":return`${W.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${W.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var TK=x(()=>{e()});function Rj(){return{localeError:sx()}}var sx=()=>{let $={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function _(W){return $[W]??null}let J={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},U={nan:"NaN",number:"raqam",array:"massiv"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${W.expected}, qabul qilingan ${Y}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${X}, qabul qilingan ${Y}`}case"invalid_value":if(W.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${I(W.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Juda katta: kutilgan ${W.origin??"qiymat"} ${X}${W.maximum.toString()} ${G.unit} ${G.verb}`;return`Juda katta: kutilgan ${W.origin??"qiymat"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Juda kichik: kutilgan ${W.origin} ${X}${W.minimum.toString()} ${G.unit} ${G.verb}`;return`Juda kichik: kutilgan ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${X.prefix}" bilan boshlanishi kerak`;if(X.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${X.suffix}" bilan tugashi kerak`;if(X.format==="includes")return`Noto\u2018g\u2018ri satr: "${X.includes}" ni o\u2018z ichiga olishi kerak`;if(X.format==="regex")return`Noto\u2018g\u2018ri satr: ${X.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${J[X.format]??W.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${W.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${W.keys.length>1?"lar":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${W.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var SK=x(()=>{e()});function Kj(){return{localeError:ex()}}var ex=()=>{let $={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function _(W){return $[W]??null}let J={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},U={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${W.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${Y}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${X}, nh\u1EADn \u0111\u01B0\u1EE3c ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${I(W.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${W.origin??"gi\xE1 tr\u1ECB"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${W.origin??"gi\xE1 tr\u1ECB"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${X.prefix}"`;if(X.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${X.suffix}"`;if(X.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${X.includes}"`;if(X.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${X.pattern}`;return`${J[X.format]??W.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${W.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${b(W.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${W.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${W.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var ZK=x(()=>{e()});function Fj(){return{localeError:$u()}}var $u=()=>{let $={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function _(W){return $[W]??null}let J={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},U={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${W.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${Y}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${X}\uFF0C\u5B9E\u9645\u63A5\u6536 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${I(W.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${W.origin??"\u503C"} ${X}${W.maximum.toString()} ${G.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${W.origin??"\u503C"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${X.prefix}" \u5F00\u5934`;if(X.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${X.suffix}" \u7ED3\u5C3E`;if(X.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${X.includes}"`;if(X.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${X.pattern}`;return`\u65E0\u6548${J[X.format]??W.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${W.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${W.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var vK=x(()=>{e()});function Ej(){return{localeError:_u()}}var _u=()=>{let $={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function _(W){return $[W]??null}let J={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${W.expected}\uFF0C\u4F46\u6536\u5230 ${Y}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${X}\uFF0C\u4F46\u6536\u5230 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${I(W.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${W.origin??"\u503C"} \u61C9\u70BA ${X}${W.maximum.toString()} ${G.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${W.origin??"\u503C"} \u61C9\u70BA ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${W.origin} \u61C9\u70BA ${X}${W.minimum.toString()} ${G.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${W.origin} \u61C9\u70BA ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${X.prefix}" \u958B\u982D`;if(X.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${X.suffix}" \u7D50\u5C3E`;if(X.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${X.includes}"`;if(X.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${X.pattern}`;return`\u7121\u6548\u7684 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${W.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${W.keys.length>1?"\u5011":""}\uFF1A${b(W.keys,"\u3001")}`;case"invalid_key":return`${W.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${W.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var yK=x(()=>{e()});function Mj(){return{localeError:Ju()}}var Ju=()=>{let $={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function _(W){return $[W]??null}let J={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},U={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${W.expected}, \xE0m\u1ECD\u0300 a r\xED ${Y}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${X}, \xE0m\u1ECD\u0300 a r\xED ${Y}`}case"invalid_value":if(W.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${I(W.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${W.origin??"iye"} ${G.verb} ${X}${W.maximum} ${G.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${X}${W.maximum}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${W.origin} ${G.verb} ${X}${W.minimum} ${G.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${X}${W.minimum}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${X.prefix}"`;if(X.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${X.suffix}"`;if(X.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${X.includes}"`;if(X.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${X.pattern}`;return`A\u1E63\xEC\u1E63e: ${J[X.format]??W.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${W.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${b(W.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${W.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${W.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var hK=x(()=>{e()});var $W={};e6($W,{zhTW:()=>Ej,zhCN:()=>Fj,yo:()=>Mj,vi:()=>Kj,uz:()=>Rj,ur:()=>Vj,uk:()=>pU,ua:()=>Nj,tr:()=>Bj,th:()=>Lj,ta:()=>Oj,sv:()=>Dj,sl:()=>jj,ru:()=>zj,ro:()=>qj,pt:()=>Qj,ps:()=>Gj,pl:()=>Yj,ota:()=>Xj,no:()=>Uj,nl:()=>Wj,ms:()=>Jj,mk:()=>_j,lt:()=>$j,ko:()=>ez,km:()=>lU,kh:()=>sz,ka:()=>tz,ja:()=>oz,it:()=>pz,is:()=>rz,id:()=>lz,hy:()=>iz,hu:()=>cz,hr:()=>nz,he:()=>dz,frCA:()=>uz,fr:()=>xz,fi:()=>mz,fa:()=>hz,es:()=>yz,eo:()=>vz,en:()=>iU,el:()=>Sz,de:()=>Tz,da:()=>Pz,cs:()=>Cz,ca:()=>fz,bg:()=>Iz,be:()=>kz,az:()=>gz,ar:()=>wz});var Aj=x(()=>{xR();uR();nR();cR();iR();lR();rR();pR();oR();Zz();tR();aR();sR();eR();$K();_K();JK();WK();UK();GK();YK();QK();qK();zK();jK();DK();az();OK();BK();HK();NK();VK();RK();KK();FK();EK();MK();AK();wK();gK();kK();IK();fK();CK();PK();Hj();TK();SK();ZK();vK();yK();hK()});class bj{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,..._){let J=_[0];if(this._map.set($,J),J&&typeof J==="object"&&"id"in J)this._idmap.set(J.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let _=this._map.get($);if(_&&typeof _==="object"&&"id"in _)this._idmap.delete(_.id);return this._map.delete($),this}get($){let _=$._zod.parent;if(_){let J={...this.get(_)??{}};delete J.id;let U={...J,...this._map.get($)};return Object.keys(U).length?U:void 0}return this._map.get($)}has($){return this._map.has($)}}function oU(){return new bj}var mK,c8,i8,g_;var tU=x(()=>{c8=Symbol("ZodOutput"),i8=Symbol("ZodInput");(mK=globalThis).__zod_globalRegistry??(mK.__zod_globalRegistry=oU());g_=globalThis.__zod_globalRegistry});function wj($,_){return new $({type:"string",...y(_)})}function gj($,_){return new $({type:"string",coerce:!0,...y(_)})}function l8($,_){return new $({type:"string",format:"email",check:"string_format",abort:!1,...y(_)})}function aU($,_){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...y(_)})}function r8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...y(_)})}function p8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...y(_)})}function o8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...y(_)})}function t8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...y(_)})}function sU($,_){return new $({type:"string",format:"url",check:"string_format",abort:!1,...y(_)})}function a8($,_){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...y(_)})}function s8($,_){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...y(_)})}function e8($,_){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...y(_)})}function $5($,_){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...y(_)})}function _5($,_){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...y(_)})}function J5($,_){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...y(_)})}function W5($,_){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...y(_)})}function U5($,_){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...y(_)})}function X5($,_){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...y(_)})}function kj($,_){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...y(_)})}function G5($,_){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...y(_)})}function Y5($,_){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...y(_)})}function Q5($,_){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...y(_)})}function q5($,_){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...y(_)})}function z5($,_){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...y(_)})}function j5($,_){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...y(_)})}function Ij($,_){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...y(_)})}function fj($,_){return new $({type:"string",format:"date",check:"string_format",...y(_)})}function Cj($,_){return new $({type:"string",format:"time",check:"string_format",precision:null,...y(_)})}function Pj($,_){return new $({type:"string",format:"duration",check:"string_format",...y(_)})}function Tj($,_){return new $({type:"number",checks:[],...y(_)})}function Sj($,_){return new $({type:"number",coerce:!0,checks:[],...y(_)})}function Zj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...y(_)})}function vj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...y(_)})}function yj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...y(_)})}function hj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...y(_)})}function mj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...y(_)})}function xj($,_){return new $({type:"boolean",...y(_)})}function uj($,_){return new $({type:"boolean",coerce:!0,...y(_)})}function dj($,_){return new $({type:"bigint",...y(_)})}function nj($,_){return new $({type:"bigint",coerce:!0,...y(_)})}function cj($,_){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...y(_)})}function ij($,_){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...y(_)})}function lj($,_){return new $({type:"symbol",...y(_)})}function rj($,_){return new $({type:"undefined",...y(_)})}function pj($,_){return new $({type:"null",...y(_)})}function oj($){return new $({type:"any"})}function tj($){return new $({type:"unknown"})}function aj($,_){return new $({type:"never",...y(_)})}function sj($,_){return new $({type:"void",...y(_)})}function ej($,_){return new $({type:"date",...y(_)})}function $D($,_){return new $({type:"date",coerce:!0,...y(_)})}function _D($,_){return new $({type:"nan",...y(_)})}function m6($,_){return new C8({check:"less_than",...y(_),value:$,inclusive:!1})}function a_($,_){return new C8({check:"less_than",...y(_),value:$,inclusive:!0})}function x6($,_){return new P8({check:"greater_than",...y(_),value:$,inclusive:!1})}function S_($,_){return new P8({check:"greater_than",...y(_),value:$,inclusive:!0})}function eU($){return x6(0,$)}function $X($){return m6(0,$)}function _X($){return a_(0,$)}function JX($){return S_(0,$)}function l4($,_){return new oq({check:"multiple_of",...y(_),value:$})}function r4($,_){return new sq({check:"max_size",...y(_),maximum:$})}function u6($,_){return new eq({check:"min_size",...y(_),minimum:$})}function P0($,_){return new $7({check:"size_equals",...y(_),size:$})}function T0($,_){return new _7({check:"max_length",...y(_),maximum:$})}function L4($,_){return new J7({check:"min_length",...y(_),minimum:$})}function S0($,_){return new W7({check:"length_equals",...y(_),length:$})}function m1($,_){return new U7({check:"string_format",format:"regex",...y(_),pattern:$})}function x1($){return new X7({check:"string_format",format:"lowercase",...y($)})}function u1($){return new G7({check:"string_format",format:"uppercase",...y($)})}function d1($,_){return new Y7({check:"string_format",format:"includes",...y(_),includes:$})}function n1($,_){return new Q7({check:"string_format",format:"starts_with",...y(_),prefix:$})}function c1($,_){return new q7({check:"string_format",format:"ends_with",...y(_),suffix:$})}function WX($,_,J){return new z7({check:"property",property:$,schema:_,...y(J)})}function i1($,_){return new j7({check:"mime_type",mime:$,...y(_)})}function R6($){return new D7({check:"overwrite",tx:$})}function l1($){return R6((_)=>_.normalize($))}function r1(){return R6(($)=>$.trim())}function p1(){return R6(($)=>$.toLowerCase())}function o1(){return R6(($)=>$.toUpperCase())}function t1(){return R6(($)=>Qq($))}function JD($,_,J){return new $({type:"array",element:_,...y(J)})}function Uu($,_,J){return new $({type:"union",options:_,...y(J)})}function Xu($,_,J){return new $({type:"union",options:_,inclusive:!1,...y(J)})}function Gu($,_,J,U){return new $({type:"union",options:J,discriminator:_,...y(U)})}function Yu($,_,J){return new $({type:"intersection",left:_,right:J})}function Qu($,_,J,U){let W=J instanceof R$;return new $({type:"tuple",items:_,rest:W?J:null,...y(W?U:J)})}function qu($,_,J,U){return new $({type:"record",keyType:_,valueType:J,...y(U)})}function zu($,_,J,U){return new $({type:"map",keyType:_,valueType:J,...y(U)})}function ju($,_,J){return new $({type:"set",valueType:_,...y(J)})}function Du($,_,J){let U=Array.isArray(_)?Object.fromEntries(_.map((W)=>[W,W])):_;return new $({type:"enum",entries:U,...y(J)})}function Ou($,_,J){return new $({type:"enum",entries:_,...y(J)})}function Lu($,_,J){return new $({type:"literal",values:Array.isArray(_)?_:[_],...y(J)})}function WD($,_){return new $({type:"file",...y(_)})}function Bu($,_){return new $({type:"transform",transform:_})}function Hu($,_){return new $({type:"optional",innerType:_})}function Nu($,_){return new $({type:"nullable",innerType:_})}function Vu($,_,J){return new $({type:"default",innerType:_,get defaultValue(){return typeof J==="function"?J():zq(J)}})}function Ru($,_,J){return new $({type:"nonoptional",innerType:_,...y(J)})}function Ku($,_){return new $({type:"success",innerType:_})}function Fu($,_,J){return new $({type:"catch",innerType:_,catchValue:typeof J==="function"?J:()=>J})}function Eu($,_,J){return new $({type:"pipe",in:_,out:J})}function Mu($,_){return new $({type:"readonly",innerType:_})}function Au($,_,J){return new $({type:"template_literal",parts:_,...y(J)})}function bu($,_){return new $({type:"lazy",getter:_})}function wu($,_){return new $({type:"promise",innerType:_})}function UD($,_,J){let U=y(J);return U.abort??(U.abort=!0),new $({type:"custom",check:"custom",fn:_,...U})}function XD($,_,J){return new $({type:"custom",check:"custom",fn:_,...y(J)})}function GD($,_){let J=xK((U)=>{return U.addIssue=(W)=>{if(typeof W==="string")U.issues.push(iJ(W,U.value,J._zod.def));else{let X=W;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=U.value),X.inst??(X.inst=J),X.continue??(X.continue=!J._zod.def.abort),U.issues.push(iJ(X))}},$(U.value,U)},_);return J}function xK($,_){let J=new X_({check:"custom",...y(_)});return J._zod.check=$,J}function YD($){let _=new X_({check:"describe"});return _._zod.onattach=[(J)=>{let U=g_.get(J)??{};g_.add(J,{...U,description:$})}],_._zod.check=()=>{},_}function QD($){let _=new X_({check:"meta"});return _._zod.onattach=[(J)=>{let U=g_.get(J)??{};g_.add(J,{...U,...$})}],_._zod.check=()=>{},_}function qD($,_){let J=y(_),U=J.truthy??["true","1","yes","on","y","enabled"],W=J.falsy??["false","0","no","off","n","disabled"];if(J.case!=="sensitive")U=U.map((B)=>typeof B==="string"?B.toLowerCase():B),W=W.map((B)=>typeof B==="string"?B.toLowerCase():B);let X=new Set(U),G=new Set(W),Y=$.Codec??cU,Q=$.Boolean??dU,L=new($.String??h1)({type:"string",error:J.error}),N=new Q({type:"boolean",error:J.error}),R=new Y({type:"pipe",in:L,out:N,transform:(B,H)=>{let V=B;if(J.case!=="sensitive")V=V.toLowerCase();if(X.has(V))return!0;else if(G.has(V))return!1;else return H.issues.push({code:"invalid_value",expected:"stringbool",values:[...X,...G],input:H.value,inst:R,continue:!1}),{}},reverseTransform:(B,H)=>{if(B===!0)return U[0]||"true";else return W[0]||"false"},error:J.error});return R}function _W($,_,J,U={}){let W=y(U),X={...y(U),check:"string_format",type:"string",format:_,fn:typeof J==="function"?J:(Y)=>J.test(Y),...W};if(J instanceof RegExp)X.pattern=J;return new $(X)}var D5;var uK=x(()=>{T8();tU();bz();e();D5={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function Z0($){let _=$?.target??"draft-2020-12";if(_==="draft-4")_="draft-04";if(_==="draft-7")_="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??g_,target:_,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function l$($,_,J={path:[],schemaPath:[]}){var U;let W=$._zod.def,X=_.seen.get($);if(X){if(X.count++,J.schemaPath.includes($))X.cycle=J.path;return X.schema}let G={schema:{},count:1,cycle:void 0,path:J.path};_.seen.set($,G);let Y=$._zod.toJSONSchema?.();if(Y)G.schema=Y;else{let L={...J,schemaPath:[...J.schemaPath,$],path:J.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(_,G.schema,L);else{let R=G.schema,B=_.processors[W.type];if(!B)throw Error(`[toJSONSchema]: Non-representable type encountered: ${W.type}`);B($,_,R,L)}let N=$._zod.parent;if(N){if(!G.ref)G.ref=N;l$(N,_,L),_.seen.get(N).isParent=!0}}let Q=_.metadataRegistry.get($);if(Q)Object.assign(G.schema,Q);if(_.io==="input"&&c_($))delete G.schema.examples,delete G.schema.default;if(_.io==="input"&&"_prefault"in G.schema)(U=G.schema).default??(U.default=G.schema._prefault);return delete G.schema._prefault,_.seen.get($).schema}function v0($,_){let J=$.seen.get(_);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let U=new Map;for(let G of $.seen.entries()){let Y=$.metadataRegistry.get(G[0])?.id;if(Y){let Q=U.get(Y);if(Q&&Q!==G[0])throw Error(`Duplicate schema id "${Y}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);U.set(Y,G[0])}}let W=(G)=>{let Y=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let N=$.external.registry.get(G[0])?.id,R=$.external.uri??((H)=>H);if(N)return{ref:R(N)};let B=G[1].defId??G[1].schema.id??`schema${$.counter++}`;return G[1].defId=B,{defId:B,ref:`${R("__shared")}#/${Y}/${B}`}}if(G[1]===J)return{ref:"#"};let q=`${"#"}/${Y}/`,L=G[1].schema.id??`__schema${$.counter++}`;return{defId:L,ref:q+L}},X=(G)=>{if(G[1].schema.$ref)return;let Y=G[1],{ref:Q,defId:q}=W(G);if(Y.def={...Y.schema},q)Y.defId=q;let L=Y.schema;for(let N in L)delete L[N];L.$ref=Q};if($.cycles==="throw")for(let G of $.seen.entries()){let Y=G[1];if(Y.cycle)throw Error(`Cycle detected: #/${Y.cycle?.join("/")}/ + `)}J.write("payload.value = newResult;"),J.write("return payload;");let R=J.compile();return(K,Q)=>R(W,K,Q)},I,j=P4,N=!A4.jitless,A=N&&hE.value,L=$.catchall,z;_._zod.parse=(W,J)=>{z??(z=U.value);let P=W.value;if(!j(P))return W.issues.push({expected:"object",code:"invalid_type",input:P,inst:_}),W;if(N&&A&&J?.async===!1&&J.jitless!==!0){if(!I)I=D($.shape);if(W=I(W,J),!L)return W;return oX([],P,W,J,z,_)}return g(W,J)}});ID=Y("$ZodUnion",(_,$)=>{l.init(_,$),$_(_._zod,"optin",()=>$.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),$_(_._zod,"optout",()=>$.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),$_(_._zod,"values",()=>{if($.options.every((U)=>U._zod.values))return new Set($.options.flatMap((U)=>Array.from(U._zod.values)));return}),$_(_._zod,"pattern",()=>{if($.options.every((U)=>U._zod.pattern)){let U=$.options.map((D)=>D._zod.pattern);return new RegExp(`^(${U.map((D)=>pg(D.source)).join("|")})$`)}return});let g=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(U,D)=>{if(g)return g(U,D);let I=!1,j=[];for(let N of $.options){let O=N._zod.run({value:U.value,issues:[]},D);if(O instanceof Promise)j.push(O),I=!0;else{if(O.issues.length===0)return O;j.push(O)}}if(!I)return CX(j,U,_,D);return Promise.all(j).then((N)=>{return CX(N,U,_,D)})}});kO=Y("$ZodXor",(_,$)=>{ID.init(_,$),$.inclusive=!1;let g=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(U,D)=>{if(g)return g(U,D);let I=!1,j=[];for(let N of $.options){let O=N._zod.run({value:U.value,issues:[]},D);if(O instanceof Promise)j.push(O),I=!0;else j.push(O)}if(!I)return rX(j,U,_,D);return Promise.all(j).then((N)=>{return rX(N,U,_,D)})}}),CO=Y("$ZodDiscriminatedUnion",(_,$)=>{$.inclusive=!1,ID.init(_,$);let g=_._zod.parse;$_(_._zod,"propValues",()=>{let D={};for(let I of $.options){let j=I._zod.propValues;if(!j||Object.keys(j).length===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(I)}"`);for(let[N,O]of Object.entries(j)){if(!D[N])D[N]=new Set;for(let A of O)D[N].add(A)}}return D});let U=V0(()=>{let D=$.options,I=new Map;for(let j of D){let N=j._zod.propValues?.[$.discriminator];if(!N||N.size===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(j)}"`);for(let O of N){if(I.has(O))throw Error(`Duplicate discriminator value "${String(O)}"`);I.set(O,j)}}return I});_._zod.parse=(D,I)=>{let j=D.value;if(!P4(j))return D.issues.push({code:"invalid_type",expected:"object",input:j,inst:_}),D;let N=U.value.get(j?.[$.discriminator]);if(N)return N._zod.run(D,I);if($.unionFallback||I.direction==="backward")return g(D,I);return D.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:$.discriminator,options:Array.from(U.value.keys()),input:j,path:[$.discriminator],inst:_}),D}}),rO=Y("$ZodIntersection",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value,I=$.left._zod.run({value:D,issues:[]},U),j=$.right._zod.run({value:D,issues:[]},U);if(I instanceof Promise||j instanceof Promise)return Promise.all([I,j]).then(([O,A])=>{return vX(g,O,A)});return vX(g,I,j)}});mI=Y("$ZodTuple",(_,$)=>{l.init(_,$);let g=$.items;_._zod.parse=(U,D)=>{let I=U.value;if(!Array.isArray(I))return U.issues.push({input:I,inst:_,expected:"tuple",code:"invalid_type"}),U;U.value=[];let j=[],N=fX(g,"optin"),O=fX(g,"optout");if(!$.rest){if(I.lengthg.length)U.issues.push({code:"too_big",maximum:g.length,inclusive:!0,input:I,inst:_,origin:"array"})}let A=Array(g.length);for(let L=0;L{A[L]=W}));else A[L]=z}if($.rest){let L=g.length-1,z=I.slice(g.length);for(let W of z){L++;let J=$.rest._zod.run({value:W,issues:[]},D);if(J instanceof Promise)j.push(J.then((P)=>wX(P,U,L)));else wX(J,U,L)}}if(j.length)return Promise.all(j).then(()=>uX(A,U,g,I,O));return uX(A,U,g,I,O)}});vO=Y("$ZodRecord",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value;if(!b6(D))return g.issues.push({expected:"record",code:"invalid_type",input:D,inst:_}),g;let I=[],j=$.keyType._zod.values;if(j){g.value={};let N=new Set;for(let A of j)if(typeof A==="string"||typeof A==="number"||typeof A==="symbol"){N.add(typeof A==="number"?A.toString():A);let L=$.keyType._zod.run({value:A,issues:[]},U);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length){g.issues.push({code:"invalid_key",origin:"record",issues:L.issues.map((J)=>l_(J,U,Z_())),input:A,path:[A],inst:_});continue}let z=L.value,W=$.valueType._zod.run({value:D[A],issues:[]},U);if(W instanceof Promise)I.push(W.then((J)=>{if(J.issues.length)g.issues.push(...s_(A,J.issues));g.value[z]=J.value}));else{if(W.issues.length)g.issues.push(...s_(A,W.issues));g.value[z]=W.value}}let O;for(let A in D)if(!N.has(A))O=O??[],O.push(A);if(O&&O.length>0)g.issues.push({code:"unrecognized_keys",input:D,inst:_,keys:O})}else{g.value={};for(let N of Reflect.ownKeys(D)){if(N==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(D,N))continue;let O=$.keyType._zod.run({value:N,issues:[]},U);if(O instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof N==="string"&&$D.test(N)&&O.issues.length){let z=$.keyType._zod.run({value:Number(N),issues:[]},U);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length===0)O=z}if(O.issues.length){if($.mode==="loose")g.value[N]=D[N];else g.issues.push({code:"invalid_key",origin:"record",issues:O.issues.map((z)=>l_(z,U,Z_())),input:N,path:[N],inst:_});continue}let L=$.valueType._zod.run({value:D[N],issues:[]},U);if(L instanceof Promise)I.push(L.then((z)=>{if(z.issues.length)g.issues.push(...s_(N,z.issues));g.value[O.value]=z.value}));else{if(L.issues.length)g.issues.push(...s_(N,L.issues));g.value[O.value]=L.value}}}if(I.length)return Promise.all(I).then(()=>g);return g}}),fO=Y("$ZodMap",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value;if(!(D instanceof Map))return g.issues.push({expected:"map",code:"invalid_type",input:D,inst:_}),g;let I=[];g.value=new Map;for(let[j,N]of D){let O=$.keyType._zod.run({value:j,issues:[]},U),A=$.valueType._zod.run({value:N,issues:[]},U);if(O instanceof Promise||A instanceof Promise)I.push(Promise.all([O,A]).then(([L,z])=>{xX(L,z,g,j,D,_,U)}));else xX(O,A,g,j,D,_,U)}if(I.length)return Promise.all(I).then(()=>g);return g}});wO=Y("$ZodSet",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value;if(!(D instanceof Set))return g.issues.push({input:D,inst:_,expected:"set",code:"invalid_type"}),g;let I=[];g.value=new Set;for(let j of D){let N=$.valueType._zod.run({value:j,issues:[]},U);if(N instanceof Promise)I.push(N.then((O)=>yX(O,g)));else yX(N,g)}if(I.length)return Promise.all(I).then(()=>g);return g}});uO=Y("$ZodEnum",(_,$)=>{l.init(_,$);let g=og($.entries),U=new Set(g);_._zod.values=U,_._zod.pattern=new RegExp(`^(${g.filter((D)=>eg.has(typeof D)).map((D)=>typeof D==="string"?P$(D):D.toString()).join("|")})$`),_._zod.parse=(D,I)=>{let j=D.value;if(U.has(j))return D;return D.issues.push({code:"invalid_value",values:g,input:j,inst:_}),D}}),xO=Y("$ZodLiteral",(_,$)=>{if(l.init(_,$),$.values.length===0)throw Error("Cannot create literal schema with no valid values");let g=new Set($.values);_._zod.values=g,_._zod.pattern=new RegExp(`^(${$.values.map((U)=>typeof U==="string"?P$(U):U?P$(U.toString()):String(U)).join("|")})$`),_._zod.parse=(U,D)=>{let I=U.value;if(g.has(I))return U;return U.issues.push({code:"invalid_value",values:$.values,input:I,inst:_}),U}}),yO=Y("$ZodFile",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{let D=g.value;if(D instanceof File)return g;return g.issues.push({expected:"file",code:"invalid_type",input:D,inst:_}),g}}),hO=Y("$ZodTransform",(_,$)=>{l.init(_,$),_._zod.optin="optional",_._zod.parse=(g,U)=>{if(U.direction==="backward")throw new L4(_.constructor.name);let D=$.transform(g.value,g);if(U.async)return(D instanceof Promise?D:Promise.resolve(D)).then((j)=>{return g.value=j,g.fallback=!0,g});if(D instanceof Promise)throw new x$;return g.value=D,g.fallback=!0,g}});iI=Y("$ZodOptional",(_,$)=>{l.init(_,$),_._zod.optin="optional",_._zod.optout="optional",$_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,void 0]):void 0}),$_(_._zod,"pattern",()=>{let g=$.innerType._zod.pattern;return g?new RegExp(`^(${pg(g.source)})?$`):void 0}),_._zod.parse=(g,U)=>{if($.innerType._zod.optin==="optional"){let D=g.value,I=$.innerType._zod.run(g,U);if(I instanceof Promise)return I.then((j)=>hX(j,D));return hX(I,D)}if(g.value===void 0)return g;return $.innerType._zod.run(g,U)}}),cO=Y("$ZodExactOptional",(_,$)=>{iI.init(_,$),$_(_._zod,"values",()=>$.innerType._zod.values),$_(_._zod,"pattern",()=>$.innerType._zod.pattern),_._zod.parse=(g,U)=>{return $.innerType._zod.run(g,U)}}),nO=Y("$ZodNullable",(_,$)=>{l.init(_,$),$_(_._zod,"optin",()=>$.innerType._zod.optin),$_(_._zod,"optout",()=>$.innerType._zod.optout),$_(_._zod,"pattern",()=>{let g=$.innerType._zod.pattern;return g?new RegExp(`^(${pg(g.source)}|null)$`):void 0}),$_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,null]):void 0}),_._zod.parse=(g,U)=>{if(g.value===null)return g;return $.innerType._zod.run(g,U)}}),dO=Y("$ZodDefault",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(g,U)=>{if(U.direction==="backward")return $.innerType._zod.run(g,U);if(g.value===void 0)return g.value=$.defaultValue,g;let D=$.innerType._zod.run(g,U);if(D instanceof Promise)return D.then((I)=>cX(I,$));return cX(D,$)}});mO=Y("$ZodPrefault",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(g,U)=>{if(U.direction==="backward")return $.innerType._zod.run(g,U);if(g.value===void 0)g.value=$.defaultValue;return $.innerType._zod.run(g,U)}}),iO=Y("$ZodNonOptional",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>{let g=$.innerType._zod.values;return g?new Set([...g].filter((U)=>U!==void 0)):void 0}),_._zod.parse=(g,U)=>{let D=$.innerType._zod.run(g,U);if(D instanceof Promise)return D.then((I)=>nX(I,_));return nX(D,_)}});lO=Y("$ZodSuccess",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{if(U.direction==="backward")throw new L4("ZodSuccess");let D=$.innerType._zod.run(g,U);if(D instanceof Promise)return D.then((I)=>{return g.value=I.issues.length===0,g});return g.value=D.issues.length===0,g}}),tO=Y("$ZodCatch",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"optout",()=>$.innerType._zod.optout),$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(g,U)=>{if(U.direction==="backward")return $.innerType._zod.run(g,U);let D=$.innerType._zod.run(g,U);if(D instanceof Promise)return D.then((I)=>{if(g.value=I.value,I.issues.length)g.value=$.catchValue({...g,error:{issues:I.issues.map((j)=>l_(j,U,Z_()))},input:g.value}),g.issues=[],g.fallback=!0;return g});if(g.value=D.value,D.issues.length)g.value=$.catchValue({...g,error:{issues:D.issues.map((I)=>l_(I,U,Z_()))},input:g.value}),g.issues=[],g.fallback=!0;return g}}),oO=Y("$ZodNaN",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{if(typeof g.value!=="number"||!Number.isNaN(g.value))return g.issues.push({input:g.value,inst:_,expected:"nan",code:"invalid_type"}),g;return g}}),lI=Y("$ZodPipe",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>$.in._zod.values),$_(_._zod,"optin",()=>$.in._zod.optin),$_(_._zod,"optout",()=>$.out._zod.optout),$_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(g,U)=>{if(U.direction==="backward"){let I=$.out._zod.run(g,U);if(I instanceof Promise)return I.then((j)=>xI(j,$.in,U));return xI(I,$.in,U)}let D=$.in._zod.run(g,U);if(D instanceof Promise)return D.then((I)=>xI(I,$.out,U));return xI(D,$.out,U)}});jD=Y("$ZodCodec",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>$.in._zod.values),$_(_._zod,"optin",()=>$.in._zod.optin),$_(_._zod,"optout",()=>$.out._zod.optout),$_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(g,U)=>{if((U.direction||"forward")==="forward"){let I=$.in._zod.run(g,U);if(I instanceof Promise)return I.then((j)=>yI(j,$,U));return yI(I,$,U)}else{let I=$.out._zod.run(g,U);if(I instanceof Promise)return I.then((j)=>yI(j,$,U));return yI(I,$,U)}}});pO=Y("$ZodPreprocess",(_,$)=>{lI.init(_,$)}),eO=Y("$ZodReadonly",(_,$)=>{l.init(_,$),$_(_._zod,"propValues",()=>$.innerType._zod.propValues),$_(_._zod,"values",()=>$.innerType._zod.values),$_(_._zod,"optin",()=>$.innerType?._zod?.optin),$_(_._zod,"optout",()=>$.innerType?._zod?.optout),_._zod.parse=(g,U)=>{if(U.direction==="backward")return $.innerType._zod.run(g,U);let D=$.innerType._zod.run(g,U);if(D instanceof Promise)return D.then(dX);return dX(D)}});aO=Y("$ZodTemplateLiteral",(_,$)=>{l.init(_,$);let g=[];for(let U of $.parts)if(typeof U==="object"&&U!==null){if(!U._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...U._zod.traits].shift()}`);let D=U._zod.pattern instanceof RegExp?U._zod.pattern.source:U._zod.pattern;if(!D)throw Error(`Invalid template literal part: ${U._zod.traits}`);let I=D.startsWith("^")?1:0,j=D.endsWith("$")?D.length-1:D.length;g.push(D.slice(I,j))}else if(U===null||nE.has(typeof U))g.push(P$(`${U}`));else throw Error(`Invalid template literal part: ${U}`);_._zod.pattern=new RegExp(`^${g.join("")}$`),_._zod.parse=(U,D)=>{if(typeof U.value!=="string")return U.issues.push({input:U.value,inst:_,expected:"string",code:"invalid_type"}),U;if(_._zod.pattern.lastIndex=0,!_._zod.pattern.test(U.value))return U.issues.push({input:U.value,inst:_,code:"invalid_format",format:$.format??"template_literal",pattern:_._zod.pattern.source}),U;return U}}),sO=Y("$ZodFunction",(_,$)=>{return l.init(_,$),_._def=$,_._zod.def=$,_.implement=(g)=>{if(typeof g!=="function")throw Error("implement() must be called with a function");return function(...U){let D=_._def.input?qI(_._def.input,U):U,I=Reflect.apply(g,this,D);if(_._def.output)return qI(_._def.output,I);return I}},_.implementAsync=(g)=>{if(typeof g!=="function")throw Error("implementAsync() must be called with a function");return async function(...U){let D=_._def.input?await BI(_._def.input,U):U,I=await Reflect.apply(g,this,D);if(_._def.output)return await BI(_._def.output,I);return I}},_._zod.parse=(g,U)=>{if(typeof g.value!=="function")return g.issues.push({code:"invalid_type",expected:"function",input:g.value,inst:_}),g;if(_._def.output&&_._def.output._zod.def.type==="promise")g.value=_.implementAsync(g.value);else g.value=_.implement(g.value);return g},_.input=(...g)=>{let U=_.constructor;if(Array.isArray(g[0]))return new U({type:"function",input:new mI({type:"tuple",items:g[0],rest:g[1]}),output:_._def.output});return new U({type:"function",input:g[0],output:_._def.output})},_.output=(g)=>{return new _.constructor({type:"function",input:_._def.input,output:g})},_}),_A=Y("$ZodPromise",(_,$)=>{l.init(_,$),_._zod.parse=(g,U)=>{return Promise.resolve(g.value).then((D)=>$.innerType._zod.run({value:D,issues:[]},U))}}),$A=Y("$ZodLazy",(_,$)=>{l.init(_,$),$_(_._zod,"innerType",()=>{let g=$;if(!g._cachedInner)g._cachedInner=$.getter();return g._cachedInner}),$_(_._zod,"pattern",()=>_._zod.innerType?._zod?.pattern),$_(_._zod,"propValues",()=>_._zod.innerType?._zod?.propValues),$_(_._zod,"optin",()=>_._zod.innerType?._zod?.optin??void 0),$_(_._zod,"optout",()=>_._zod.innerType?._zod?.optout??void 0),_._zod.parse=(g,U)=>{return _._zod.innerType._zod.run(g,U)}}),gA=Y("$ZodCustom",(_,$)=>{Y_.init(_,$),l.init(_,$),_._zod.parse=(g,U)=>{return g},_._zod.check=(g)=>{let U=g.value,D=$.fn(U);if(D instanceof Promise)return D.then((I)=>mX(I,g,U,_));mX(D,g,U,_);return}})});function UA(){return{localeError:aK()}}var aK=()=>{let _={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function $(D){return _[D]??null}let g={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${D.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`;return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${I}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`}case"invalid_value":if(D.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${F(D.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${D.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${I} ${D.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${D.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${I} ${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${D.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${I} ${D.minimum.toString()} ${j.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${D.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${I} ${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${D.prefix}"`;if(I.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${I.suffix}"`;if(I.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${I.includes}"`;if(I.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${I.pattern}`;return`${g[I.format]??D.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${D.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${D.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${D.keys.length>1?"\u0629":""}: ${B(D.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${D.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${D.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var eX=f(()=>{c()});function IA(){return{localeError:sK()}}var sK=()=>{let _={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function $(D){return _[D]??null}let g={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${D.expected}, daxil olan ${N}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${I}, daxil olan ${N}`}case"invalid_value":if(D.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${F(D.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${D.origin??"d\u0259y\u0259r"} ${I}${D.maximum.toString()} ${j.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${D.origin??"d\u0259y\u0259r"} ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${D.origin} ${I}${D.minimum.toString()} ${j.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${D.origin} ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${I.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(I.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${I.suffix}" il\u0259 bitm\u0259lidir`;if(I.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${I.includes}" daxil olmal\u0131d\u0131r`;if(I.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${I.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${g[I.format]??D.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${D.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${D.keys.length>1?"lar":""}: ${B(D.keys,", ")}`;case"invalid_key":return`${D.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${D.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var aX=f(()=>{c()});function sX(_,$,g,U){let D=Math.abs(_),I=D%10,j=D%100;if(j>=11&&j<=19)return U;if(I===1)return $;if(I>=2&&I<=4)return g;return U}function jA(){return{localeError:_V()}}var _V=()=>{let _={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function $(D){return _[D]??null}let g={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},U={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${D.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${I}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`}case"invalid_value":if(D.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${F(D.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j){let N=Number(D.maximum),O=sX(N,j.unit.one,j.unit.few,j.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${D.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${I}${D.maximum.toString()} ${O}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${D.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j){let N=Number(D.minimum),O=sX(N,j.unit.one,j.unit.few,j.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${D.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${I}${D.minimum.toString()} ${O}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${D.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${I.includes}"`;if(I.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${g[I.format]??D.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${D.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${D.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${B(D.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${D.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${D.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var _5=f(()=>{c()});function NA(){return{localeError:$V()}}var $V=()=>{let _={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function $(D){return _[D]??null}let g={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${D.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${I}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`}case"invalid_value":if(D.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${F(D.values[0])}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${D.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${I}${D.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${D.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${D.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${I}${D.minimum.toString()} ${j.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${D.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${I.pattern}`;let j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(I.format==="emoji")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="datetime")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="date")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(I.format==="time")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="duration")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${j} ${g[I.format]??D.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${D.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${D.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${D.keys.length>1?"\u043E\u0432\u0435":""}: ${B(D.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${D.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${D.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var $5=f(()=>{c()});function EA(){return{localeError:gV()}}var gV=()=>{let _={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function $(D){return _[D]??null}let g={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${D.expected}, s'ha rebut ${N}`;return`Tipus inv\xE0lid: s'esperava ${I}, s'ha rebut ${N}`}case"invalid_value":if(D.values.length===1)return`Valor inv\xE0lid: s'esperava ${F(D.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${B(D.values," o ")}`;case"too_big":{let I=D.inclusive?"com a m\xE0xim":"menys de",j=$(D.origin);if(j)return`Massa gran: s'esperava que ${D.origin??"el valor"} contingu\xE9s ${I} ${D.maximum.toString()} ${j.unit??"elements"}`;return`Massa gran: s'esperava que ${D.origin??"el valor"} fos ${I} ${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?"com a m\xEDnim":"m\xE9s de",j=$(D.origin);if(j)return`Massa petit: s'esperava que ${D.origin} contingu\xE9s ${I} ${D.minimum.toString()} ${j.unit}`;return`Massa petit: s'esperava que ${D.origin} fos ${I} ${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${I.prefix}"`;if(I.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${I.suffix}"`;if(I.format==="includes")return`Format inv\xE0lid: ha d'incloure "${I.includes}"`;if(I.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${I.pattern}`;return`Format inv\xE0lid per a ${g[I.format]??D.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${D.divisor}`;case"unrecognized_keys":return`Clau${D.keys.length>1?"s":""} no reconeguda${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${D.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${D.origin}`;default:return"Entrada inv\xE0lida"}}};var g5=f(()=>{c()});function OA(){return{localeError:DV()}}var DV=()=>{let _={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function $(D){return _[D]??null}let g={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},U={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${D.expected}, obdr\u017Eeno ${N}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${I}, obdr\u017Eeno ${N}`}case"invalid_value":if(D.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${F(D.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${D.origin??"hodnota"} mus\xED m\xEDt ${I}${D.maximum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${D.origin??"hodnota"} mus\xED b\xFDt ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${D.origin??"hodnota"} mus\xED m\xEDt ${I}${D.minimum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${D.origin??"hodnota"} mus\xED b\xFDt ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${I.prefix}"`;if(I.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${I.suffix}"`;if(I.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${I.includes}"`;if(I.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${I.pattern}`;return`Neplatn\xFD form\xE1t ${g[I.format]??D.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${D.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${B(D.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${D.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${D.origin}`;default:return"Neplatn\xFD vstup"}}};var D5=f(()=>{c()});function AA(){return{localeError:UV()}}var UV=()=>{let _={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function $(D){return _[D]??null}let g={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Ugyldigt input: forventede instanceof ${D.expected}, fik ${N}`;return`Ugyldigt input: forventede ${I}, fik ${N}`}case"invalid_value":if(D.values.length===1)return`Ugyldig v\xE6rdi: forventede ${F(D.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin),N=U[D.origin]??D.origin;if(j)return`For stor: forventede ${N??"value"} ${j.verb} ${I} ${D.maximum.toString()} ${j.unit??"elementer"}`;return`For stor: forventede ${N??"value"} havde ${I} ${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin),N=U[D.origin]??D.origin;if(j)return`For lille: forventede ${N} ${j.verb} ${I} ${D.minimum.toString()} ${j.unit}`;return`For lille: forventede ${N} havde ${I} ${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Ugyldig streng: skal starte med "${I.prefix}"`;if(I.format==="ends_with")return`Ugyldig streng: skal ende med "${I.suffix}"`;if(I.format==="includes")return`Ugyldig streng: skal indeholde "${I.includes}"`;if(I.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${I.pattern}`;return`Ugyldig ${g[I.format]??D.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${D.divisor}`;case"unrecognized_keys":return`${D.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${B(D.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${D.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${D.origin}`;default:return"Ugyldigt input"}}};var U5=f(()=>{c()});function LA(){return{localeError:IV()}}var IV=()=>{let _={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function $(D){return _[D]??null}let g={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},U={nan:"NaN",number:"Zahl",array:"Array"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${D.expected}, erhalten ${N}`;return`Ung\xFCltige Eingabe: erwartet ${I}, erhalten ${N}`}case"invalid_value":if(D.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${F(D.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Zu gro\xDF: erwartet, dass ${D.origin??"Wert"} ${I}${D.maximum.toString()} ${j.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${D.origin??"Wert"} ${I}${D.maximum.toString()} ist`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Zu klein: erwartet, dass ${D.origin} ${I}${D.minimum.toString()} ${j.unit} hat`;return`Zu klein: erwartet, dass ${D.origin} ${I}${D.minimum.toString()} ist`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Ung\xFCltiger String: muss mit "${I.prefix}" beginnen`;if(I.format==="ends_with")return`Ung\xFCltiger String: muss mit "${I.suffix}" enden`;if(I.format==="includes")return`Ung\xFCltiger String: muss "${I.includes}" enthalten`;if(I.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${I.pattern} entsprechen`;return`Ung\xFCltig: ${g[I.format]??D.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${D.divisor} sein`;case"unrecognized_keys":return`${D.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${B(D.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${D.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${D.origin}`;default:return"Ung\xFCltige Eingabe"}}};var I5=f(()=>{c()});function JA(){return{localeError:jV()}}var jV=()=>{let _={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function $(D){return _[D]??null}let g={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(typeof D.expected==="string"&&/^[A-Z]/.test(D.expected))return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${D.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${I}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`}case"invalid_value":if(D.values.length===1)return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${F(D.values[0])}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${D.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${I}${D.maximum.toString()} ${j.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${D.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${D.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${I}${D.minimum.toString()} ${j.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${D.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${I.prefix}"`;if(I.format==="ends_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${I.suffix}"`;if(I.format==="includes")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${I.includes}"`;if(I.format==="regex")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${I.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${g[I.format]??D.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${D.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${D.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${D.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${B(D.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${D.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${D.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var j5=f(()=>{c()});function ND(){return{localeError:NV()}}var NV=()=>{let _={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function $(D){return _[D]??null}let g={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;return`Invalid input: expected ${I}, received ${N}`}case"invalid_value":if(D.values.length===1)return`Invalid input: expected ${F(D.values[0])}`;return`Invalid option: expected one of ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Too big: expected ${D.origin??"value"} to have ${I}${D.maximum.toString()} ${j.unit??"elements"}`;return`Too big: expected ${D.origin??"value"} to be ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Too small: expected ${D.origin} to have ${I}${D.minimum.toString()} ${j.unit}`;return`Too small: expected ${D.origin} to be ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Invalid string: must start with "${I.prefix}"`;if(I.format==="ends_with")return`Invalid string: must end with "${I.suffix}"`;if(I.format==="includes")return`Invalid string: must include "${I.includes}"`;if(I.format==="regex")return`Invalid string: must match pattern ${I.pattern}`;return`Invalid ${g[I.format]??D.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${D.divisor}`;case"unrecognized_keys":return`Unrecognized key${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Invalid key in ${D.origin}`;case"invalid_union":if(D.options&&Array.isArray(D.options)&&D.options.length>0)return`Invalid discriminator value. Expected ${D.options.map((j)=>`'${j}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${D.origin}`;default:return"Invalid input"}}};var PA=f(()=>{c()});function zA(){return{localeError:EV()}}var EV=()=>{let _={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function $(D){return _[D]??null}let g={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},U={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${D.expected}, ricevi\u011Dis ${N}`;return`Nevalida enigo: atendi\u011Dis ${I}, ricevi\u011Dis ${N}`}case"invalid_value":if(D.values.length===1)return`Nevalida enigo: atendi\u011Dis ${F(D.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Tro granda: atendi\u011Dis ke ${D.origin??"valoro"} havu ${I}${D.maximum.toString()} ${j.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${D.origin??"valoro"} havu ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Tro malgranda: atendi\u011Dis ke ${D.origin} havu ${I}${D.minimum.toString()} ${j.unit}`;return`Tro malgranda: atendi\u011Dis ke ${D.origin} estu ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${I.prefix}"`;if(I.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${I.suffix}"`;if(I.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${I.includes}"`;if(I.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${I.pattern}`;return`Nevalida ${g[I.format]??D.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${D.divisor}`;case"unrecognized_keys":return`Nekonata${D.keys.length>1?"j":""} \u015Dlosilo${D.keys.length>1?"j":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${D.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${D.origin}`;default:return"Nevalida enigo"}}};var N5=f(()=>{c()});function SA(){return{localeError:OV()}}var OV=()=>{let _={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function $(D){return _[D]??null}let g={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${D.expected}, recibido ${N}`;return`Entrada inv\xE1lida: se esperaba ${I}, recibido ${N}`}case"invalid_value":if(D.values.length===1)return`Entrada inv\xE1lida: se esperaba ${F(D.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin),N=U[D.origin]??D.origin;if(j)return`Demasiado grande: se esperaba que ${N??"valor"} tuviera ${I}${D.maximum.toString()} ${j.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${N??"valor"} fuera ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin),N=U[D.origin]??D.origin;if(j)return`Demasiado peque\xF1o: se esperaba que ${N} tuviera ${I}${D.minimum.toString()} ${j.unit}`;return`Demasiado peque\xF1o: se esperaba que ${N} fuera ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${I.prefix}"`;if(I.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${I.suffix}"`;if(I.format==="includes")return`Cadena inv\xE1lida: debe incluir "${I.includes}"`;if(I.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${I.pattern}`;return`Inv\xE1lido ${g[I.format]??D.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${D.divisor}`;case"unrecognized_keys":return`Llave${D.keys.length>1?"s":""} desconocida${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${U[D.origin]??D.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${U[D.origin]??D.origin}`;default:return"Entrada inv\xE1lida"}}};var E5=f(()=>{c()});function WA(){return{localeError:AV()}}var AV=()=>{let _={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function $(D){return _[D]??null}let g={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${D.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${I} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(D.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${F(D.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${B(D.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${D.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${I}${D.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${D.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${I}${D.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${D.origin} \u0628\u0627\u06CC\u062F ${I}${D.minimum.toString()} ${j.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${D.origin} \u0628\u0627\u06CC\u062F ${I}${D.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${I.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(I.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${I.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(I.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${I.includes}" \u0628\u0627\u0634\u062F`;if(I.format==="regex")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${I.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${g[I.format]??D.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${D.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${D.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${B(D.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${D.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${D.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var O5=f(()=>{c()});function XA(){return{localeError:LV()}}var LV=()=>{let _={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function $(D){return _[D]??null}let g={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Virheellinen tyyppi: odotettiin instanceof ${D.expected}, oli ${N}`;return`Virheellinen tyyppi: odotettiin ${I}, oli ${N}`}case"invalid_value":if(D.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${F(D.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Liian suuri: ${j.subject} t\xE4ytyy olla ${I}${D.maximum.toString()} ${j.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Liian pieni: ${j.subject} t\xE4ytyy olla ${I}${D.minimum.toString()} ${j.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${I.prefix}"`;if(I.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${I.suffix}"`;if(I.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${I.includes}"`;if(I.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${I.pattern}`;return`Virheellinen ${g[I.format]??D.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${D.divisor} monikerta`;case"unrecognized_keys":return`${D.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${B(D.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};var A5=f(()=>{c()});function RA(){return{localeError:JV()}}var JV=()=>{let _={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function $(D){return _[D]??null}let g={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Entr\xE9e invalide : instanceof ${D.expected} attendu, ${N} re\xE7u`;return`Entr\xE9e invalide : ${I} attendu, ${N} re\xE7u`}case"invalid_value":if(D.values.length===1)return`Entr\xE9e invalide : ${F(D.values[0])} attendu`;return`Option invalide : une valeur parmi ${B(D.values,"|")} attendue`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Trop grand : ${U[D.origin]??"valeur"} doit ${j.verb} ${I}${D.maximum.toString()} ${j.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${U[D.origin]??"valeur"} doit \xEAtre ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Trop petit : ${U[D.origin]??"valeur"} doit ${j.verb} ${I}${D.minimum.toString()} ${j.unit}`;return`Trop petit : ${U[D.origin]??"valeur"} doit \xEAtre ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${I.prefix}"`;if(I.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${I.suffix}"`;if(I.format==="includes")return`Cha\xEEne invalide : doit inclure "${I.includes}"`;if(I.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${I.pattern}`;return`${g[I.format]??D.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${D.divisor}`;case"unrecognized_keys":return`Cl\xE9${D.keys.length>1?"s":""} non reconnue${D.keys.length>1?"s":""} : ${B(D.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${D.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${D.origin}`;default:return"Entr\xE9e invalide"}}};var L5=f(()=>{c()});function GA(){return{localeError:PV()}}var PV=()=>{let _={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function $(D){return _[D]??null}let g={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Entr\xE9e invalide : attendu instanceof ${D.expected}, re\xE7u ${N}`;return`Entr\xE9e invalide : attendu ${I}, re\xE7u ${N}`}case"invalid_value":if(D.values.length===1)return`Entr\xE9e invalide : attendu ${F(D.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"\u2264":"<",j=$(D.origin);if(j)return`Trop grand : attendu que ${D.origin??"la valeur"} ait ${I}${D.maximum.toString()} ${j.unit}`;return`Trop grand : attendu que ${D.origin??"la valeur"} soit ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?"\u2265":">",j=$(D.origin);if(j)return`Trop petit : attendu que ${D.origin} ait ${I}${D.minimum.toString()} ${j.unit}`;return`Trop petit : attendu que ${D.origin} soit ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${I.prefix}"`;if(I.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${I.suffix}"`;if(I.format==="includes")return`Cha\xEEne invalide : doit inclure "${I.includes}"`;if(I.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${I.pattern}`;return`${g[I.format]??D.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${D.divisor}`;case"unrecognized_keys":return`Cl\xE9${D.keys.length>1?"s":""} non reconnue${D.keys.length>1?"s":""} : ${B(D.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${D.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${D.origin}`;default:return"Entr\xE9e invalide"}}};var J5=f(()=>{c()});function YA(){return{localeError:zV()}}var zV=()=>{let _={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},$={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},g=(A)=>A?_[A]:void 0,U=(A)=>{let L=g(A);if(L)return L.label;return A??_.unknown.label},D=(A)=>`\u05D4${U(A)}`,I=(A)=>{return(g(A)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},j=(A)=>{if(!A)return null;return $[A]??null},N={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},O={nan:"NaN"};return(A)=>{switch(A.code){case"invalid_type":{let L=A.expected,z=O[L??""]??U(L),W=M(A.input),J=O[W]??_[W]?.label??W;if(/^[A-Z]/.test(A.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${A.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${J}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${z}, \u05D4\u05EA\u05E7\u05D1\u05DC ${J}`}case"invalid_value":{if(A.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${F(A.values[0])}`;let L=A.values.map((J)=>F(J));if(A.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L[0]} \u05D0\u05D5 ${L[1]}`;let z=L[L.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L.slice(0,-1).join(", ")} \u05D0\u05D5 ${z}`}case"too_big":{let L=j(A.origin),z=D(A.origin??"value");if(A.origin==="string")return`${L?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${A.maximum.toString()} ${L?.unit??""} ${A.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(A.origin==="number"){let P=A.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${A.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${A.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${P}`}if(A.origin==="array"||A.origin==="set"){let P=A.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",S=A.inclusive?`${A.maximum} ${L?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${A.maximum} ${L?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${S}`.trim()}let W=A.inclusive?"<=":"<",J=I(A.origin??"value");if(L?.unit)return`${L.longLabel} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.maximum.toString()} ${L.unit}`;return`${L?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.maximum.toString()}`}case"too_small":{let L=j(A.origin),z=D(A.origin??"value");if(A.origin==="string")return`${L?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${A.minimum.toString()} ${L?.unit??""} ${A.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(A.origin==="number"){let P=A.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${A.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${A.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${P}`}if(A.origin==="array"||A.origin==="set"){let P=A.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(A.minimum===1&&A.inclusive){let X=A.origin==="set"?"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3":"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${X}`}let S=A.inclusive?`${A.minimum} ${L?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${A.minimum} ${L?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${S}`.trim()}let W=A.inclusive?">=":">",J=I(A.origin??"value");if(L?.unit)return`${L.shortLabel} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.minimum.toString()} ${L.unit}`;return`${L?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.minimum.toString()}`}case"invalid_format":{let L=A;if(L.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${L.prefix}"`;if(L.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${L.suffix}"`;if(L.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${L.includes}"`;if(L.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${L.pattern}`;let z=N[L.format],W=z?.label??L.format,P=(z?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${W} \u05DC\u05D0 ${P}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${A.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${A.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${A.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${B(A.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${D(A.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var P5=f(()=>{c()});function QA(){return{localeError:SV()}}var SV=()=>{let _={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function $(D){return _[D]??null}let g={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},U={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${D.expected}, a primljeno je ${N}`;return`Neispravan unos: o\u010Dekuje se ${I}, a primljeno je ${N}`}case"invalid_value":if(D.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${F(D.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin),N=U[D.origin]??D.origin;if(j)return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} ima ${I}${D.maximum.toString()} ${j.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} bude ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin),N=U[D.origin]??D.origin;if(j)return`Premalo: o\u010Dekivano da ${N} ima ${I}${D.minimum.toString()} ${j.unit}`;return`Premalo: o\u010Dekivano da ${N} bude ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${I.prefix}"`;if(I.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${I.suffix}"`;if(I.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${I.includes}"`;if(I.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${I.pattern}`;return`Neispravna ${g[I.format]??D.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${D.divisor}`;case"unrecognized_keys":return`Neprepoznat${D.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${B(D.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${U[D.origin]??D.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${U[D.origin]??D.origin}`;default:return"Neispravan unos"}}};var z5=f(()=>{c()});function TA(){return{localeError:WV()}}var WV=()=>{let _={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function $(D){return _[D]??null}let g={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},U={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${D.expected}, a kapott \xE9rt\xE9k ${N}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${I}, a kapott \xE9rt\xE9k ${N}`}case"invalid_value":if(D.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${F(D.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`T\xFAl nagy: ${D.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${I}${D.maximum.toString()} ${j.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${D.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${D.origin} m\xE9rete t\xFAl kicsi ${I}${D.minimum.toString()} ${j.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${D.origin} t\xFAl kicsi ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\xC9rv\xE9nytelen string: "${I.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(I.format==="ends_with")return`\xC9rv\xE9nytelen string: "${I.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(I.format==="includes")return`\xC9rv\xE9nytelen string: "${I.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(I.format==="regex")return`\xC9rv\xE9nytelen string: ${I.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${g[I.format]??D.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${D.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${D.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${D.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var S5=f(()=>{c()});function W5(_,$,g){return Math.abs(_)===1?$:g}function v0(_){if(!_)return"";let $=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],g=_[_.length-1];return _+($.includes(g)?"\u0576":"\u0568")}function qA(){return{localeError:XV()}}var XV=()=>{let _={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function $(D){return _[D]??null}let g={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},U={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${D.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`;return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${I}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`}case"invalid_value":if(D.values.length===1)return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${F(D.values[1])}`;return`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j){let N=Number(D.maximum),O=W5(N,j.unit.one,j.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${v0(D.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${I}${D.maximum.toString()} ${O}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${v0(D.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j){let N=Number(D.minimum),O=W5(N,j.unit.one,j.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${v0(D.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${I}${D.minimum.toString()} ${O}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${v0(D.origin)} \u056C\u056B\u0576\u056B ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${I.prefix}"-\u0578\u057E`;if(I.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${I.suffix}"-\u0578\u057E`;if(I.format==="includes")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${I.includes}"`;if(I.format==="regex")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${I.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${g[I.format]??D.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${D.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${D.keys.length>1?"\u0576\u0565\u0580":""}. ${B(D.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${v0(D.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${v0(D.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var X5=f(()=>{c()});function BA(){return{localeError:RV()}}var RV=()=>{let _={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function $(D){return _[D]??null}let g={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Input tidak valid: diharapkan instanceof ${D.expected}, diterima ${N}`;return`Input tidak valid: diharapkan ${I}, diterima ${N}`}case"invalid_value":if(D.values.length===1)return`Input tidak valid: diharapkan ${F(D.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Terlalu besar: diharapkan ${D.origin??"value"} memiliki ${I}${D.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: diharapkan ${D.origin??"value"} menjadi ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Terlalu kecil: diharapkan ${D.origin} memiliki ${I}${D.minimum.toString()} ${j.unit}`;return`Terlalu kecil: diharapkan ${D.origin} menjadi ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`String tidak valid: harus dimulai dengan "${I.prefix}"`;if(I.format==="ends_with")return`String tidak valid: harus berakhir dengan "${I.suffix}"`;if(I.format==="includes")return`String tidak valid: harus menyertakan "${I.includes}"`;if(I.format==="regex")return`String tidak valid: harus sesuai pola ${I.pattern}`;return`${g[I.format]??D.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${D.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${D.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${D.origin}`;default:return"Input tidak valid"}}};var R5=f(()=>{c()});function KA(){return{localeError:GV()}}var GV=()=>{let _={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function $(D){return _[D]??null}let g={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},U={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera instanceof ${D.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera ${I}`}case"invalid_value":if(D.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${F(D.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${D.origin??"gildi"} hafi ${I}${D.maximum.toString()} ${j.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${D.origin??"gildi"} s\xE9 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${D.origin} hafi ${I}${D.minimum.toString()} ${j.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${D.origin} s\xE9 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${I.prefix}"`;if(I.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${I.suffix}"`;if(I.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${I.includes}"`;if(I.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${I.pattern}`;return`Rangt ${g[I.format]??D.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${D.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${D.keys.length>1?"ir lyklar":"ur lykill"}: ${B(D.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${D.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${D.origin}`;default:return"Rangt gildi"}}};var G5=f(()=>{c()});function VA(){return{localeError:YV()}}var YV=()=>{let _={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function $(D){return _[D]??null}let g={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"numero",array:"vettore"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Input non valido: atteso instanceof ${D.expected}, ricevuto ${N}`;return`Input non valido: atteso ${I}, ricevuto ${N}`}case"invalid_value":if(D.values.length===1)return`Input non valido: atteso ${F(D.values[0])}`;return`Opzione non valida: atteso uno tra ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Troppo grande: ${D.origin??"valore"} deve avere ${I}${D.maximum.toString()} ${j.unit??"elementi"}`;return`Troppo grande: ${D.origin??"valore"} deve essere ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Troppo piccolo: ${D.origin} deve avere ${I}${D.minimum.toString()} ${j.unit}`;return`Troppo piccolo: ${D.origin} deve essere ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Stringa non valida: deve iniziare con "${I.prefix}"`;if(I.format==="ends_with")return`Stringa non valida: deve terminare con "${I.suffix}"`;if(I.format==="includes")return`Stringa non valida: deve includere "${I.includes}"`;if(I.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${I.pattern}`;return`Input non valido: ${g[I.format]??D.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${D.divisor}`;case"unrecognized_keys":return`Chiav${D.keys.length>1?"i":"e"} non riconosciut${D.keys.length>1?"e":"a"}: ${B(D.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${D.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${D.origin}`;default:return"Input non valido"}}};var Y5=f(()=>{c()});function FA(){return{localeError:QV()}}var QV=()=>{let _={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function $(D){return _[D]??null}let g={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},U={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${D.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${I}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(D.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${F(D.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${B(D.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let I=D.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",j=$(D.origin);if(j)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${D.origin??"\u5024"}\u306F${D.maximum.toString()}${j.unit??"\u8981\u7D20"}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${D.origin??"\u5024"}\u306F${D.maximum.toString()}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let I=D.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",j=$(D.origin);if(j)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${D.origin}\u306F${D.minimum.toString()}${j.unit}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${D.origin}\u306F${D.minimum.toString()}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${I.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${g[I.format]??D.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${D.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${D.keys.length>1?"\u7FA4":""}: ${B(D.keys,"\u3001")}`;case"invalid_key":return`${D.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${D.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var Q5=f(()=>{c()});function MA(){return{localeError:TV()}}var TV=()=>{let _={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function $(D){return _[D]??null}let g={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},U={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${D.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${I}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`}case"invalid_value":if(D.values.length===1)return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${F(D.values[0])}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${B(D.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${D.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${j.verb} ${I}${D.maximum.toString()} ${j.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${D.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${D.origin} ${j.verb} ${I}${D.minimum.toString()} ${j.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${D.origin} \u10D8\u10E7\u10DD\u10E1 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${I.prefix}"-\u10D8\u10D7`;if(I.format==="ends_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${I.suffix}"-\u10D8\u10D7`;if(I.format==="includes")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${I.includes}"-\u10E1`;if(I.format==="regex")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${I.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${g[I.format]??D.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${D.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${D.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${B(D.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${D.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${D.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var T5=f(()=>{c()});function ED(){return{localeError:qV()}}var qV=()=>{let _={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function $(D){return _[D]??null}let g={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},U={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${D.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`;return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${I} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`}case"invalid_value":if(D.values.length===1)return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${F(D.values[0])}`;return`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${D.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${I} ${D.maximum.toString()} ${j.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${D.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${I} ${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${D.origin} ${I} ${D.minimum.toString()} ${j.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${D.origin} ${I} ${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${I.prefix}"`;if(I.format==="ends_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${I.suffix}"`;if(I.format==="includes")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${I.includes}"`;if(I.format==="regex")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${I.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${g[I.format]??D.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${D.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${B(D.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${D.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${D.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};var ZA=f(()=>{c()});function bA(){return ED()}var q5=f(()=>{ZA()});function HA(){return{localeError:BV()}}var BV=()=>{let _={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function $(D){return _[D]??null}let g={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${D.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${I}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`}case"invalid_value":if(D.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${F(D.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${B(D.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let I=D.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",j=I==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(D.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${D.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${D.maximum.toString()}${O} ${I}${j}`;return`${D.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${D.maximum.toString()} ${I}${j}`}case"too_small":{let I=D.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",j=I==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(D.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${D.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${D.minimum.toString()}${O} ${I}${j}`;return`${D.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${D.minimum.toString()} ${I}${j}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${I.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${g[I.format]??D.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${D.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${B(D.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${D.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${D.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var B5=f(()=>{c()});function K5(_){let $=Math.abs(_),g=$%10,U=$%100;if(U>=11&&U<=19||g===0)return"many";if(g===1)return"one";return"few"}function kA(){return{localeError:KV()}}var OD=(_)=>{return _.charAt(0).toUpperCase()+_.slice(1)},KV=()=>{let _={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function $(D,I,j,N){let O=_[D]??null;if(O===null)return O;return{unit:O.unit[I],verb:O.verb[N][j?"inclusive":"notInclusive"]}}let g={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},U={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Gautas tipas ${N}, o tik\u0117tasi - instanceof ${D.expected}`;return`Gautas tipas ${N}, o tik\u0117tasi - ${I}`}case"invalid_value":if(D.values.length===1)return`Privalo b\u016Bti ${F(D.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${B(D.values,"|")} pasirinkim\u0173`;case"too_big":{let I=U[D.origin]??D.origin,j=$(D.origin,K5(Number(D.maximum)),D.inclusive??!1,"smaller");if(j?.verb)return`${OD(I??D.origin??"reik\u0161m\u0117")} ${j.verb} ${D.maximum.toString()} ${j.unit??"element\u0173"}`;let N=D.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${OD(I??D.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${D.maximum.toString()} ${j?.unit}`}case"too_small":{let I=U[D.origin]??D.origin,j=$(D.origin,K5(Number(D.minimum)),D.inclusive??!1,"bigger");if(j?.verb)return`${OD(I??D.origin??"reik\u0161m\u0117")} ${j.verb} ${D.minimum.toString()} ${j.unit??"element\u0173"}`;let N=D.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${OD(I??D.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${D.minimum.toString()} ${j?.unit}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${I.prefix}"`;if(I.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${I.suffix}"`;if(I.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${I.includes}"`;if(I.format==="regex")return`Eilut\u0117 privalo atitikti ${I.pattern}`;return`Neteisingas ${g[I.format]??D.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${D.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${D.keys.length>1?"i":"as"} rakt${D.keys.length>1?"ai":"as"}: ${B(D.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let I=U[D.origin]??D.origin;return`${OD(I??D.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var V5=f(()=>{c()});function CA(){return{localeError:VV()}}var VV=()=>{let _={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function $(D){return _[D]??null}let g={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},U={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${D.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${I}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`}case"invalid_value":if(D.values.length===1)return`Invalid input: expected ${F(D.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${D.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${I}${D.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${D.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${D.origin} \u0434\u0430 \u0438\u043C\u0430 ${I}${D.minimum.toString()} ${j.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${D.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${I.pattern}`;return`Invalid ${g[I.format]??D.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${D.divisor}`;case"unrecognized_keys":return`${D.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${B(D.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${D.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${D.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var F5=f(()=>{c()});function rA(){return{localeError:FV()}}var FV=()=>{let _={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function $(D){return _[D]??null}let g={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"nombor"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Input tidak sah: dijangka instanceof ${D.expected}, diterima ${N}`;return`Input tidak sah: dijangka ${I}, diterima ${N}`}case"invalid_value":if(D.values.length===1)return`Input tidak sah: dijangka ${F(D.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Terlalu besar: dijangka ${D.origin??"nilai"} ${j.verb} ${I}${D.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: dijangka ${D.origin??"nilai"} adalah ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Terlalu kecil: dijangka ${D.origin} ${j.verb} ${I}${D.minimum.toString()} ${j.unit}`;return`Terlalu kecil: dijangka ${D.origin} adalah ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`String tidak sah: mesti bermula dengan "${I.prefix}"`;if(I.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${I.suffix}"`;if(I.format==="includes")return`String tidak sah: mesti mengandungi "${I.includes}"`;if(I.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${I.pattern}`;return`${g[I.format]??D.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${D.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${B(D.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${D.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${D.origin}`;default:return"Input tidak sah"}}};var M5=f(()=>{c()});function vA(){return{localeError:MV()}}var MV=()=>{let _={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function $(D){return _[D]??null}let g={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},U={nan:"NaN",number:"getal"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Ongeldige invoer: verwacht instanceof ${D.expected}, ontving ${N}`;return`Ongeldige invoer: verwacht ${I}, ontving ${N}`}case"invalid_value":if(D.values.length===1)return`Ongeldige invoer: verwacht ${F(D.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin),N=D.origin==="date"?"laat":D.origin==="string"?"lang":"groot";if(j)return`Te ${N}: verwacht dat ${D.origin??"waarde"} ${I}${D.maximum.toString()} ${j.unit??"elementen"} ${j.verb}`;return`Te ${N}: verwacht dat ${D.origin??"waarde"} ${I}${D.maximum.toString()} is`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin),N=D.origin==="date"?"vroeg":D.origin==="string"?"kort":"klein";if(j)return`Te ${N}: verwacht dat ${D.origin} ${I}${D.minimum.toString()} ${j.unit} ${j.verb}`;return`Te ${N}: verwacht dat ${D.origin} ${I}${D.minimum.toString()} is`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Ongeldige tekst: moet met "${I.prefix}" beginnen`;if(I.format==="ends_with")return`Ongeldige tekst: moet op "${I.suffix}" eindigen`;if(I.format==="includes")return`Ongeldige tekst: moet "${I.includes}" bevatten`;if(I.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${I.pattern}`;return`Ongeldig: ${g[I.format]??D.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${D.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${D.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${D.origin}`;default:return"Ongeldige invoer"}}};var Z5=f(()=>{c()});function fA(){return{localeError:ZV()}}var ZV=()=>{let _={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function $(D){return _[D]??null}let g={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"tall",array:"liste"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Ugyldig input: forventet instanceof ${D.expected}, fikk ${N}`;return`Ugyldig input: forventet ${I}, fikk ${N}`}case"invalid_value":if(D.values.length===1)return`Ugyldig verdi: forventet ${F(D.values[0])}`;return`Ugyldig valg: forventet en av ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`For stor(t): forventet ${D.origin??"value"} til \xE5 ha ${I}${D.maximum.toString()} ${j.unit??"elementer"}`;return`For stor(t): forventet ${D.origin??"value"} til \xE5 ha ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`For lite(n): forventet ${D.origin} til \xE5 ha ${I}${D.minimum.toString()} ${j.unit}`;return`For lite(n): forventet ${D.origin} til \xE5 ha ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${I.prefix}"`;if(I.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${I.suffix}"`;if(I.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${I.includes}"`;if(I.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${I.pattern}`;return`Ugyldig ${g[I.format]??D.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${D.divisor}`;case"unrecognized_keys":return`${D.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${B(D.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${D.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${D.origin}`;default:return"Ugyldig input"}}};var b5=f(()=>{c()});function wA(){return{localeError:bV()}}var bV=()=>{let _={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function $(D){return _[D]??null}let g={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},U={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`F\xE2sit giren: umulan instanceof ${D.expected}, al\u0131nan ${N}`;return`F\xE2sit giren: umulan ${I}, al\u0131nan ${N}`}case"invalid_value":if(D.values.length===1)return`F\xE2sit giren: umulan ${F(D.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Fazla b\xFCy\xFCk: ${D.origin??"value"}, ${I}${D.maximum.toString()} ${j.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${D.origin??"value"}, ${I}${D.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Fazla k\xFC\xE7\xFCk: ${D.origin}, ${I}${D.minimum.toString()} ${j.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${D.origin}, ${I}${D.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`F\xE2sit metin: "${I.prefix}" ile ba\u015Flamal\u0131.`;if(I.format==="ends_with")return`F\xE2sit metin: "${I.suffix}" ile bitmeli.`;if(I.format==="includes")return`F\xE2sit metin: "${I.includes}" ihtiv\xE2 etmeli.`;if(I.format==="regex")return`F\xE2sit metin: ${I.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${g[I.format]??D.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${D.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`${D.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${D.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var H5=f(()=>{c()});function uA(){return{localeError:HV()}}var HV=()=>{let _={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function $(D){return _[D]??null}let g={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${D.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${I} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(D.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${F(D.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${B(D.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${D.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${I}${D.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${D.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${I}${D.maximum.toString()} \u0648\u064A`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${D.origin} \u0628\u0627\u06CC\u062F ${I}${D.minimum.toString()} ${j.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${D.origin} \u0628\u0627\u06CC\u062F ${I}${D.minimum.toString()} \u0648\u064A`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${I.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(I.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${I.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(I.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${I.includes}" \u0648\u0644\u0631\u064A`;if(I.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${I.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${g[I.format]??D.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${D.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${D.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${B(D.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${D.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${D.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var k5=f(()=>{c()});function xA(){return{localeError:kV()}}var kV=()=>{let _={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function $(D){return _[D]??null}let g={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},U={nan:"NaN",number:"liczba",array:"tablica"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${D.expected}, otrzymano ${N}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${I}, otrzymano ${N}`}case"invalid_value":if(D.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${F(D.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${D.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${I}${D.maximum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${D.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${D.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${I}${D.minimum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${D.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${I.prefix}"`;if(I.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${I.suffix}"`;if(I.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${I.includes}"`;if(I.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${I.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${g[I.format]??D.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${D.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${D.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${D.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var C5=f(()=>{c()});function yA(){return{localeError:CV()}}var CV=()=>{let _={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function $(D){return _[D]??null}let g={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Tipo inv\xE1lido: esperado instanceof ${D.expected}, recebido ${N}`;return`Tipo inv\xE1lido: esperado ${I}, recebido ${N}`}case"invalid_value":if(D.values.length===1)return`Entrada inv\xE1lida: esperado ${F(D.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Muito grande: esperado que ${D.origin??"valor"} tivesse ${I}${D.maximum.toString()} ${j.unit??"elementos"}`;return`Muito grande: esperado que ${D.origin??"valor"} fosse ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Muito pequeno: esperado que ${D.origin} tivesse ${I}${D.minimum.toString()} ${j.unit}`;return`Muito pequeno: esperado que ${D.origin} fosse ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${I.prefix}"`;if(I.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${I.suffix}"`;if(I.format==="includes")return`Texto inv\xE1lido: deve incluir "${I.includes}"`;if(I.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${I.pattern}`;return`${g[I.format]??D.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${D.divisor}`;case"unrecognized_keys":return`Chave${D.keys.length>1?"s":""} desconhecida${D.keys.length>1?"s":""}: ${B(D.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${D.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${D.origin}`;default:return"Campo inv\xE1lido"}}};var r5=f(()=>{c()});function hA(){return{localeError:rV()}}var rV=()=>{let _={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function $(D){return _[D]??null}let g={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},U={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;return`Intrare invalid\u0103: a\u0219teptat ${I}, primit ${N}`}case"invalid_value":if(D.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${F(D.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Prea mare: a\u0219teptat ca ${D.origin??"valoarea"} ${j.verb} ${I}${D.maximum.toString()} ${j.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${D.origin??"valoarea"} s\u0103 fie ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Prea mic: a\u0219teptat ca ${D.origin} ${j.verb} ${I}${D.minimum.toString()} ${j.unit}`;return`Prea mic: a\u0219teptat ca ${D.origin} s\u0103 fie ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${I.prefix}"`;if(I.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${I.suffix}"`;if(I.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${I.includes}"`;if(I.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${I.pattern}`;return`Format invalid: ${g[I.format]??D.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${D.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${B(D.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${D.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${D.origin}`;default:return"Intrare invalid\u0103"}}};var v5=f(()=>{c()});function f5(_,$,g,U){let D=Math.abs(_),I=D%10,j=D%100;if(j>=11&&j<=19)return U;if(I===1)return $;if(I>=2&&I<=4)return g;return U}function cA(){return{localeError:vV()}}var vV=()=>{let _={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function $(D){return _[D]??null}let g={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${D.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${I}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`}case"invalid_value":if(D.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${F(D.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j){let N=Number(D.maximum),O=f5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${D.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${I}${D.maximum.toString()} ${O}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${D.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j){let N=Number(D.minimum),O=f5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${D.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${I}${D.minimum.toString()} ${O}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${D.origin} \u0431\u0443\u0434\u0435\u0442 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${g[I.format]??D.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${D.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${D.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${D.keys.length>1?"\u0438":""}: ${B(D.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${D.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${D.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};var w5=f(()=>{c()});function nA(){return{localeError:fV()}}var fV=()=>{let _={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function $(D){return _[D]??null}let g={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},U={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${D.expected}, prejeto ${N}`;return`Neveljaven vnos: pri\u010Dakovano ${I}, prejeto ${N}`}case"invalid_value":if(D.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${F(D.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Preveliko: pri\u010Dakovano, da bo ${D.origin??"vrednost"} imelo ${I}${D.maximum.toString()} ${j.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${D.origin??"vrednost"} ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Premajhno: pri\u010Dakovano, da bo ${D.origin} imelo ${I}${D.minimum.toString()} ${j.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${D.origin} ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${I.prefix}"`;if(I.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${I.suffix}"`;if(I.format==="includes")return`Neveljaven niz: mora vsebovati "${I.includes}"`;if(I.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${I.pattern}`;return`Neveljaven ${g[I.format]??D.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${D.divisor}`;case"unrecognized_keys":return`Neprepoznan${D.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${B(D.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${D.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${D.origin}`;default:return"Neveljaven vnos"}}};var u5=f(()=>{c()});function dA(){return{localeError:wV()}}var wV=()=>{let _={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function $(D){return _[D]??null}let g={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},U={nan:"NaN",number:"antal",array:"lista"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${D.expected}, fick ${N}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${I}, fick ${N}`}case"invalid_value":if(D.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${F(D.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${D.origin??"v\xE4rdet"} att ha ${I}${D.maximum.toString()} ${j.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${D.origin??"v\xE4rdet"} att ha ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${D.origin??"v\xE4rdet"} att ha ${I}${D.minimum.toString()} ${j.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${D.origin??"v\xE4rdet"} att ha ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${I.prefix}"`;if(I.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${I.suffix}"`;if(I.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${I.includes}"`;if(I.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${I.pattern}"`;return`Ogiltig(t) ${g[I.format]??D.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${D.divisor}`;case"unrecognized_keys":return`${D.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${B(D.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${D.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${D.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var x5=f(()=>{c()});function mA(){return{localeError:uV()}}var uV=()=>{let _={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function $(D){return _[D]??null}let g={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${D.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${I}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`}case"invalid_value":if(D.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${F(D.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${B(D.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${D.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${I}${D.maximum.toString()} ${j.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${D.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${I}${D.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${D.origin} ${I}${D.minimum.toString()} ${j.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${D.origin} ${I}${D.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${I.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${g[I.format]??D.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${D.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${D.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${B(D.keys,", ")}`;case"invalid_key":return`${D.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${D.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};var y5=f(()=>{c()});function iA(){return{localeError:xV()}}var xV=()=>{let _={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function $(D){return _[D]??null}let g={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},U={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${D.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`;return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${I} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`}case"invalid_value":if(D.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${F(D.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",j=$(D.origin);if(j)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${D.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${D.maximum.toString()} ${j.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${D.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",j=$(D.origin);if(j)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${D.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${D.minimum.toString()} ${j.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${D.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${I.prefix}"`;if(I.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${I.suffix}"`;if(I.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${I.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(I.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${I.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${g[I.format]??D.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${D.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${B(D.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${D.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${D.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var h5=f(()=>{c()});function lA(){return{localeError:yV()}}var yV=()=>{let _={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function $(D){return _[D]??null}let g={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${D.expected}, al\u0131nan ${N}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${I}, al\u0131nan ${N}`}case"invalid_value":if(D.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${F(D.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\xC7ok b\xFCy\xFCk: beklenen ${D.origin??"de\u011Fer"} ${I}${D.maximum.toString()} ${j.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${D.origin??"de\u011Fer"} ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${D.origin} ${I}${D.minimum.toString()} ${j.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${D.origin} ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Ge\xE7ersiz metin: "${I.prefix}" ile ba\u015Flamal\u0131`;if(I.format==="ends_with")return`Ge\xE7ersiz metin: "${I.suffix}" ile bitmeli`;if(I.format==="includes")return`Ge\xE7ersiz metin: "${I.includes}" i\xE7ermeli`;if(I.format==="regex")return`Ge\xE7ersiz metin: ${I.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${g[I.format]??D.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${D.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${D.keys.length>1?"lar":""}: ${B(D.keys,", ")}`;case"invalid_key":return`${D.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${D.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var c5=f(()=>{c()});function AD(){return{localeError:hV()}}var hV=()=>{let _={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function $(D){return _[D]??null}let g={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${D.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${I}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`}case"invalid_value":if(D.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${F(D.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${D.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${j.verb} ${I}${D.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${D.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${D.origin} ${j.verb} ${I}${D.minimum.toString()} ${j.unit}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${D.origin} \u0431\u0443\u0434\u0435 ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${g[I.format]??D.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${D.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${D.keys.length>1?"\u0456":""}: ${B(D.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${D.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${D.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};var tA=f(()=>{c()});function oA(){return AD()}var n5=f(()=>{tA()});function pA(){return{localeError:cV()}}var cV=()=>{let _={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function $(D){return _[D]??null}let g={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},U={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${D.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${I} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(D.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${F(D.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${B(D.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${D.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${I}${D.maximum.toString()} ${j.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${D.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${I}${D.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${D.origin} \u06A9\u06D2 ${I}${D.minimum.toString()} ${j.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${D.origin} \u06A9\u0627 ${I}${D.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${I.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${g[I.format]??D.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${D.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${D.keys.length>1?"\u0632":""}: ${B(D.keys,"\u060C ")}`;case"invalid_key":return`${D.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${D.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var d5=f(()=>{c()});function eA(){return{localeError:nV()}}var nV=()=>{let _={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function $(D){return _[D]??null}let g={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},U={nan:"NaN",number:"raqam",array:"massiv"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${D.expected}, qabul qilingan ${N}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${I}, qabul qilingan ${N}`}case"invalid_value":if(D.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${F(D.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Juda katta: kutilgan ${D.origin??"qiymat"} ${I}${D.maximum.toString()} ${j.unit} ${j.verb}`;return`Juda katta: kutilgan ${D.origin??"qiymat"} ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Juda kichik: kutilgan ${D.origin} ${I}${D.minimum.toString()} ${j.unit} ${j.verb}`;return`Juda kichik: kutilgan ${D.origin} ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${I.prefix}" bilan boshlanishi kerak`;if(I.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${I.suffix}" bilan tugashi kerak`;if(I.format==="includes")return`Noto\u2018g\u2018ri satr: "${I.includes}" ni o\u2018z ichiga olishi kerak`;if(I.format==="regex")return`Noto\u2018g\u2018ri satr: ${I.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${g[I.format]??D.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${D.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${D.keys.length>1?"lar":""}: ${B(D.keys,", ")}`;case"invalid_key":return`${D.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${D.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var m5=f(()=>{c()});function aA(){return{localeError:dV()}}var dV=()=>{let _={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function $(D){return _[D]??null}let g={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},U={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${D.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${I}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`}case"invalid_value":if(D.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${F(D.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${D.origin??"gi\xE1 tr\u1ECB"} ${j.verb} ${I}${D.maximum.toString()} ${j.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${D.origin??"gi\xE1 tr\u1ECB"} ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${D.origin} ${j.verb} ${I}${D.minimum.toString()} ${j.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${D.origin} ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${I.prefix}"`;if(I.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${I.suffix}"`;if(I.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${I.includes}"`;if(I.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${I.pattern}`;return`${g[I.format]??D.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${D.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${B(D.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${D.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${D.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var i5=f(()=>{c()});function sA(){return{localeError:mV()}}var mV=()=>{let _={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function $(D){return _[D]??null}let g={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},U={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${D.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${I}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`}case"invalid_value":if(D.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${F(D.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${D.origin??"\u503C"} ${I}${D.maximum.toString()} ${j.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${D.origin??"\u503C"} ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${D.origin} ${I}${D.minimum.toString()} ${j.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${D.origin} ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${I.prefix}" \u5F00\u5934`;if(I.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${I.suffix}" \u7ED3\u5C3E`;if(I.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${I.includes}"`;if(I.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${I.pattern}`;return`\u65E0\u6548${g[I.format]??D.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${D.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${B(D.keys,", ")}`;case"invalid_key":return`${D.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${D.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var l5=f(()=>{c()});function _L(){return{localeError:iV()}}var iV=()=>{let _={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function $(D){return _[D]??null}let g={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},U={nan:"NaN"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${D.expected}\uFF0C\u4F46\u6536\u5230 ${N}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${I}\uFF0C\u4F46\u6536\u5230 ${N}`}case"invalid_value":if(D.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${F(D.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${D.origin??"\u503C"} \u61C9\u70BA ${I}${D.maximum.toString()} ${j.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${D.origin??"\u503C"} \u61C9\u70BA ${I}${D.maximum.toString()}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${D.origin} \u61C9\u70BA ${I}${D.minimum.toString()} ${j.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${D.origin} \u61C9\u70BA ${I}${D.minimum.toString()}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${I.prefix}" \u958B\u982D`;if(I.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${I.suffix}" \u7D50\u5C3E`;if(I.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${I.includes}"`;if(I.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${I.pattern}`;return`\u7121\u6548\u7684 ${g[I.format]??D.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${D.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${D.keys.length>1?"\u5011":""}\uFF1A${B(D.keys,"\u3001")}`;case"invalid_key":return`${D.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${D.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var t5=f(()=>{c()});function $L(){return{localeError:lV()}}var lV=()=>{let _={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function $(D){return _[D]??null}let g={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},U={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(D)=>{switch(D.code){case"invalid_type":{let I=U[D.expected]??D.expected,j=M(D.input),N=U[j]??j;if(/^[A-Z]/.test(D.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${D.expected}, \xE0m\u1ECD\u0300 a r\xED ${N}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${I}, \xE0m\u1ECD\u0300 a r\xED ${N}`}case"invalid_value":if(D.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${F(D.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${B(D.values,"|")}`;case"too_big":{let I=D.inclusive?"<=":"<",j=$(D.origin);if(j)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${D.origin??"iye"} ${j.verb} ${I}${D.maximum} ${j.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${I}${D.maximum}`}case"too_small":{let I=D.inclusive?">=":">",j=$(D.origin);if(j)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${D.origin} ${j.verb} ${I}${D.minimum} ${j.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${I}${D.minimum}`}case"invalid_format":{let I=D;if(I.format==="starts_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${I.prefix}"`;if(I.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${I.suffix}"`;if(I.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${I.includes}"`;if(I.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${I.pattern}`;return`A\u1E63\xEC\u1E63e: ${g[I.format]??D.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${D.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${B(D.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${D.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${D.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var o5=f(()=>{c()});var f0={};r$(f0,{zhTW:()=>_L,zhCN:()=>sA,yo:()=>$L,vi:()=>aA,uz:()=>eA,ur:()=>pA,uk:()=>AD,ua:()=>oA,tr:()=>lA,th:()=>iA,ta:()=>mA,sv:()=>dA,sl:()=>nA,ru:()=>cA,ro:()=>hA,pt:()=>yA,ps:()=>uA,pl:()=>xA,ota:()=>wA,no:()=>fA,nl:()=>vA,ms:()=>rA,mk:()=>CA,lt:()=>kA,ko:()=>HA,km:()=>ED,kh:()=>bA,ka:()=>MA,ja:()=>FA,it:()=>VA,is:()=>KA,id:()=>BA,hy:()=>qA,hu:()=>TA,hr:()=>QA,he:()=>YA,frCA:()=>GA,fr:()=>RA,fi:()=>XA,fa:()=>WA,es:()=>SA,eo:()=>zA,en:()=>ND,el:()=>JA,de:()=>LA,da:()=>AA,cs:()=>OA,ca:()=>EA,bg:()=>NA,be:()=>jA,az:()=>IA,ar:()=>UA});var gL=f(()=>{eX();aX();_5();$5();g5();D5();U5();I5();j5();PA();N5();E5();O5();A5();L5();J5();P5();z5();S5();X5();R5();G5();Y5();Q5();T5();q5();ZA();B5();V5();F5();M5();Z5();b5();H5();k5();C5();r5();v5();w5();u5();x5();y5();h5();c5();n5();tA();d5();m5();i5();l5();t5();o5()});class DL{constructor(){this._map=new WeakMap,this._idmap=new Map}add(_,...$){let g=$[0];if(this._map.set(_,g),g&&typeof g==="object"&&"id"in g)this._idmap.set(g.id,_);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(_){let $=this._map.get(_);if($&&typeof $==="object"&&"id"in $)this._idmap.delete($.id);return this._map.delete(_),this}get(_){let $=_._zod.parent;if($){let g={...this.get($)??{}};delete g.id;let U={...g,...this._map.get(_)};return Object.keys(U).length?U:void 0}return this._map.get(_)}has(_){return this._map.has(_)}}function LD(){return new DL}var p5,tI,oI,w_;var JD=f(()=>{tI=Symbol("ZodOutput"),oI=Symbol("ZodInput");(p5=globalThis).__zod_globalRegistry??(p5.__zod_globalRegistry=LD());w_=globalThis.__zod_globalRegistry});function UL(_,$){return new _({type:"string",...C($)})}function IL(_,$){return new _({type:"string",coerce:!0,...C($)})}function pI(_,$){return new _({type:"string",format:"email",check:"string_format",abort:!1,...C($)})}function PD(_,$){return new _({type:"string",format:"guid",check:"string_format",abort:!1,...C($)})}function eI(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,...C($)})}function aI(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C($)})}function sI(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C($)})}function _1(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C($)})}function zD(_,$){return new _({type:"string",format:"url",check:"string_format",abort:!1,...C($)})}function $1(_,$){return new _({type:"string",format:"emoji",check:"string_format",abort:!1,...C($)})}function g1(_,$){return new _({type:"string",format:"nanoid",check:"string_format",abort:!1,...C($)})}function D1(_,$){return new _({type:"string",format:"cuid",check:"string_format",abort:!1,...C($)})}function U1(_,$){return new _({type:"string",format:"cuid2",check:"string_format",abort:!1,...C($)})}function I1(_,$){return new _({type:"string",format:"ulid",check:"string_format",abort:!1,...C($)})}function j1(_,$){return new _({type:"string",format:"xid",check:"string_format",abort:!1,...C($)})}function N1(_,$){return new _({type:"string",format:"ksuid",check:"string_format",abort:!1,...C($)})}function E1(_,$){return new _({type:"string",format:"ipv4",check:"string_format",abort:!1,...C($)})}function O1(_,$){return new _({type:"string",format:"ipv6",check:"string_format",abort:!1,...C($)})}function jL(_,$){return new _({type:"string",format:"mac",check:"string_format",abort:!1,...C($)})}function A1(_,$){return new _({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C($)})}function L1(_,$){return new _({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C($)})}function J1(_,$){return new _({type:"string",format:"base64",check:"string_format",abort:!1,...C($)})}function P1(_,$){return new _({type:"string",format:"base64url",check:"string_format",abort:!1,...C($)})}function z1(_,$){return new _({type:"string",format:"e164",check:"string_format",abort:!1,...C($)})}function S1(_,$){return new _({type:"string",format:"jwt",check:"string_format",abort:!1,...C($)})}function NL(_,$){return new _({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C($)})}function EL(_,$){return new _({type:"string",format:"date",check:"string_format",...C($)})}function OL(_,$){return new _({type:"string",format:"time",check:"string_format",precision:null,...C($)})}function AL(_,$){return new _({type:"string",format:"duration",check:"string_format",...C($)})}function LL(_,$){return new _({type:"number",checks:[],...C($)})}function JL(_,$){return new _({type:"number",coerce:!0,checks:[],...C($)})}function PL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"safeint",...C($)})}function zL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float32",...C($)})}function SL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float64",...C($)})}function WL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"int32",...C($)})}function XL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"uint32",...C($)})}function RL(_,$){return new _({type:"boolean",...C($)})}function GL(_,$){return new _({type:"boolean",coerce:!0,...C($)})}function YL(_,$){return new _({type:"bigint",...C($)})}function QL(_,$){return new _({type:"bigint",coerce:!0,...C($)})}function TL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...C($)})}function qL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...C($)})}function BL(_,$){return new _({type:"symbol",...C($)})}function KL(_,$){return new _({type:"undefined",...C($)})}function VL(_,$){return new _({type:"null",...C($)})}function FL(_){return new _({type:"any"})}function ML(_){return new _({type:"unknown"})}function ZL(_,$){return new _({type:"never",...C($)})}function bL(_,$){return new _({type:"void",...C($)})}function HL(_,$){return new _({type:"date",...C($)})}function kL(_,$){return new _({type:"date",coerce:!0,...C($)})}function CL(_,$){return new _({type:"nan",...C($)})}function Q$(_,$){return new vI({check:"less_than",...C($),value:_,inclusive:!1})}function g$(_,$){return new vI({check:"less_than",...C($),value:_,inclusive:!0})}function T$(_,$){return new fI({check:"greater_than",...C($),value:_,inclusive:!1})}function h_(_,$){return new fI({check:"greater_than",...C($),value:_,inclusive:!0})}function SD(_){return T$(0,_)}function WD(_){return Q$(0,_)}function XD(_){return g$(0,_)}function RD(_){return h_(0,_)}function U6(_,$){return new F2({check:"multiple_of",...C($),value:_})}function I6(_,$){return new b2({check:"max_size",...C($),maximum:_})}function q$(_,$){return new H2({check:"min_size",...C($),minimum:_})}function k6(_,$){return new k2({check:"size_equals",...C($),size:_})}function C6(_,$){return new C2({check:"max_length",...C($),maximum:_})}function y$(_,$){return new r2({check:"min_length",...C($),minimum:_})}function r6(_,$){return new v2({check:"length_equals",...C($),length:_})}function W4(_,$){return new f2({check:"string_format",format:"regex",...C($),pattern:_})}function X4(_){return new w2({check:"string_format",format:"lowercase",...C(_)})}function R4(_){return new u2({check:"string_format",format:"uppercase",...C(_)})}function G4(_,$){return new x2({check:"string_format",format:"includes",...C($),includes:_})}function Y4(_,$){return new y2({check:"string_format",format:"starts_with",...C($),prefix:_})}function Q4(_,$){return new h2({check:"string_format",format:"ends_with",...C($),suffix:_})}function GD(_,$,g){return new c2({check:"property",property:_,schema:$,...C(g)})}function T4(_,$){return new n2({check:"mime_type",mime:_,...C($)})}function z$(_){return new d2({check:"overwrite",tx:_})}function q4(_){return z$(($)=>$.normalize(_))}function B4(){return z$((_)=>_.trim())}function K4(){return z$((_)=>_.toLowerCase())}function V4(){return z$((_)=>_.toUpperCase())}function F4(){return z$((_)=>yE(_))}function rL(_,$,g){return new _({type:"array",element:$,...C(g)})}function oV(_,$,g){return new _({type:"union",options:$,...C(g)})}function pV(_,$,g){return new _({type:"union",options:$,inclusive:!1,...C(g)})}function eV(_,$,g,U){return new _({type:"union",options:g,discriminator:$,...C(U)})}function aV(_,$,g){return new _({type:"intersection",left:$,right:g})}function sV(_,$,g,U){let D=g instanceof l;return new _({type:"tuple",items:$,rest:D?g:null,...C(D?U:g)})}function _F(_,$,g,U){return new _({type:"record",keyType:$,valueType:g,...C(U)})}function $F(_,$,g,U){return new _({type:"map",keyType:$,valueType:g,...C(U)})}function gF(_,$,g){return new _({type:"set",valueType:$,...C(g)})}function DF(_,$,g){let U=Array.isArray($)?Object.fromEntries($.map((D)=>[D,D])):$;return new _({type:"enum",entries:U,...C(g)})}function UF(_,$,g){return new _({type:"enum",entries:$,...C(g)})}function IF(_,$,g){return new _({type:"literal",values:Array.isArray($)?$:[$],...C(g)})}function vL(_,$){return new _({type:"file",...C($)})}function jF(_,$){return new _({type:"transform",transform:$})}function NF(_,$){return new _({type:"optional",innerType:$})}function EF(_,$){return new _({type:"nullable",innerType:$})}function OF(_,$,g){return new _({type:"default",innerType:$,get defaultValue(){return typeof g==="function"?g():cE(g)}})}function AF(_,$,g){return new _({type:"nonoptional",innerType:$,...C(g)})}function LF(_,$){return new _({type:"success",innerType:$})}function JF(_,$,g){return new _({type:"catch",innerType:$,catchValue:typeof g==="function"?g:()=>g})}function PF(_,$,g){return new _({type:"pipe",in:$,out:g})}function zF(_,$){return new _({type:"readonly",innerType:$})}function SF(_,$,g){return new _({type:"template_literal",parts:$,...C(g)})}function WF(_,$){return new _({type:"lazy",getter:$})}function XF(_,$){return new _({type:"promise",innerType:$})}function fL(_,$,g){let U=C(g);return U.abort??(U.abort=!0),new _({type:"custom",check:"custom",fn:$,...U})}function wL(_,$,g){return new _({type:"custom",check:"custom",fn:$,...C(g)})}function uL(_,$){let g=e5((U)=>{return U.addIssue=(D)=>{if(typeof D==="string")U.issues.push(F0(D,U.value,g._zod.def));else{let I=D;if(I.fatal)I.continue=!1;I.code??(I.code="custom"),I.input??(I.input=U.value),I.inst??(I.inst=g),I.continue??(I.continue=!g._zod.def.abort),U.issues.push(F0(I))}},_(U.value,U)},$);return g}function e5(_,$){let g=new Y_({check:"custom",...C($)});return g._zod.check=_,g}function xL(_){let $=new Y_({check:"describe"});return $._zod.onattach=[(g)=>{let U=w_.get(g)??{};w_.add(g,{...U,description:_})}],$._zod.check=()=>{},$}function yL(_){let $=new Y_({check:"meta"});return $._zod.onattach=[(g)=>{let U=w_.get(g)??{};w_.add(g,{...U,..._})}],$._zod.check=()=>{},$}function hL(_,$){let g=C($),U=g.truthy??["true","1","yes","on","y","enabled"],D=g.falsy??["false","0","no","off","n","disabled"];if(g.case!=="sensitive")U=U.map((J)=>typeof J==="string"?J.toLowerCase():J),D=D.map((J)=>typeof J==="string"?J.toLowerCase():J);let I=new Set(U),j=new Set(D),N=_.Codec??jD,O=_.Boolean??UD,L=new(_.String??S4)({type:"string",error:g.error}),z=new O({type:"boolean",error:g.error}),W=new N({type:"pipe",in:L,out:z,transform:(J,P)=>{let S=J;if(g.case!=="sensitive")S=S.toLowerCase();if(I.has(S))return!0;else if(j.has(S))return!1;else return P.issues.push({code:"invalid_value",expected:"stringbool",values:[...I,...j],input:P.value,inst:W,continue:!1}),{}},reverseTransform:(J,P)=>{if(J===!0)return U[0]||"true";else return D[0]||"false"},error:g.error});return W}function w0(_,$,g,U={}){let D=C(U),I={...C(U),check:"string_format",type:"string",format:$,fn:typeof g==="function"?g:(N)=>g.test(N),...D};if(g instanceof RegExp)I.pattern=g;return new _(I)}var W1;var a5=f(()=>{wI();JD();DA();c();W1={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function v6(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";return{processors:_.processors??{},metadataRegistry:_?.metadata??w_,target:$,unrepresentable:_?.unrepresentable??"throw",override:_?.override??(()=>{}),io:_?.io??"output",counter:0,seen:new Map,cycles:_?.cycles??"ref",reused:_?.reused??"inline",external:_?.external??void 0}}function A_(_,$,g={path:[],schemaPath:[]}){var U;let D=_._zod.def,I=$.seen.get(_);if(I){if(I.count++,g.schemaPath.includes(_))I.cycle=g.path;return I.schema}let j={schema:{},count:1,cycle:void 0,path:g.path};$.seen.set(_,j);let N=_._zod.toJSONSchema?.();if(N)j.schema=N;else{let L={...g,schemaPath:[...g.schemaPath,_],path:g.path};if(_._zod.processJSONSchema)_._zod.processJSONSchema($,j.schema,L);else{let W=j.schema,J=$.processors[D.type];if(!J)throw Error(`[toJSONSchema]: Non-representable type encountered: ${D.type}`);J(_,$,W,L)}let z=_._zod.parent;if(z){if(!j.ref)j.ref=z;A_(z,$,L),$.seen.get(z).isParent=!0}}let O=$.metadataRegistry.get(_);if(O)Object.assign(j.schema,O);if($.io==="input"&&t_(_))delete j.schema.examples,delete j.schema.default;if($.io==="input"&&"_prefault"in j.schema)(U=j.schema).default??(U.default=j.schema._prefault);return delete j.schema._prefault,$.seen.get(_).schema}function f6(_,$){let g=_.seen.get($);if(!g)throw Error("Unprocessed schema. This is a bug in Zod.");let U=new Map;for(let j of _.seen.entries()){let N=_.metadataRegistry.get(j[0])?.id;if(N){let O=U.get(N);if(O&&O!==j[0])throw Error(`Duplicate schema id "${N}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);U.set(N,j[0])}}let D=(j)=>{let N=_.target==="draft-2020-12"?"$defs":"definitions";if(_.external){let z=_.external.registry.get(j[0])?.id,W=_.external.uri??((P)=>P);if(z)return{ref:W(z)};let J=j[1].defId??j[1].schema.id??`schema${_.counter++}`;return j[1].defId=J,{defId:J,ref:`${W("__shared")}#/${N}/${J}`}}if(j[1]===g)return{ref:"#"};let A=`${"#"}/${N}/`,L=j[1].schema.id??`__schema${_.counter++}`;return{defId:L,ref:A+L}},I=(j)=>{if(j[1].schema.$ref)return;let N=j[1],{ref:O,defId:A}=D(j);if(N.def={...N.schema},A)N.defId=A;let L=N.schema;for(let z in L)delete L[z];L.$ref=O};if(_.cycles==="throw")for(let j of _.seen.entries()){let N=j[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let G of $.seen.entries()){let Y=G[1];if(_===G[0]){X(G);continue}if($.external){let q=$.external.registry.get(G[0])?.id;if(_!==G[0]&&q){X(G);continue}}if($.metadataRegistry.get(G[0])?.id){X(G);continue}if(Y.cycle){X(G);continue}if(Y.count>1){if($.reused==="ref"){X(G);continue}}}}function y0($,_){let J=$.seen.get(_);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(Y)=>{let Q=$.seen.get(Y);if(Q.ref===null)return;let q=Q.def??Q.schema,L={...q},N=Q.ref;if(Q.ref=null,N){U(N);let B=$.seen.get(N),H=B.schema;if(H.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))q.allOf=q.allOf??[],q.allOf.push(H);else Object.assign(q,H);if(Object.assign(q,L),Y._zod.parent===N)for(let K in q){if(K==="$ref"||K==="allOf")continue;if(!(K in L))delete q[K]}if(H.$ref&&B.def)for(let K in q){if(K==="$ref"||K==="allOf")continue;if(K in B.def&&JSON.stringify(q[K])===JSON.stringify(B.def[K]))delete q[K]}}let R=Y._zod.parent;if(R&&R!==N){U(R);let B=$.seen.get(R);if(B?.schema.$ref){if(q.$ref=B.schema.$ref,B.def)for(let H in q){if(H==="$ref"||H==="allOf")continue;if(H in B.def&&JSON.stringify(q[H])===JSON.stringify(B.def[H]))delete q[H]}}}$.override({zodSchema:Y,jsonSchema:q,path:Q.path??[]})};for(let Y of[...$.seen.entries()].reverse())U(Y[0]);let W={};if($.target==="draft-2020-12")W.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")W.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let Y=$.external.registry.get(_)?.id;if(!Y)throw Error("Schema is missing an `id` property");W.$id=$.external.uri(Y)}Object.assign(W,J.def??J.schema);let X=$.metadataRegistry.get(_)?.id;if(X!==void 0&&W.id===X)delete W.id;let G=$.external?.defs??{};for(let Y of $.seen.entries()){let Q=Y[1];if(Q.def&&Q.defId){if(Q.def.id===Q.defId)delete Q.def.id;G[Q.defId]=Q.def}}if($.external);else if(Object.keys(G).length>0)if($.target==="draft-2020-12")W.$defs=G;else W.definitions=G;try{let Y=JSON.parse(JSON.stringify(W));return Object.defineProperty(Y,"~standard",{value:{..._["~standard"],jsonSchema:{input:JW(_,"input",$.processors),output:JW(_,"output",$.processors)}},enumerable:!1,writable:!1}),Y}catch(Y){throw Error("Error converting schema to JSON.")}}function c_($,_){let J=_??{seen:new Set};if(J.seen.has($))return!1;J.seen.add($);let U=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return c_(U.element,J);if(U.type==="set")return c_(U.valueType,J);if(U.type==="lazy")return c_(U.getter(),J);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return c_(U.innerType,J);if(U.type==="intersection")return c_(U.left,J)||c_(U.right,J);if(U.type==="record"||U.type==="map")return c_(U.keyType,J)||c_(U.valueType,J);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return c_(U.in,J)||c_(U.out,J)}if(U.type==="object"){for(let W in U.shape)if(c_(U.shape[W],J))return!0;return!1}if(U.type==="union"){for(let W of U.options)if(c_(W,J))return!0;return!1}if(U.type==="tuple"){for(let W of U.items)if(c_(W,J))return!0;if(U.rest&&c_(U.rest,J))return!0;return!1}return!1}var zD=($,_={})=>(J)=>{let U=Z0({...J,processors:_});return l$($,U),v0(U,$),y0(U,$)},JW=($,_,J={})=>(U)=>{let{libraryOptions:W,target:X}=U??{},G=Z0({...W??{},target:X,io:_,processors:J});return l$($,G),v0(G,$),y0(G,$)};var UX=x(()=>{tU()});function XX($,_){if("_idmap"in $){let U=$,W=Z0({..._,processors:O5}),X={};for(let Q of U._idmap.entries()){let[q,L]=Q;l$(L,W)}let G={},Y={registry:U,uri:_?.uri,defs:X};W.external=Y;for(let Q of U._idmap.entries()){let[q,L]=Q;v0(W,L),G[q]=y0(W,L)}if(Object.keys(X).length>0){let Q=W.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[Q]:X}}return{schemas:G}}let J=Z0({..._,processors:O5});return l$($,J),v0(J,$),y0(J,$)}var gu,jD=($,_,J,U)=>{let W=J;W.type="string";let{minimum:X,maximum:G,format:Y,patterns:Q,contentEncoding:q}=$._zod.bag;if(typeof X==="number")W.minLength=X;if(typeof G==="number")W.maxLength=G;if(Y){if(W.format=gu[Y]??Y,W.format==="")delete W.format;if(Y==="time")delete W.format}if(q)W.contentEncoding=q;if(Q&&Q.size>0){let L=[...Q];if(L.length===1)W.pattern=L[0].source;else if(L.length>1)W.allOf=[...L.map((N)=>({..._.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"?{type:"string"}:{},pattern:N.source}))]}},DD=($,_,J,U)=>{let W=J,{minimum:X,maximum:G,format:Y,multipleOf:Q,exclusiveMaximum:q,exclusiveMinimum:L}=$._zod.bag;if(typeof Y==="string"&&Y.includes("int"))W.type="integer";else W.type="number";let N=typeof L==="number"&&L>=(X??Number.NEGATIVE_INFINITY),R=typeof q==="number"&&q<=(G??Number.POSITIVE_INFINITY),B=_.target==="draft-04"||_.target==="openapi-3.0";if(N)if(B)W.minimum=L,W.exclusiveMinimum=!0;else W.exclusiveMinimum=L;else if(typeof X==="number")W.minimum=X;if(R)if(B)W.maximum=q,W.exclusiveMaximum=!0;else W.exclusiveMaximum=q;else if(typeof G==="number")W.maximum=G;if(typeof Q==="number")W.multipleOf=Q},OD=($,_,J,U)=>{J.type="boolean"},LD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},BD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},HD=($,_,J,U)=>{if(_.target==="openapi-3.0")J.type="string",J.nullable=!0,J.enum=[null];else J.type="null"},ND=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},VD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},RD=($,_,J,U)=>{J.not={}},KD=($,_,J,U)=>{},FD=($,_,J,U)=>{},ED=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},MD=($,_,J,U)=>{let W=$._zod.def,X=TU(W.entries);if(X.every((G)=>typeof G==="number"))J.type="number";if(X.every((G)=>typeof G==="string"))J.type="string";J.enum=X},AD=($,_,J,U)=>{let W=$._zod.def,X=[];for(let G of W.values)if(G===void 0){if(_.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof G==="bigint")if(_.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else X.push(Number(G));else X.push(G);if(X.length===0);else if(X.length===1){let G=X[0];if(J.type=G===null?"null":typeof G,_.target==="draft-04"||_.target==="openapi-3.0")J.enum=[G];else J.const=G}else{if(X.every((G)=>typeof G==="number"))J.type="number";if(X.every((G)=>typeof G==="string"))J.type="string";if(X.every((G)=>typeof G==="boolean"))J.type="boolean";if(X.every((G)=>G===null))J.type="null";J.enum=X}},bD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},wD=($,_,J,U)=>{let W=J,X=$._zod.pattern;if(!X)throw Error("Pattern not found in template literal");W.type="string",W.pattern=X.source},gD=($,_,J,U)=>{let W=J,X={type:"string",format:"binary",contentEncoding:"binary"},{minimum:G,maximum:Y,mime:Q}=$._zod.bag;if(G!==void 0)X.minLength=G;if(Y!==void 0)X.maxLength=Y;if(Q)if(Q.length===1)X.contentMediaType=Q[0],Object.assign(W,X);else Object.assign(W,X),W.anyOf=Q.map((q)=>({contentMediaType:q}));else Object.assign(W,X)},kD=($,_,J,U)=>{J.type="boolean"},ID=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},fD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},CD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},PD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},TD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},SD=($,_,J,U)=>{let W=J,X=$._zod.def,{minimum:G,maximum:Y}=$._zod.bag;if(typeof G==="number")W.minItems=G;if(typeof Y==="number")W.maxItems=Y;W.type="array",W.items=l$(X.element,_,{...U,path:[...U.path,"items"]})},ZD=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="object",W.properties={};let G=X.shape;for(let q in G)W.properties[q]=l$(G[q],_,{...U,path:[...U.path,"properties",q]});let Y=new Set(Object.keys(G)),Q=new Set([...Y].filter((q)=>{let L=X.shape[q]._zod;if(_.io==="input")return L.optin===void 0;else return L.optout===void 0}));if(Q.size>0)W.required=Array.from(Q);if(X.catchall?._zod.def.type==="never")W.additionalProperties=!1;else if(!X.catchall){if(_.io==="output")W.additionalProperties=!1}else if(X.catchall)W.additionalProperties=l$(X.catchall,_,{...U,path:[...U.path,"additionalProperties"]})},L5=($,_,J,U)=>{let W=$._zod.def,X=W.inclusive===!1,G=W.options.map((Y,Q)=>l$(Y,_,{...U,path:[...U.path,X?"oneOf":"anyOf",Q]}));if(X)J.oneOf=G;else J.anyOf=G},vD=($,_,J,U)=>{let W=$._zod.def,X=l$(W.left,_,{...U,path:[...U.path,"allOf",0]}),G=l$(W.right,_,{...U,path:[...U.path,"allOf",1]}),Y=(q)=>("allOf"in q)&&Object.keys(q).length===1,Q=[...Y(X)?X.allOf:[X],...Y(G)?G.allOf:[G]];J.allOf=Q},yD=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="array";let G=_.target==="draft-2020-12"?"prefixItems":"items",Y=_.target==="draft-2020-12"?"items":_.target==="openapi-3.0"?"items":"additionalItems",Q=X.items.map((R,B)=>l$(R,_,{...U,path:[...U.path,G,B]})),q=X.rest?l$(X.rest,_,{...U,path:[...U.path,Y,..._.target==="openapi-3.0"?[X.items.length]:[]]}):null;if(_.target==="draft-2020-12"){if(W.prefixItems=Q,q)W.items=q}else if(_.target==="openapi-3.0"){if(W.items={anyOf:Q},q)W.items.anyOf.push(q);if(W.minItems=Q.length,!q)W.maxItems=Q.length}else if(W.items=Q,q)W.additionalItems=q;let{minimum:L,maximum:N}=$._zod.bag;if(typeof L==="number")W.minItems=L;if(typeof N==="number")W.maxItems=N},hD=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="object";let G=X.keyType,Q=G._zod.bag?.patterns;if(X.mode==="loose"&&Q&&Q.size>0){let L=l$(X.valueType,_,{...U,path:[...U.path,"patternProperties","*"]});W.patternProperties={};for(let N of Q)W.patternProperties[N.source]=L}else{if(_.target==="draft-07"||_.target==="draft-2020-12")W.propertyNames=l$(X.keyType,_,{...U,path:[...U.path,"propertyNames"]});W.additionalProperties=l$(X.valueType,_,{...U,path:[...U.path,"additionalProperties"]})}let q=G._zod.values;if(q){let L=[...q].filter((N)=>typeof N==="string"||typeof N==="number");if(L.length>0)W.required=L}},mD=($,_,J,U)=>{let W=$._zod.def,X=l$(W.innerType,_,U),G=_.seen.get($);if(_.target==="openapi-3.0")G.ref=W.innerType,J.nullable=!0;else J.anyOf=[X,{type:"null"}]},xD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},uD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType,J.default=JSON.parse(JSON.stringify(W.defaultValue))},dD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);if(X.ref=W.innerType,_.io==="input")J._prefault=JSON.parse(JSON.stringify(W.defaultValue))},nD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType;let G;try{G=W.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}J.default=G},cD=($,_,J,U)=>{let W=$._zod.def,X=W.in._zod.traits.has("$ZodTransform"),G=_.io==="input"?X?W.out:W.in:W.out;l$(G,_,U);let Y=_.seen.get($);Y.ref=G},iD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType,J.readOnly=!0},lD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},B5=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},rD=($,_,J,U)=>{let W=$._zod.innerType;l$(W,_,U);let X=_.seen.get($);X.ref=W},O5;var GX=x(()=>{UX();e();gu={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},O5={string:jD,number:DD,boolean:OD,bigint:LD,symbol:BD,null:HD,undefined:ND,void:VD,never:RD,any:KD,unknown:FD,date:ED,enum:MD,literal:AD,nan:bD,template_literal:wD,file:gD,success:kD,custom:ID,function:fD,transform:CD,map:PD,set:TD,array:SD,object:ZD,union:L5,intersection:vD,tuple:yD,record:hD,nullable:mD,nonoptional:xD,default:uD,prefault:dD,catch:nD,pipe:cD,readonly:iD,promise:lD,optional:B5,lazy:rD}});class pD{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let _=$?.target??"draft-2020-12";if(_==="draft-4")_="draft-04";if(_==="draft-7")_="draft-07";this.ctx=Z0({processors:O5,target:_,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,_={path:[],schemaPath:[]}){return l$($,this.ctx,_)}emit($,_){if(_){if(_.cycles)this.ctx.cycles=_.cycles;if(_.reused)this.ctx.reused=_.reused;if(_.external)this.ctx.external=_.external}v0(this.ctx,$);let J=y0(this.ctx,$),{"~standard":U,...W}=J;return W}}var dK=x(()=>{GX();UX()});var nK={};var cK=()=>{};var B4={};e6(B4,{version:()=>O7,util:()=>C,treeifyError:()=>N8,toJSONSchema:()=>XX,toDotPath:()=>LR,safeParseAsync:()=>Vq,safeParse:()=>Nq,safeEncodeAsync:()=>fm,safeEncode:()=>km,safeDecodeAsync:()=>Cm,safeDecode:()=>Im,registry:()=>oU,regexes:()=>t_,process:()=>l$,prettifyError:()=>V8,parseAsync:()=>K8,parse:()=>R8,meta:()=>QD,locales:()=>$W,isValidJWT:()=>vR,isValidBase64URL:()=>ZR,isValidBase64:()=>v7,initializeContext:()=>Z0,globalRegistry:()=>g_,globalConfig:()=>T1,formatError:()=>rJ,flattenError:()=>lJ,finalize:()=>y0,extractDefs:()=>v0,encodeAsync:()=>wm,encode:()=>Am,describe:()=>YD,decodeAsync:()=>gm,decode:()=>bm,createToJSONSchemaMethod:()=>zD,createStandardJSONSchemaMethod:()=>JW,config:()=>V_,clone:()=>T_,_xor:()=>Xu,_xid:()=>J5,_void:()=>sj,_uuidv7:()=>t8,_uuidv6:()=>o8,_uuidv4:()=>p8,_uuid:()=>r8,_url:()=>sU,_uppercase:()=>u1,_unknown:()=>tj,_union:()=>Uu,_undefined:()=>rj,_ulid:()=>_5,_uint64:()=>ij,_uint32:()=>mj,_tuple:()=>Qu,_trim:()=>r1,_transform:()=>Bu,_toUpperCase:()=>o1,_toLowerCase:()=>p1,_templateLiteral:()=>Au,_symbol:()=>lj,_superRefine:()=>GD,_success:()=>Ku,_stringbool:()=>qD,_stringFormat:()=>_W,_string:()=>wj,_startsWith:()=>n1,_slugify:()=>t1,_size:()=>P0,_set:()=>ju,_safeParseAsync:()=>aJ,_safeParse:()=>tJ,_safeEncodeAsync:()=>g8,_safeEncode:()=>b8,_safeDecodeAsync:()=>k8,_safeDecode:()=>w8,_regex:()=>m1,_refine:()=>XD,_record:()=>qu,_readonly:()=>Mu,_property:()=>WX,_promise:()=>wu,_positive:()=>eU,_pipe:()=>Eu,_parseAsync:()=>oJ,_parse:()=>pJ,_overwrite:()=>R6,_optional:()=>Hu,_number:()=>Tj,_nullable:()=>Nu,_null:()=>pj,_normalize:()=>l1,_nonpositive:()=>_X,_nonoptional:()=>Ru,_nonnegative:()=>JX,_never:()=>aj,_negative:()=>$X,_nativeEnum:()=>Ou,_nanoid:()=>s8,_nan:()=>_D,_multipleOf:()=>l4,_minSize:()=>u6,_minLength:()=>L4,_min:()=>S_,_mime:()=>i1,_maxSize:()=>r4,_maxLength:()=>T0,_max:()=>a_,_map:()=>zu,_mac:()=>kj,_lte:()=>a_,_lt:()=>m6,_lowercase:()=>x1,_literal:()=>Lu,_length:()=>S0,_lazy:()=>bu,_ksuid:()=>W5,_jwt:()=>j5,_isoTime:()=>Cj,_isoDuration:()=>Pj,_isoDateTime:()=>Ij,_isoDate:()=>fj,_ipv6:()=>X5,_ipv4:()=>U5,_intersection:()=>Yu,_int64:()=>cj,_int32:()=>hj,_int:()=>Zj,_includes:()=>d1,_guid:()=>aU,_gte:()=>S_,_gt:()=>x6,_float64:()=>yj,_float32:()=>vj,_file:()=>WD,_enum:()=>Du,_endsWith:()=>c1,_encodeAsync:()=>M8,_encode:()=>F8,_emoji:()=>a8,_email:()=>l8,_e164:()=>z5,_discriminatedUnion:()=>Gu,_default:()=>Vu,_decodeAsync:()=>A8,_decode:()=>E8,_date:()=>ej,_custom:()=>UD,_cuid2:()=>$5,_cuid:()=>e8,_coercedString:()=>gj,_coercedNumber:()=>Sj,_coercedDate:()=>$D,_coercedBoolean:()=>uj,_coercedBigint:()=>nj,_cidrv6:()=>Y5,_cidrv4:()=>G5,_check:()=>xK,_catch:()=>Fu,_boolean:()=>xj,_bigint:()=>dj,_base64url:()=>q5,_base64:()=>Q5,_array:()=>JD,_any:()=>oj,TimePrecision:()=>D5,NEVER:()=>O8,JSONSchemaGenerator:()=>pD,JSONSchema:()=>nK,Doc:()=>S8,$output:()=>c8,$input:()=>i8,$constructor:()=>M,$brand:()=>L8,$ZodXor:()=>$z,$ZodXID:()=>b7,$ZodVoid:()=>t7,$ZodUnknown:()=>p7,$ZodUnion:()=>nU,$ZodUndefined:()=>i7,$ZodUUID:()=>N7,$ZodURL:()=>R7,$ZodULID:()=>A7,$ZodType:()=>R$,$ZodTuple:()=>u8,$ZodTransform:()=>qz,$ZodTemplateLiteral:()=>Kz,$ZodSymbol:()=>c7,$ZodSuccess:()=>Bz,$ZodStringFormat:()=>J_,$ZodString:()=>h1,$ZodSet:()=>Xz,$ZodRegistry:()=>bj,$ZodRecord:()=>Wz,$ZodRealError:()=>o_,$ZodReadonly:()=>Rz,$ZodPromise:()=>Ez,$ZodPreprocess:()=>Vz,$ZodPrefault:()=>Oz,$ZodPipe:()=>n8,$ZodOptional:()=>d8,$ZodObjectJIT:()=>e7,$ZodObject:()=>mR,$ZodNumberFormat:()=>d7,$ZodNumber:()=>m8,$ZodNullable:()=>jz,$ZodNull:()=>l7,$ZodNonOptional:()=>Lz,$ZodNever:()=>o7,$ZodNanoID:()=>F7,$ZodNaN:()=>Nz,$ZodMap:()=>Uz,$ZodMAC:()=>T7,$ZodLiteral:()=>Yz,$ZodLazy:()=>Mz,$ZodKSUID:()=>w7,$ZodJWT:()=>x7,$ZodIntersection:()=>Jz,$ZodISOTime:()=>I7,$ZodISODuration:()=>f7,$ZodISODateTime:()=>g7,$ZodISODate:()=>k7,$ZodIPv6:()=>P7,$ZodIPv4:()=>C7,$ZodGUID:()=>H7,$ZodFunction:()=>Fz,$ZodFile:()=>Qz,$ZodExactOptional:()=>zz,$ZodError:()=>hU,$ZodEnum:()=>Gz,$ZodEncodeError:()=>S1,$ZodEmoji:()=>K7,$ZodEmail:()=>V7,$ZodE164:()=>m7,$ZodDiscriminatedUnion:()=>_z,$ZodDefault:()=>Dz,$ZodDate:()=>a7,$ZodCustomStringFormat:()=>u7,$ZodCustom:()=>Az,$ZodCodec:()=>cU,$ZodCheckUpperCase:()=>G7,$ZodCheckStringFormat:()=>sJ,$ZodCheckStartsWith:()=>Q7,$ZodCheckSizeEquals:()=>$7,$ZodCheckRegex:()=>U7,$ZodCheckProperty:()=>z7,$ZodCheckOverwrite:()=>D7,$ZodCheckNumberFormat:()=>tq,$ZodCheckMultipleOf:()=>oq,$ZodCheckMinSize:()=>eq,$ZodCheckMinLength:()=>J7,$ZodCheckMimeType:()=>j7,$ZodCheckMaxSize:()=>sq,$ZodCheckMaxLength:()=>_7,$ZodCheckLowerCase:()=>X7,$ZodCheckLessThan:()=>C8,$ZodCheckLengthEquals:()=>W7,$ZodCheckIncludes:()=>Y7,$ZodCheckGreaterThan:()=>P8,$ZodCheckEndsWith:()=>q7,$ZodCheckBigIntFormat:()=>aq,$ZodCheck:()=>X_,$ZodCatch:()=>Hz,$ZodCUID2:()=>M7,$ZodCUID:()=>E7,$ZodCIDRv6:()=>Z7,$ZodCIDRv4:()=>S7,$ZodBoolean:()=>dU,$ZodBigIntFormat:()=>n7,$ZodBigInt:()=>x8,$ZodBase64URL:()=>h7,$ZodBase64:()=>y7,$ZodAsyncError:()=>O4,$ZodArray:()=>s7,$ZodAny:()=>r7});var Q6=x(()=>{e();f8();Aj();GX();dK();cK();Z1();Rq();Hq();bz();T8();L7();tU();uK();UX()});var H5={};e6(H5,{uppercase:()=>u1,trim:()=>r1,toUpperCase:()=>o1,toLowerCase:()=>p1,startsWith:()=>n1,slugify:()=>t1,size:()=>P0,regex:()=>m1,property:()=>WX,positive:()=>eU,overwrite:()=>R6,normalize:()=>l1,nonpositive:()=>_X,nonnegative:()=>JX,negative:()=>$X,multipleOf:()=>l4,minSize:()=>u6,minLength:()=>L4,mime:()=>i1,maxSize:()=>r4,maxLength:()=>T0,lte:()=>a_,lt:()=>m6,lowercase:()=>x1,length:()=>S0,includes:()=>d1,gte:()=>S_,gt:()=>x6,endsWith:()=>c1});var N5=x(()=>{Q6()});var a1={};e6(a1,{time:()=>aD,duration:()=>sD,datetime:()=>oD,date:()=>tD,ZodISOTime:()=>qX,ZodISODuration:()=>zX,ZodISODateTime:()=>YX,ZodISODate:()=>QX});function oD($){return Ij(YX,$)}function tD($){return fj(QX,$)}function aD($){return Cj(qX,$)}function sD($){return Pj(zX,$)}var YX,QX,qX,zX;var jX=x(()=>{Q6();OX();YX=M("ZodISODateTime",($,_)=>{g7.init($,_),a$.init($,_)});QX=M("ZodISODate",($,_)=>{k7.init($,_),a$.init($,_)});qX=M("ZodISOTime",($,_)=>{I7.init($,_),a$.init($,_)});zX=M("ZodISODuration",($,_)=>{f7.init($,_),a$.init($,_)})});var iK=($,_)=>{hU.init($,_),$.name="ZodError",Object.defineProperties($,{format:{value:(J)=>rJ($,J)},flatten:{value:(J)=>lJ($,J)},addIssue:{value:(J)=>{$.issues.push(J),$.message=JSON.stringify($.issues,nJ,2)}},addIssues:{value:(J)=>{$.issues.push(...J),$.message=JSON.stringify($.issues,nJ,2)}},isEmpty:{get(){return $.issues.length===0}}})},lK,i_;var eD=x(()=>{Q6();Q6();e();lK=M("ZodError",iK),i_=M("ZodError",iK,{Parent:Error})});var V5,R5,K5,F5,E5,M5,A5,b5,w5,g5,k5,I5;var $O=x(()=>{Q6();eD();V5=pJ(i_),R5=oJ(i_),K5=tJ(i_),F5=aJ(i_),E5=F8(i_),M5=E8(i_),A5=M8(i_),b5=A8(i_),w5=b8(i_),g5=w8(i_),k5=g8(i_),I5=k8(i_)});var DX={};e6(DX,{xor:()=>iO,xid:()=>LO,void:()=>mO,uuidv7:()=>GO,uuidv6:()=>XO,uuidv4:()=>UO,uuid:()=>WO,url:()=>YO,unknown:()=>h0,union:()=>vX,undefined:()=>yO,ulid:()=>OO,uint64:()=>ZO,uint32:()=>PO,tuple:()=>r5,transform:()=>hX,templateLiteral:()=>XL,symbol:()=>vO,superRefine:()=>FG,success:()=>_L,stringbool:()=>OL,stringFormat:()=>bO,string:()=>WW,strictObject:()=>nO,set:()=>tO,refine:()=>KG,record:()=>p5,readonly:()=>LG,promise:()=>GL,preprocess:()=>BL,prefault:()=>GG,pipe:()=>BX,partialRecord:()=>rO,optional:()=>XW,object:()=>dO,number:()=>C5,nullish:()=>$L,nullable:()=>GW,null:()=>v5,nonoptional:()=>YG,never:()=>ZX,nativeEnum:()=>aO,nanoid:()=>zO,nan:()=>JL,meta:()=>jL,map:()=>oO,mac:()=>NO,looseRecord:()=>pO,looseObject:()=>cO,literal:()=>sO,lazy:()=>NG,ksuid:()=>BO,keyof:()=>uO,jwt:()=>AO,json:()=>LL,ipv6:()=>VO,ipv4:()=>HO,invertCodec:()=>UL,intersection:()=>i5,int64:()=>SO,int32:()=>CO,int:()=>LX,instanceof:()=>DL,httpUrl:()=>QO,hostname:()=>wO,hex:()=>gO,hash:()=>kO,guid:()=>JO,function:()=>YL,float64:()=>fO,float32:()=>IO,file:()=>eO,exactOptional:()=>_G,enum:()=>yX,emoji:()=>qO,email:()=>_O,e164:()=>MO,discriminatedUnion:()=>lO,describe:()=>zL,date:()=>xO,custom:()=>qL,cuid2:()=>DO,cuid:()=>jO,codec:()=>WL,cidrv6:()=>KO,cidrv4:()=>RO,check:()=>QL,catch:()=>zG,boolean:()=>P5,bigint:()=>TO,base64url:()=>EO,base64:()=>FO,array:()=>qW,any:()=>hO,_function:()=>YL,_default:()=>UG,_ZodString:()=>NX,ZodXor:()=>d5,ZodXID:()=>AX,ZodVoid:()=>x5,ZodUnknown:()=>h5,ZodUnion:()=>jW,ZodUndefined:()=>S5,ZodUUID:()=>d6,ZodURL:()=>YW,ZodULID:()=>MX,ZodType:()=>F$,ZodTuple:()=>l5,ZodTransform:()=>e5,ZodTemplateLiteral:()=>BG,ZodSymbol:()=>T5,ZodSuccess:()=>QG,ZodStringFormat:()=>a$,ZodString:()=>$2,ZodSet:()=>t5,ZodRecord:()=>s1,ZodReadonly:()=>OG,ZodPromise:()=>VG,ZodPreprocess:()=>DG,ZodPrefault:()=>XG,ZodPipe:()=>DW,ZodOptional:()=>mX,ZodObject:()=>zW,ZodNumberFormat:()=>m0,ZodNumber:()=>J2,ZodNullable:()=>JG,ZodNull:()=>Z5,ZodNonOptional:()=>xX,ZodNever:()=>m5,ZodNanoID:()=>KX,ZodNaN:()=>jG,ZodMap:()=>o5,ZodMAC:()=>f5,ZodLiteral:()=>a5,ZodLazy:()=>HG,ZodKSUID:()=>bX,ZodJWT:()=>TX,ZodIntersection:()=>c5,ZodIPv6:()=>gX,ZodIPv4:()=>wX,ZodGUID:()=>UW,ZodFunction:()=>RG,ZodFile:()=>s5,ZodExactOptional:()=>$G,ZodEnum:()=>e1,ZodEmoji:()=>RX,ZodEmail:()=>VX,ZodE164:()=>PX,ZodDiscriminatedUnion:()=>n5,ZodDefault:()=>WG,ZodDate:()=>QW,ZodCustomStringFormat:()=>_2,ZodCustom:()=>LW,ZodCodec:()=>OW,ZodCatch:()=>qG,ZodCUID2:()=>EX,ZodCUID:()=>FX,ZodCIDRv6:()=>IX,ZodCIDRv4:()=>kX,ZodBoolean:()=>W2,ZodBigIntFormat:()=>SX,ZodBigInt:()=>U2,ZodBase64URL:()=>CX,ZodBase64:()=>fX,ZodArray:()=>u5,ZodAny:()=>y5});function HX($,_,J){let U=Object.getPrototypeOf($),W=rK.get(U);if(!W)W=new Set,rK.set(U,W);if(W.has(_))return;W.add(_);for(let X in J){let G=J[X];Object.defineProperty(U,X,{configurable:!0,enumerable:!1,get(){let Y=G.bind(this);return Object.defineProperty(this,X,{configurable:!0,writable:!0,enumerable:!0,value:Y}),Y},set(Y){Object.defineProperty(this,X,{configurable:!0,writable:!0,enumerable:!0,value:Y})}})}}function WW($){return wj($2,$)}function _O($){return l8(VX,$)}function JO($){return aU(UW,$)}function WO($){return r8(d6,$)}function UO($){return p8(d6,$)}function XO($){return o8(d6,$)}function GO($){return t8(d6,$)}function YO($){return sU(YW,$)}function QO($){return sU(YW,{protocol:t_.httpProtocol,hostname:t_.domain,...C.normalizeParams($)})}function qO($){return a8(RX,$)}function zO($){return s8(KX,$)}function jO($){return e8(FX,$)}function DO($){return $5(EX,$)}function OO($){return _5(MX,$)}function LO($){return J5(AX,$)}function BO($){return W5(bX,$)}function HO($){return U5(wX,$)}function NO($){return kj(f5,$)}function VO($){return X5(gX,$)}function RO($){return G5(kX,$)}function KO($){return Y5(IX,$)}function FO($){return Q5(fX,$)}function EO($){return q5(CX,$)}function MO($){return z5(PX,$)}function AO($){return j5(TX,$)}function bO($,_,J={}){return _W(_2,$,_,J)}function wO($){return _W(_2,"hostname",t_.hostname,$)}function gO($){return _W(_2,"hex",t_.hex,$)}function kO($,_){let J=_?.enc??"hex",U=`${$}_${J}`,W=t_[U];if(!W)throw Error(`Unrecognized hash format: ${U}`);return _W(_2,U,W,_)}function C5($){return Tj(J2,$)}function LX($){return Zj(m0,$)}function IO($){return vj(m0,$)}function fO($){return yj(m0,$)}function CO($){return hj(m0,$)}function PO($){return mj(m0,$)}function P5($){return xj(W2,$)}function TO($){return dj(U2,$)}function SO($){return cj(SX,$)}function ZO($){return ij(SX,$)}function vO($){return lj(T5,$)}function yO($){return rj(S5,$)}function v5($){return pj(Z5,$)}function hO(){return oj(y5)}function h0(){return tj(h5)}function ZX($){return aj(m5,$)}function mO($){return sj(x5,$)}function xO($){return ej(QW,$)}function qW($,_){return JD(u5,$,_)}function uO($){let _=$._zod.def.shape;return yX(Object.keys(_))}function dO($,_){let J={type:"object",shape:$??{},...C.normalizeParams(_)};return new zW(J)}function nO($,_){return new zW({type:"object",shape:$,catchall:ZX(),...C.normalizeParams(_)})}function cO($,_){return new zW({type:"object",shape:$,catchall:h0(),...C.normalizeParams(_)})}function vX($,_){return new jW({type:"union",options:$,...C.normalizeParams(_)})}function iO($,_){return new d5({type:"union",options:$,inclusive:!1,...C.normalizeParams(_)})}function lO($,_,J){return new n5({type:"union",options:_,discriminator:$,...C.normalizeParams(J)})}function i5($,_){return new c5({type:"intersection",left:$,right:_})}function r5($,_,J){let U=_ instanceof R$,W=U?J:_;return new l5({type:"tuple",items:$,rest:U?_:null,...C.normalizeParams(W)})}function p5($,_,J){if(!_||!_._zod)return new s1({type:"record",keyType:WW(),valueType:$,...C.normalizeParams(_)});return new s1({type:"record",keyType:$,valueType:_,...C.normalizeParams(J)})}function rO($,_,J){let U=T_($);return U._zod.values=void 0,new s1({type:"record",keyType:U,valueType:_,...C.normalizeParams(J)})}function pO($,_,J){return new s1({type:"record",keyType:$,valueType:_,mode:"loose",...C.normalizeParams(J)})}function oO($,_,J){return new o5({type:"map",keyType:$,valueType:_,...C.normalizeParams(J)})}function tO($,_){return new t5({type:"set",valueType:$,...C.normalizeParams(_)})}function yX($,_){let J=Array.isArray($)?Object.fromEntries($.map((U)=>[U,U])):$;return new e1({type:"enum",entries:J,...C.normalizeParams(_)})}function aO($,_){return new e1({type:"enum",entries:$,...C.normalizeParams(_)})}function sO($,_){return new a5({type:"literal",values:Array.isArray($)?$:[$],...C.normalizeParams(_)})}function eO($){return WD(s5,$)}function hX($){return new e5({type:"transform",transform:$})}function XW($){return new mX({type:"optional",innerType:$})}function _G($){return new $G({type:"optional",innerType:$})}function GW($){return new JG({type:"nullable",innerType:$})}function $L($){return XW(GW($))}function UG($,_){return new WG({type:"default",innerType:$,get defaultValue(){return typeof _==="function"?_():C.shallowClone(_)}})}function GG($,_){return new XG({type:"prefault",innerType:$,get defaultValue(){return typeof _==="function"?_():C.shallowClone(_)}})}function YG($,_){return new xX({type:"nonoptional",innerType:$,...C.normalizeParams(_)})}function _L($){return new QG({type:"success",innerType:$})}function zG($,_){return new qG({type:"catch",innerType:$,catchValue:typeof _==="function"?_:()=>_})}function JL($){return _D(jG,$)}function BX($,_){return new DW({type:"pipe",in:$,out:_})}function WL($,_,J){return new OW({type:"pipe",in:$,out:_,transform:J.decode,reverseTransform:J.encode})}function UL($){let _=$._zod.def;return new OW({type:"pipe",in:_.out,out:_.in,transform:_.reverseTransform,reverseTransform:_.transform})}function LG($){return new OG({type:"readonly",innerType:$})}function XL($,_){return new BG({type:"template_literal",parts:$,...C.normalizeParams(_)})}function NG($){return new HG({type:"lazy",getter:$})}function GL($){return new VG({type:"promise",innerType:$})}function YL($){return new RG({type:"function",input:Array.isArray($?.input)?r5($?.input):$?.input??qW(h0()),output:$?.output??h0()})}function QL($){let _=new X_({check:"custom"});return _._zod.check=$,_}function qL($,_){return UD(LW,$??(()=>!0),_)}function KG($,_={}){return XD(LW,$,_)}function FG($,_){return GD($,_)}function DL($,_={}){let J=new LW({type:"custom",check:"custom",fn:(U)=>U instanceof $,abort:!0,...C.normalizeParams(_)});return J._zod.bag.Class=$,J._zod.check=(U)=>{if(!(U.value instanceof $))U.issues.push({code:"invalid_type",expected:$.name,input:U.value,inst:J,path:[...J._zod.def.path??[]]})},J}function LL($){let _=NG(()=>{return vX([WW($),C5(),P5(),v5(),qW(_),p5(WW(),_)])});return _}function BL($,_){return new DG({type:"pipe",in:hX($),out:_})}var rK,F$,NX,$2,a$,VX,UW,d6,YW,RX,KX,FX,EX,MX,AX,bX,wX,f5,gX,kX,IX,fX,CX,PX,TX,_2,J2,m0,W2,U2,SX,T5,S5,Z5,y5,h5,m5,x5,QW,u5,zW,jW,d5,n5,c5,l5,s1,o5,t5,e1,a5,s5,e5,mX,$G,JG,WG,XG,xX,QG,qG,jG,DW,OW,DG,OG,BG,HG,VG,RG,LW,zL,jL,OL=(...$)=>qD({Codec:OW,Boolean:W2,String:$2},...$);var OX=x(()=>{Q6();Q6();GX();UX();N5();jX();$O();rK=new WeakMap;F$=M("ZodType",($,_)=>{return R$.init($,_),Object.assign($["~standard"],{jsonSchema:{input:JW($,"input"),output:JW($,"output")}}),$.toJSONSchema=zD($,{}),$.def=_,$.type=_.type,Object.defineProperty($,"_def",{value:_}),$.parse=(J,U)=>V5($,J,U,{callee:$.parse}),$.safeParse=(J,U)=>K5($,J,U),$.parseAsync=async(J,U)=>R5($,J,U,{callee:$.parseAsync}),$.safeParseAsync=async(J,U)=>F5($,J,U),$.spa=$.safeParseAsync,$.encode=(J,U)=>E5($,J,U),$.decode=(J,U)=>M5($,J,U),$.encodeAsync=async(J,U)=>A5($,J,U),$.decodeAsync=async(J,U)=>b5($,J,U),$.safeEncode=(J,U)=>w5($,J,U),$.safeDecode=(J,U)=>g5($,J,U),$.safeEncodeAsync=async(J,U)=>k5($,J,U),$.safeDecodeAsync=async(J,U)=>I5($,J,U),HX($,"ZodType",{check(...J){let U=this.def;return this.clone(C.mergeDefs(U,{checks:[...U.checks??[],...J.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}),{parent:!0})},with(...J){return this.check(...J)},clone(J,U){return T_(this,J,U)},brand(){return this},register(J,U){return J.add(this,U),this},refine(J,U){return this.check(KG(J,U))},superRefine(J,U){return this.check(FG(J,U))},overwrite(J){return this.check(R6(J))},optional(){return XW(this)},exactOptional(){return _G(this)},nullable(){return GW(this)},nullish(){return XW(GW(this))},nonoptional(J){return YG(this,J)},array(){return qW(this)},or(J){return vX([this,J])},and(J){return i5(this,J)},transform(J){return BX(this,hX(J))},default(J){return UG(this,J)},prefault(J){return GG(this,J)},catch(J){return zG(this,J)},pipe(J){return BX(this,J)},readonly(){return LG(this)},describe(J){let U=this.clone();return g_.add(U,{description:J}),U},meta(...J){if(J.length===0)return g_.get(this);let U=this.clone();return g_.add(U,J[0]),U},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(J){return J(this)}}),Object.defineProperty($,"description",{get(){return g_.get($)?.description},configurable:!0}),$}),NX=M("_ZodString",($,_)=>{h1.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>jD($,U,W,X);let J=$._zod.bag;$.format=J.format??null,$.minLength=J.minimum??null,$.maxLength=J.maximum??null,HX($,"_ZodString",{regex(...U){return this.check(m1(...U))},includes(...U){return this.check(d1(...U))},startsWith(...U){return this.check(n1(...U))},endsWith(...U){return this.check(c1(...U))},min(...U){return this.check(L4(...U))},max(...U){return this.check(T0(...U))},length(...U){return this.check(S0(...U))},nonempty(...U){return this.check(L4(1,...U))},lowercase(U){return this.check(x1(U))},uppercase(U){return this.check(u1(U))},trim(){return this.check(r1())},normalize(...U){return this.check(l1(...U))},toLowerCase(){return this.check(p1())},toUpperCase(){return this.check(o1())},slugify(){return this.check(t1())}})}),$2=M("ZodString",($,_)=>{h1.init($,_),NX.init($,_),$.email=(J)=>$.check(l8(VX,J)),$.url=(J)=>$.check(sU(YW,J)),$.jwt=(J)=>$.check(j5(TX,J)),$.emoji=(J)=>$.check(a8(RX,J)),$.guid=(J)=>$.check(aU(UW,J)),$.uuid=(J)=>$.check(r8(d6,J)),$.uuidv4=(J)=>$.check(p8(d6,J)),$.uuidv6=(J)=>$.check(o8(d6,J)),$.uuidv7=(J)=>$.check(t8(d6,J)),$.nanoid=(J)=>$.check(s8(KX,J)),$.guid=(J)=>$.check(aU(UW,J)),$.cuid=(J)=>$.check(e8(FX,J)),$.cuid2=(J)=>$.check($5(EX,J)),$.ulid=(J)=>$.check(_5(MX,J)),$.base64=(J)=>$.check(Q5(fX,J)),$.base64url=(J)=>$.check(q5(CX,J)),$.xid=(J)=>$.check(J5(AX,J)),$.ksuid=(J)=>$.check(W5(bX,J)),$.ipv4=(J)=>$.check(U5(wX,J)),$.ipv6=(J)=>$.check(X5(gX,J)),$.cidrv4=(J)=>$.check(G5(kX,J)),$.cidrv6=(J)=>$.check(Y5(IX,J)),$.e164=(J)=>$.check(z5(PX,J)),$.datetime=(J)=>$.check(oD(J)),$.date=(J)=>$.check(tD(J)),$.time=(J)=>$.check(aD(J)),$.duration=(J)=>$.check(sD(J))});a$=M("ZodStringFormat",($,_)=>{J_.init($,_),NX.init($,_)}),VX=M("ZodEmail",($,_)=>{V7.init($,_),a$.init($,_)});UW=M("ZodGUID",($,_)=>{H7.init($,_),a$.init($,_)});d6=M("ZodUUID",($,_)=>{N7.init($,_),a$.init($,_)});YW=M("ZodURL",($,_)=>{R7.init($,_),a$.init($,_)});RX=M("ZodEmoji",($,_)=>{K7.init($,_),a$.init($,_)});KX=M("ZodNanoID",($,_)=>{F7.init($,_),a$.init($,_)});FX=M("ZodCUID",($,_)=>{E7.init($,_),a$.init($,_)});EX=M("ZodCUID2",($,_)=>{M7.init($,_),a$.init($,_)});MX=M("ZodULID",($,_)=>{A7.init($,_),a$.init($,_)});AX=M("ZodXID",($,_)=>{b7.init($,_),a$.init($,_)});bX=M("ZodKSUID",($,_)=>{w7.init($,_),a$.init($,_)});wX=M("ZodIPv4",($,_)=>{C7.init($,_),a$.init($,_)});f5=M("ZodMAC",($,_)=>{T7.init($,_),a$.init($,_)});gX=M("ZodIPv6",($,_)=>{P7.init($,_),a$.init($,_)});kX=M("ZodCIDRv4",($,_)=>{S7.init($,_),a$.init($,_)});IX=M("ZodCIDRv6",($,_)=>{Z7.init($,_),a$.init($,_)});fX=M("ZodBase64",($,_)=>{y7.init($,_),a$.init($,_)});CX=M("ZodBase64URL",($,_)=>{h7.init($,_),a$.init($,_)});PX=M("ZodE164",($,_)=>{m7.init($,_),a$.init($,_)});TX=M("ZodJWT",($,_)=>{x7.init($,_),a$.init($,_)});_2=M("ZodCustomStringFormat",($,_)=>{u7.init($,_),a$.init($,_)});J2=M("ZodNumber",($,_)=>{m8.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>DD($,U,W,X),HX($,"ZodNumber",{gt(U,W){return this.check(x6(U,W))},gte(U,W){return this.check(S_(U,W))},min(U,W){return this.check(S_(U,W))},lt(U,W){return this.check(m6(U,W))},lte(U,W){return this.check(a_(U,W))},max(U,W){return this.check(a_(U,W))},int(U){return this.check(LX(U))},safe(U){return this.check(LX(U))},positive(U){return this.check(x6(0,U))},nonnegative(U){return this.check(S_(0,U))},negative(U){return this.check(m6(0,U))},nonpositive(U){return this.check(a_(0,U))},multipleOf(U,W){return this.check(l4(U,W))},step(U,W){return this.check(l4(U,W))},finite(){return this}});let J=$._zod.bag;$.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),$.isFinite=!0,$.format=J.format??null});m0=M("ZodNumberFormat",($,_)=>{d7.init($,_),J2.init($,_)});W2=M("ZodBoolean",($,_)=>{dU.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>OD($,J,U,W)});U2=M("ZodBigInt",($,_)=>{x8.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>LD($,U,W,X),$.gte=(U,W)=>$.check(S_(U,W)),$.min=(U,W)=>$.check(S_(U,W)),$.gt=(U,W)=>$.check(x6(U,W)),$.gte=(U,W)=>$.check(S_(U,W)),$.min=(U,W)=>$.check(S_(U,W)),$.lt=(U,W)=>$.check(m6(U,W)),$.lte=(U,W)=>$.check(a_(U,W)),$.max=(U,W)=>$.check(a_(U,W)),$.positive=(U)=>$.check(x6(BigInt(0),U)),$.negative=(U)=>$.check(m6(BigInt(0),U)),$.nonpositive=(U)=>$.check(a_(BigInt(0),U)),$.nonnegative=(U)=>$.check(S_(BigInt(0),U)),$.multipleOf=(U,W)=>$.check(l4(U,W));let J=$._zod.bag;$.minValue=J.minimum??null,$.maxValue=J.maximum??null,$.format=J.format??null});SX=M("ZodBigIntFormat",($,_)=>{n7.init($,_),U2.init($,_)});T5=M("ZodSymbol",($,_)=>{c7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>BD($,J,U,W)});S5=M("ZodUndefined",($,_)=>{i7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>ND($,J,U,W)});Z5=M("ZodNull",($,_)=>{l7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>HD($,J,U,W)});y5=M("ZodAny",($,_)=>{r7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>KD($,J,U,W)});h5=M("ZodUnknown",($,_)=>{p7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>FD($,J,U,W)});m5=M("ZodNever",($,_)=>{o7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>RD($,J,U,W)});x5=M("ZodVoid",($,_)=>{t7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>VD($,J,U,W)});QW=M("ZodDate",($,_)=>{a7.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>ED($,U,W,X),$.min=(U,W)=>$.check(S_(U,W)),$.max=(U,W)=>$.check(a_(U,W));let J=$._zod.bag;$.minDate=J.minimum?new Date(J.minimum):null,$.maxDate=J.maximum?new Date(J.maximum):null});u5=M("ZodArray",($,_)=>{s7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>SD($,J,U,W),$.element=_.element,HX($,"ZodArray",{min(J,U){return this.check(L4(J,U))},nonempty(J){return this.check(L4(1,J))},max(J,U){return this.check(T0(J,U))},length(J,U){return this.check(S0(J,U))},unwrap(){return this.element}})});zW=M("ZodObject",($,_)=>{e7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>ZD($,J,U,W),C.defineLazy($,"shape",()=>{return _.shape}),HX($,"ZodObject",{keyof(){return yX(Object.keys(this._zod.def.shape))},catchall(J){return this.clone({...this._zod.def,catchall:J})},passthrough(){return this.clone({...this._zod.def,catchall:h0()})},loose(){return this.clone({...this._zod.def,catchall:h0()})},strict(){return this.clone({...this._zod.def,catchall:ZX()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(J){return C.extend(this,J)},safeExtend(J){return C.safeExtend(this,J)},merge(J){return C.merge(this,J)},pick(J){return C.pick(this,J)},omit(J){return C.omit(this,J)},partial(...J){return C.partial(mX,this,J[0])},required(...J){return C.required(xX,this,J[0])}})});jW=M("ZodUnion",($,_)=>{nU.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>L5($,J,U,W),$.options=_.options});d5=M("ZodXor",($,_)=>{jW.init($,_),$z.init($,_),$._zod.processJSONSchema=(J,U,W)=>L5($,J,U,W),$.options=_.options});n5=M("ZodDiscriminatedUnion",($,_)=>{jW.init($,_),_z.init($,_)});c5=M("ZodIntersection",($,_)=>{Jz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>vD($,J,U,W)});l5=M("ZodTuple",($,_)=>{u8.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>yD($,J,U,W),$.rest=(J)=>$.clone({...$._zod.def,rest:J})});s1=M("ZodRecord",($,_)=>{Wz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>hD($,J,U,W),$.keyType=_.keyType,$.valueType=_.valueType});o5=M("ZodMap",($,_)=>{Uz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>PD($,J,U,W),$.keyType=_.keyType,$.valueType=_.valueType,$.min=(...J)=>$.check(u6(...J)),$.nonempty=(J)=>$.check(u6(1,J)),$.max=(...J)=>$.check(r4(...J)),$.size=(...J)=>$.check(P0(...J))});t5=M("ZodSet",($,_)=>{Xz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>TD($,J,U,W),$.min=(...J)=>$.check(u6(...J)),$.nonempty=(J)=>$.check(u6(1,J)),$.max=(...J)=>$.check(r4(...J)),$.size=(...J)=>$.check(P0(...J))});e1=M("ZodEnum",($,_)=>{Gz.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>MD($,U,W,X),$.enum=_.entries,$.options=Object.values(_.entries);let J=new Set(Object.keys(_.entries));$.extract=(U,W)=>{let X={};for(let G of U)if(J.has(G))X[G]=_.entries[G];else throw Error(`Key ${G} not found in enum`);return new e1({..._,checks:[],...C.normalizeParams(W),entries:X})},$.exclude=(U,W)=>{let X={..._.entries};for(let G of U)if(J.has(G))delete X[G];else throw Error(`Key ${G} not found in enum`);return new e1({..._,checks:[],...C.normalizeParams(W),entries:X})}});a5=M("ZodLiteral",($,_)=>{Yz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>AD($,J,U,W),$.values=new Set(_.values),Object.defineProperty($,"value",{get(){if(_.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return _.values[0]}})});s5=M("ZodFile",($,_)=>{Qz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>gD($,J,U,W),$.min=(J,U)=>$.check(u6(J,U)),$.max=(J,U)=>$.check(r4(J,U)),$.mime=(J,U)=>$.check(i1(Array.isArray(J)?J:[J],U))});e5=M("ZodTransform",($,_)=>{qz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>CD($,J,U,W),$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new S1($.constructor.name);J.addIssue=(X)=>{if(typeof X==="string")J.issues.push(C.issue(X,J.value,_));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=J.value),G.inst??(G.inst=$),J.issues.push(C.issue(G))}};let W=_.transform(J.value,J);if(W instanceof Promise)return W.then((X)=>{return J.value=X,J.fallback=!0,J});return J.value=W,J.fallback=!0,J}});mX=M("ZodOptional",($,_)=>{d8.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>B5($,J,U,W),$.unwrap=()=>$._zod.def.innerType});$G=M("ZodExactOptional",($,_)=>{zz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>B5($,J,U,W),$.unwrap=()=>$._zod.def.innerType});JG=M("ZodNullable",($,_)=>{jz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>mD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});WG=M("ZodDefault",($,_)=>{Dz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>uD($,J,U,W),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});XG=M("ZodPrefault",($,_)=>{Oz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>dD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});xX=M("ZodNonOptional",($,_)=>{Lz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>xD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});QG=M("ZodSuccess",($,_)=>{Bz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>kD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});qG=M("ZodCatch",($,_)=>{Hz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>nD($,J,U,W),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});jG=M("ZodNaN",($,_)=>{Nz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>bD($,J,U,W)});DW=M("ZodPipe",($,_)=>{n8.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>cD($,J,U,W),$.in=_.in,$.out=_.out});OW=M("ZodCodec",($,_)=>{DW.init($,_),cU.init($,_)});DG=M("ZodPreprocess",($,_)=>{DW.init($,_),Vz.init($,_)}),OG=M("ZodReadonly",($,_)=>{Rz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>iD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});BG=M("ZodTemplateLiteral",($,_)=>{Kz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>wD($,J,U,W)});HG=M("ZodLazy",($,_)=>{Mz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>rD($,J,U,W),$.unwrap=()=>$._zod.def.getter()});VG=M("ZodPromise",($,_)=>{Ez.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>lD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});RG=M("ZodFunction",($,_)=>{Fz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>fD($,J,U,W)});LW=M("ZodCustom",($,_)=>{Az.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>ID($,J,U,W)});zL=YD,jL=QD});function oK($){V_({customError:$})}function tK(){return V_().customError}var pK,EG;var aK=x(()=>{Q6();pK={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function($){})(EG||(EG={}))});function Cu($,_){let J=$.$schema;if(J==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(J==="http://json-schema.org/draft-07/schema#")return"draft-7";if(J==="http://json-schema.org/draft-04/schema#")return"draft-4";return _??"draft-2020-12"}function Pu($,_){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let J=$.slice(1).split("/").filter(Boolean);if(J.length===0)return _.rootSchema;let U=_.version==="draft-2020-12"?"$defs":"definitions";if(J[0]===U){let W=J[1];if(!W||!_.defs[W])throw Error(`Reference not found: ${$}`);return _.defs[W]}throw Error(`Reference not found: ${$}`)}function sK($,_){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return i.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let W=$.$ref;if(_.refs.has(W))return _.refs.get(W);if(_.processing.has(W))return i.lazy(()=>{if(!_.refs.has(W))throw Error(`Circular reference not resolved: ${W}`);return _.refs.get(W)});_.processing.add(W);let X=Pu(W,_),G=Z_(X,_);return _.refs.set(W,G),_.processing.delete(W),G}if($.enum!==void 0){let W=$.enum;if(_.version==="openapi-3.0"&&$.nullable===!0&&W.length===1&&W[0]===null)return i.null();if(W.length===0)return i.never();if(W.length===1)return i.literal(W[0]);if(W.every((G)=>typeof G==="string"))return i.enum(W);let X=W.map((G)=>i.literal(G));if(X.length<2)return X[0];return i.union([X[0],X[1],...X.slice(2)])}if($.const!==void 0)return i.literal($.const);let J=$.type;if(Array.isArray(J)){let W=J.map((X)=>{let G={...$,type:X};return sK(G,_)});if(W.length===0)return i.never();if(W.length===1)return W[0];return i.union(W)}if(!J)return i.any();let U;switch(J){case"string":{let W=i.string();if($.format){let X=$.format;if(X==="email")W=W.check(i.email());else if(X==="uri"||X==="uri-reference")W=W.check(i.url());else if(X==="uuid"||X==="guid")W=W.check(i.uuid());else if(X==="date-time")W=W.check(i.iso.datetime());else if(X==="date")W=W.check(i.iso.date());else if(X==="time")W=W.check(i.iso.time());else if(X==="duration")W=W.check(i.iso.duration());else if(X==="ipv4")W=W.check(i.ipv4());else if(X==="ipv6")W=W.check(i.ipv6());else if(X==="mac")W=W.check(i.mac());else if(X==="cidr")W=W.check(i.cidrv4());else if(X==="cidr-v6")W=W.check(i.cidrv6());else if(X==="base64")W=W.check(i.base64());else if(X==="base64url")W=W.check(i.base64url());else if(X==="e164")W=W.check(i.e164());else if(X==="jwt")W=W.check(i.jwt());else if(X==="emoji")W=W.check(i.emoji());else if(X==="nanoid")W=W.check(i.nanoid());else if(X==="cuid")W=W.check(i.cuid());else if(X==="cuid2")W=W.check(i.cuid2());else if(X==="ulid")W=W.check(i.ulid());else if(X==="xid")W=W.check(i.xid());else if(X==="ksuid")W=W.check(i.ksuid())}if(typeof $.minLength==="number")W=W.min($.minLength);if(typeof $.maxLength==="number")W=W.max($.maxLength);if($.pattern)W=W.regex(new RegExp($.pattern));U=W;break}case"number":case"integer":{let W=J==="integer"?i.number().int():i.number();if(typeof $.minimum==="number")W=W.min($.minimum);if(typeof $.maximum==="number")W=W.max($.maximum);if(typeof $.exclusiveMinimum==="number")W=W.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")W=W.gt($.minimum);if(typeof $.exclusiveMaximum==="number")W=W.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")W=W.lt($.maximum);if(typeof $.multipleOf==="number")W=W.multipleOf($.multipleOf);U=W;break}case"boolean":{U=i.boolean();break}case"null":{U=i.null();break}case"object":{let W={},X=$.properties||{},G=new Set($.required||[]);for(let[Q,q]of Object.entries(X)){let L=Z_(q,_);W[Q]=G.has(Q)?L:L.optional()}if($.propertyNames){let Q=Z_($.propertyNames,_),q=$.additionalProperties&&typeof $.additionalProperties==="object"?Z_($.additionalProperties,_):i.any();if(Object.keys(W).length===0){U=i.record(Q,q);break}let L=i.object(W).passthrough(),N=i.looseRecord(Q,q);U=i.intersection(L,N);break}if($.patternProperties){let Q=$.patternProperties,q=Object.keys(Q),L=[];for(let R of q){let B=Z_(Q[R],_),H=i.string().regex(new RegExp(R));L.push(i.looseRecord(H,B))}let N=[];if(Object.keys(W).length>0)N.push(i.object(W).passthrough());if(N.push(...L),N.length===0)U=i.object({}).passthrough();else if(N.length===1)U=N[0];else{let R=i.intersection(N[0],N[1]);for(let B=2;BZ_(Q,_)),Y=X&&typeof X==="object"&&!Array.isArray(X)?Z_(X,_):void 0;if(Y)U=i.tuple(G).rest(Y);else U=i.tuple(G);if(typeof $.minItems==="number")U=U.check(i.minLength($.minItems));if(typeof $.maxItems==="number")U=U.check(i.maxLength($.maxItems))}else if(Array.isArray(X)){let G=X.map((Q)=>Z_(Q,_)),Y=$.additionalItems&&typeof $.additionalItems==="object"?Z_($.additionalItems,_):void 0;if(Y)U=i.tuple(G).rest(Y);else U=i.tuple(G);if(typeof $.minItems==="number")U=U.check(i.minLength($.minItems));if(typeof $.maxItems==="number")U=U.check(i.maxLength($.maxItems))}else if(X!==void 0){let G=Z_(X,_),Y=i.array(G);if(typeof $.minItems==="number")Y=Y.min($.minItems);if(typeof $.maxItems==="number")Y=Y.max($.maxItems);U=Y}else U=i.array(i.any());break}default:throw Error(`Unsupported type: ${J}`)}return U}function Z_($,_){if(typeof $==="boolean")return $?i.any():i.never();let J=sK($,_),U=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let Y=$.anyOf.map((q)=>Z_(q,_)),Q=i.union(Y);J=U?i.intersection(J,Q):Q}if($.oneOf&&Array.isArray($.oneOf)){let Y=$.oneOf.map((q)=>Z_(q,_)),Q=i.xor(Y);J=U?i.intersection(J,Q):Q}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)J=U?J:i.any();else{let Y=U?J:Z_($.allOf[0],_),Q=U?0:1;for(let q=Q;q<$.allOf.length;q++)Y=i.intersection(Y,Z_($.allOf[q],_));J=Y}if($.nullable===!0&&_.version==="openapi-3.0")J=i.nullable(J);if($.readOnly===!0)J=i.readonly(J);if($.default!==void 0)J=J.default($.default);let W={},X=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let Y of X)if(Y in $)W[Y]=$[Y];let G=["contentEncoding","contentMediaType","contentSchema"];for(let Y of G)if(Y in $)W[Y]=$[Y];for(let Y of Object.keys($))if(!fu.has(Y))W[Y]=$[Y];if(Object.keys(W).length>0)_.registry.add(J,W);if($.description)J=J.describe($.description);return J}function HL($,_){if(typeof $==="boolean")return $?i.any():i.never();let J;try{J=JSON.parse(JSON.stringify($))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let U=Cu(J,_?.defaultTarget),W=J.$defs||J.definitions||{},X={version:U,defs:W,refs:new Map,processing:new Set,rootSchema:J,registry:_?.registry??g_};return Z_(J,X)}var i,fu;var eK=x(()=>{tU();N5();jX();OX();i={...DX,...H5,iso:a1},fu=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var MG={};e6(MG,{string:()=>Tu,number:()=>Su,date:()=>yu,boolean:()=>Zu,bigint:()=>vu});function Tu($){return gj($2,$)}function Su($){return Sj(J2,$)}function Zu($){return uj(W2,$)}function vu($){return nj(U2,$)}function yu($){return $D(QW,$)}var $F=x(()=>{Q6();OX()});var AG={};e6(AG,{xor:()=>iO,xid:()=>LO,void:()=>mO,uuidv7:()=>GO,uuidv6:()=>XO,uuidv4:()=>UO,uuid:()=>WO,util:()=>C,url:()=>YO,uppercase:()=>u1,unknown:()=>h0,union:()=>vX,undefined:()=>yO,ulid:()=>OO,uint64:()=>ZO,uint32:()=>PO,tuple:()=>r5,trim:()=>r1,treeifyError:()=>N8,transform:()=>hX,toUpperCase:()=>o1,toLowerCase:()=>p1,toJSONSchema:()=>XX,templateLiteral:()=>XL,symbol:()=>vO,superRefine:()=>FG,success:()=>_L,stringbool:()=>OL,stringFormat:()=>bO,string:()=>WW,strictObject:()=>nO,startsWith:()=>n1,slugify:()=>t1,size:()=>P0,setErrorMap:()=>oK,set:()=>tO,safeParseAsync:()=>F5,safeParse:()=>K5,safeEncodeAsync:()=>k5,safeEncode:()=>w5,safeDecodeAsync:()=>I5,safeDecode:()=>g5,registry:()=>oU,regexes:()=>t_,regex:()=>m1,refine:()=>KG,record:()=>p5,readonly:()=>LG,property:()=>WX,promise:()=>GL,prettifyError:()=>V8,preprocess:()=>BL,prefault:()=>GG,positive:()=>eU,pipe:()=>BX,partialRecord:()=>rO,parseAsync:()=>R5,parse:()=>V5,overwrite:()=>R6,optional:()=>XW,object:()=>dO,number:()=>C5,nullish:()=>$L,nullable:()=>GW,null:()=>v5,normalize:()=>l1,nonpositive:()=>_X,nonoptional:()=>YG,nonnegative:()=>JX,never:()=>ZX,negative:()=>$X,nativeEnum:()=>aO,nanoid:()=>zO,nan:()=>JL,multipleOf:()=>l4,minSize:()=>u6,minLength:()=>L4,mime:()=>i1,meta:()=>jL,maxSize:()=>r4,maxLength:()=>T0,map:()=>oO,mac:()=>NO,lte:()=>a_,lt:()=>m6,lowercase:()=>x1,looseRecord:()=>pO,looseObject:()=>cO,locales:()=>$W,literal:()=>sO,length:()=>S0,lazy:()=>NG,ksuid:()=>BO,keyof:()=>uO,jwt:()=>AO,json:()=>LL,iso:()=>a1,ipv6:()=>VO,ipv4:()=>HO,invertCodec:()=>UL,intersection:()=>i5,int64:()=>SO,int32:()=>CO,int:()=>LX,instanceof:()=>DL,includes:()=>d1,httpUrl:()=>QO,hostname:()=>wO,hex:()=>gO,hash:()=>kO,guid:()=>JO,gte:()=>S_,gt:()=>x6,globalRegistry:()=>g_,getErrorMap:()=>tK,function:()=>YL,fromJSONSchema:()=>HL,formatError:()=>rJ,float64:()=>fO,float32:()=>IO,flattenError:()=>lJ,file:()=>eO,exactOptional:()=>_G,enum:()=>yX,endsWith:()=>c1,encodeAsync:()=>A5,encode:()=>E5,emoji:()=>qO,email:()=>_O,e164:()=>MO,discriminatedUnion:()=>lO,describe:()=>zL,decodeAsync:()=>b5,decode:()=>M5,date:()=>xO,custom:()=>qL,cuid2:()=>DO,cuid:()=>jO,core:()=>B4,config:()=>V_,coerce:()=>MG,codec:()=>WL,clone:()=>T_,cidrv6:()=>KO,cidrv4:()=>RO,check:()=>QL,catch:()=>zG,boolean:()=>P5,bigint:()=>TO,base64url:()=>EO,base64:()=>FO,array:()=>qW,any:()=>hO,_function:()=>YL,_default:()=>UG,_ZodString:()=>NX,ZodXor:()=>d5,ZodXID:()=>AX,ZodVoid:()=>x5,ZodUnknown:()=>h5,ZodUnion:()=>jW,ZodUndefined:()=>S5,ZodUUID:()=>d6,ZodURL:()=>YW,ZodULID:()=>MX,ZodType:()=>F$,ZodTuple:()=>l5,ZodTransform:()=>e5,ZodTemplateLiteral:()=>BG,ZodSymbol:()=>T5,ZodSuccess:()=>QG,ZodStringFormat:()=>a$,ZodString:()=>$2,ZodSet:()=>t5,ZodRecord:()=>s1,ZodRealError:()=>i_,ZodReadonly:()=>OG,ZodPromise:()=>VG,ZodPreprocess:()=>DG,ZodPrefault:()=>XG,ZodPipe:()=>DW,ZodOptional:()=>mX,ZodObject:()=>zW,ZodNumberFormat:()=>m0,ZodNumber:()=>J2,ZodNullable:()=>JG,ZodNull:()=>Z5,ZodNonOptional:()=>xX,ZodNever:()=>m5,ZodNanoID:()=>KX,ZodNaN:()=>jG,ZodMap:()=>o5,ZodMAC:()=>f5,ZodLiteral:()=>a5,ZodLazy:()=>HG,ZodKSUID:()=>bX,ZodJWT:()=>TX,ZodIssueCode:()=>pK,ZodIntersection:()=>c5,ZodISOTime:()=>qX,ZodISODuration:()=>zX,ZodISODateTime:()=>YX,ZodISODate:()=>QX,ZodIPv6:()=>gX,ZodIPv4:()=>wX,ZodGUID:()=>UW,ZodFunction:()=>RG,ZodFirstPartyTypeKind:()=>EG,ZodFile:()=>s5,ZodExactOptional:()=>$G,ZodError:()=>lK,ZodEnum:()=>e1,ZodEmoji:()=>RX,ZodEmail:()=>VX,ZodE164:()=>PX,ZodDiscriminatedUnion:()=>n5,ZodDefault:()=>WG,ZodDate:()=>QW,ZodCustomStringFormat:()=>_2,ZodCustom:()=>LW,ZodCodec:()=>OW,ZodCatch:()=>qG,ZodCUID2:()=>EX,ZodCUID:()=>FX,ZodCIDRv6:()=>IX,ZodCIDRv4:()=>kX,ZodBoolean:()=>W2,ZodBigIntFormat:()=>SX,ZodBigInt:()=>U2,ZodBase64URL:()=>CX,ZodBase64:()=>fX,ZodArray:()=>u5,ZodAny:()=>y5,TimePrecision:()=>D5,NEVER:()=>O8,$output:()=>c8,$input:()=>i8,$brand:()=>L8});var NL=x(()=>{Q6();Q6();Zz();Q6();GX();eK();Aj();jX();jX();$F();OX();N5();eD();$O();aK();V_(iU())});var _F={};e6(_F,{z:()=>AG,xor:()=>iO,xid:()=>LO,void:()=>mO,uuidv7:()=>GO,uuidv6:()=>XO,uuidv4:()=>UO,uuid:()=>WO,util:()=>C,url:()=>YO,uppercase:()=>u1,unknown:()=>h0,union:()=>vX,undefined:()=>yO,ulid:()=>OO,uint64:()=>ZO,uint32:()=>PO,tuple:()=>r5,trim:()=>r1,treeifyError:()=>N8,transform:()=>hX,toUpperCase:()=>o1,toLowerCase:()=>p1,toJSONSchema:()=>XX,templateLiteral:()=>XL,symbol:()=>vO,superRefine:()=>FG,success:()=>_L,stringbool:()=>OL,stringFormat:()=>bO,string:()=>WW,strictObject:()=>nO,startsWith:()=>n1,slugify:()=>t1,size:()=>P0,setErrorMap:()=>oK,set:()=>tO,safeParseAsync:()=>F5,safeParse:()=>K5,safeEncodeAsync:()=>k5,safeEncode:()=>w5,safeDecodeAsync:()=>I5,safeDecode:()=>g5,registry:()=>oU,regexes:()=>t_,regex:()=>m1,refine:()=>KG,record:()=>p5,readonly:()=>LG,property:()=>WX,promise:()=>GL,prettifyError:()=>V8,preprocess:()=>BL,prefault:()=>GG,positive:()=>eU,pipe:()=>BX,partialRecord:()=>rO,parseAsync:()=>R5,parse:()=>V5,overwrite:()=>R6,optional:()=>XW,object:()=>dO,number:()=>C5,nullish:()=>$L,nullable:()=>GW,null:()=>v5,normalize:()=>l1,nonpositive:()=>_X,nonoptional:()=>YG,nonnegative:()=>JX,never:()=>ZX,negative:()=>$X,nativeEnum:()=>aO,nanoid:()=>zO,nan:()=>JL,multipleOf:()=>l4,minSize:()=>u6,minLength:()=>L4,mime:()=>i1,meta:()=>jL,maxSize:()=>r4,maxLength:()=>T0,map:()=>oO,mac:()=>NO,lte:()=>a_,lt:()=>m6,lowercase:()=>x1,looseRecord:()=>pO,looseObject:()=>cO,locales:()=>$W,literal:()=>sO,length:()=>S0,lazy:()=>NG,ksuid:()=>BO,keyof:()=>uO,jwt:()=>AO,json:()=>LL,iso:()=>a1,ipv6:()=>VO,ipv4:()=>HO,invertCodec:()=>UL,intersection:()=>i5,int64:()=>SO,int32:()=>CO,int:()=>LX,instanceof:()=>DL,includes:()=>d1,httpUrl:()=>QO,hostname:()=>wO,hex:()=>gO,hash:()=>kO,guid:()=>JO,gte:()=>S_,gt:()=>x6,globalRegistry:()=>g_,getErrorMap:()=>tK,function:()=>YL,fromJSONSchema:()=>HL,formatError:()=>rJ,float64:()=>fO,float32:()=>IO,flattenError:()=>lJ,file:()=>eO,exactOptional:()=>_G,enum:()=>yX,endsWith:()=>c1,encodeAsync:()=>A5,encode:()=>E5,emoji:()=>qO,email:()=>_O,e164:()=>MO,discriminatedUnion:()=>lO,describe:()=>zL,default:()=>hu,decodeAsync:()=>b5,decode:()=>M5,date:()=>xO,custom:()=>qL,cuid2:()=>DO,cuid:()=>jO,core:()=>B4,config:()=>V_,coerce:()=>MG,codec:()=>WL,clone:()=>T_,cidrv6:()=>KO,cidrv4:()=>RO,check:()=>QL,catch:()=>zG,boolean:()=>P5,bigint:()=>TO,base64url:()=>EO,base64:()=>FO,array:()=>qW,any:()=>hO,_function:()=>YL,_default:()=>UG,_ZodString:()=>NX,ZodXor:()=>d5,ZodXID:()=>AX,ZodVoid:()=>x5,ZodUnknown:()=>h5,ZodUnion:()=>jW,ZodUndefined:()=>S5,ZodUUID:()=>d6,ZodURL:()=>YW,ZodULID:()=>MX,ZodType:()=>F$,ZodTuple:()=>l5,ZodTransform:()=>e5,ZodTemplateLiteral:()=>BG,ZodSymbol:()=>T5,ZodSuccess:()=>QG,ZodStringFormat:()=>a$,ZodString:()=>$2,ZodSet:()=>t5,ZodRecord:()=>s1,ZodRealError:()=>i_,ZodReadonly:()=>OG,ZodPromise:()=>VG,ZodPreprocess:()=>DG,ZodPrefault:()=>XG,ZodPipe:()=>DW,ZodOptional:()=>mX,ZodObject:()=>zW,ZodNumberFormat:()=>m0,ZodNumber:()=>J2,ZodNullable:()=>JG,ZodNull:()=>Z5,ZodNonOptional:()=>xX,ZodNever:()=>m5,ZodNanoID:()=>KX,ZodNaN:()=>jG,ZodMap:()=>o5,ZodMAC:()=>f5,ZodLiteral:()=>a5,ZodLazy:()=>HG,ZodKSUID:()=>bX,ZodJWT:()=>TX,ZodIssueCode:()=>pK,ZodIntersection:()=>c5,ZodISOTime:()=>qX,ZodISODuration:()=>zX,ZodISODateTime:()=>YX,ZodISODate:()=>QX,ZodIPv6:()=>gX,ZodIPv4:()=>wX,ZodGUID:()=>UW,ZodFunction:()=>RG,ZodFirstPartyTypeKind:()=>EG,ZodFile:()=>s5,ZodExactOptional:()=>$G,ZodError:()=>lK,ZodEnum:()=>e1,ZodEmoji:()=>RX,ZodEmail:()=>VX,ZodE164:()=>PX,ZodDiscriminatedUnion:()=>n5,ZodDefault:()=>WG,ZodDate:()=>QW,ZodCustomStringFormat:()=>_2,ZodCustom:()=>LW,ZodCodec:()=>OW,ZodCatch:()=>qG,ZodCUID2:()=>EX,ZodCUID:()=>FX,ZodCIDRv6:()=>IX,ZodCIDRv4:()=>kX,ZodBoolean:()=>W2,ZodBigIntFormat:()=>SX,ZodBigInt:()=>U2,ZodBase64URL:()=>CX,ZodBase64:()=>fX,ZodArray:()=>u5,ZodAny:()=>y5,TimePrecision:()=>D5,NEVER:()=>O8,$output:()=>c8,$input:()=>i8,$brand:()=>L8});var hu;var JF=x(()=>{NL();NL();hu=AG});var Y9=t0((hr)=>{class zB extends Error{constructor($,_,J){super(J);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=_,this.exitCode=$,this.nestedError=void 0}}class CM extends zB{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}hr.CommanderError=zB;hr.InvalidArgumentError=CM});var GY=t0((nr)=>{var{InvalidArgumentError:ur}=Y9();class PM{constructor($,_){switch(this.description=_||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,_){if(_===this.defaultValue||!Array.isArray(_))return[$];return _.concat($)}default($,_){return this.defaultValue=$,this.defaultValueDescription=_,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(_,J)=>{if(!this.argChoices.includes(_))throw new ur(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(_,J);return _},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function dr($){let _=$.name()+($.variadic===!0?"...":"");return $.required?"<"+_+">":"["+_+"]"}nr.Argument=PM;nr.humanReadableArgName=dr});var jB=t0((rr)=>{var{humanReadableArgName:lr}=GY();class TM{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let _=$.commands.filter((U)=>!U._hidden),J=$._getHelpCommand();if(J&&!J._hidden)_.push(J);if(this.sortSubcommands)_.sort((U,W)=>{return U.name().localeCompare(W.name())});return _}compareOptions($,_){let J=(U)=>{return U.short?U.short.replace(/^-/,""):U.long.replace(/^--/,"")};return J($).localeCompare(J(_))}visibleOptions($){let _=$.options.filter((U)=>!U.hidden),J=$._getHelpOption();if(J&&!J.hidden){let U=J.short&&$._findOption(J.short),W=J.long&&$._findOption(J.long);if(!U&&!W)_.push(J);else if(J.long&&!W)_.push($.createOption(J.long,J.description));else if(J.short&&!U)_.push($.createOption(J.short,J.description))}if(this.sortOptions)_.sort(this.compareOptions);return _}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let _=[];for(let J=$.parent;J;J=J.parent){let U=J.options.filter((W)=>!W.hidden);_.push(...U)}if(this.sortOptions)_.sort(this.compareOptions);return _}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((_)=>{_.description=_.description||$._argsDescription[_.name()]||""});if($.registeredArguments.find((_)=>_.description))return $.registeredArguments;return[]}subcommandTerm($){let _=$.registeredArguments.map((J)=>lr(J)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(_?" "+_:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,_){return _.visibleCommands($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleSubcommandTerm(_.subcommandTerm(U))))},0)}longestOptionTermLength($,_){return _.visibleOptions($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleOptionTerm(_.optionTerm(U))))},0)}longestGlobalOptionTermLength($,_){return _.visibleGlobalOptions($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleOptionTerm(_.optionTerm(U))))},0)}longestArgumentTermLength($,_){return _.visibleArguments($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleArgumentTerm(_.argumentTerm(U))))},0)}commandUsage($){let _=$._name;if($._aliases[0])_=_+"|"+$._aliases[0];let J="";for(let U=$.parent;U;U=U.parent)J=U.name()+" "+J;return J+_+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let _=[];if($.argChoices)_.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")_.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)_.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)_.push(`env: ${$.envVar}`);if(_.length>0)return`${$.description} (${_.join(", ")})`;return $.description}argumentDescription($){let _=[];if($.argChoices)_.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0)_.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(_.length>0){let J=`(${_.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}formatHelp($,_){let J=_.padWidth($,_),U=_.helpWidth??80;function W(L,N){return _.formatItem(L,J,N,_)}let X=[`${_.styleTitle("Usage:")} ${_.styleUsage(_.commandUsage($))}`,""],G=_.commandDescription($);if(G.length>0)X=X.concat([_.boxWrap(_.styleCommandDescription(G),U),""]);let Y=_.visibleArguments($).map((L)=>{return W(_.styleArgumentTerm(_.argumentTerm(L)),_.styleArgumentDescription(_.argumentDescription(L)))});if(Y.length>0)X=X.concat([_.styleTitle("Arguments:"),...Y,""]);let Q=_.visibleOptions($).map((L)=>{return W(_.styleOptionTerm(_.optionTerm(L)),_.styleOptionDescription(_.optionDescription(L)))});if(Q.length>0)X=X.concat([_.styleTitle("Options:"),...Q,""]);if(_.showGlobalOptions){let L=_.visibleGlobalOptions($).map((N)=>{return W(_.styleOptionTerm(_.optionTerm(N)),_.styleOptionDescription(_.optionDescription(N)))});if(L.length>0)X=X.concat([_.styleTitle("Global Options:"),...L,""])}let q=_.visibleCommands($).map((L)=>{return W(_.styleSubcommandTerm(_.subcommandTerm(L)),_.styleSubcommandDescription(_.subcommandDescription(L)))});if(q.length>0)X=X.concat([_.styleTitle("Commands:"),...q,""]);return X.join(` -`)}displayWidth($){return SM($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((_)=>{if(_==="[options]")return this.styleOptionText(_);if(_==="[command]")return this.styleSubcommandText(_);if(_[0]==="["||_[0]==="<")return this.styleArgumentText(_);return this.styleCommandText(_)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((_)=>{if(_==="[options]")return this.styleOptionText(_);if(_[0]==="["||_[0]==="<")return this.styleArgumentText(_);return this.styleSubcommandText(_)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,_){return Math.max(_.longestOptionTermLength($,_),_.longestGlobalOptionTermLength($,_),_.longestSubcommandTermLength($,_),_.longestArgumentTermLength($,_))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,_,J,U){let X=" ".repeat(2);if(!J)return X+$;let G=$.padEnd(_+$.length-U.displayWidth($)),Y=2,q=(this.helpWidth??80)-_-Y-2,L;if(q{let G=X.match(U);if(G===null){W.push("");return}let Y=[G.shift()],Q=this.displayWidth(Y[0]);G.forEach((q)=>{let L=this.displayWidth(q);if(Q+L<=_){Y.push(q),Q+=L;return}W.push(Y.join(""));let N=q.trimStart();Y=[N],Q=this.displayWidth(N)}),W.push(Y.join(""))}),W.join(` -`)}}function SM($){let _=/\x1b\[\d*(;\d*)*m/g;return $.replace(_,"")}rr.Help=TM;rr.stripColor=SM});var DB=t0((sr)=>{var{InvalidArgumentError:tr}=Y9();class vM{constructor($,_){this.flags=$,this.description=_||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let J=ar($);if(this.short=J.shortFlag,this.long=J.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,_){return this.defaultValue=$,this.defaultValueDescription=_,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let _=$;if(typeof $==="string")_={[$]:!0};return this.implied=Object.assign(this.implied||{},_),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,_){if(_===this.defaultValue||!Array.isArray(_))return[$];return _.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(_,J)=>{if(!this.argChoices.includes(_))throw new tr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(_,J);return _},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return ZM(this.name().replace(/^no-/,""));return ZM(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class yM{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((_)=>{if(_.negate)this.negativeOptions.set(_.attributeName(),_);else this.positiveOptions.set(_.attributeName(),_)}),this.negativeOptions.forEach((_,J)=>{if(this.positiveOptions.has(J))this.dualOptions.add(J)})}valueFromOption($,_){let J=_.attributeName();if(!this.dualOptions.has(J))return!0;let U=this.negativeOptions.get(J).presetArg,W=U!==void 0?U:!1;return _.negate===(W===$)}}function ZM($){return $.split("-").reduce((_,J)=>{return _+J[0].toUpperCase()+J.slice(1)})}function ar($){let _,J,U=/^-[^-]$/,W=/^--[^-]/,X=$.split(/[ |,]+/).concat("guard");if(U.test(X[0]))_=X.shift();if(W.test(X[0]))J=X.shift();if(!_&&U.test(X[0]))_=X.shift();if(!_&&W.test(X[0]))_=J,J=X.shift();if(X[0].startsWith("-")){let G=X[0],Y=`option creation failed due to '${G}' in option flags '${$}'`;if(/^-[^-][^-]/.test(G))throw Error(`${Y} +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let j of _.seen.entries()){let N=j[1];if($===j[0]){I(j);continue}if(_.external){let A=_.external.registry.get(j[0])?.id;if($!==j[0]&&A){I(j);continue}}if(_.metadataRegistry.get(j[0])?.id){I(j);continue}if(N.cycle){I(j);continue}if(N.count>1){if(_.reused==="ref"){I(j);continue}}}}function w6(_,$){let g=_.seen.get($);if(!g)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(N)=>{let O=_.seen.get(N);if(O.ref===null)return;let A=O.def??O.schema,L={...A},z=O.ref;if(O.ref=null,z){U(z);let J=_.seen.get(z),P=J.schema;if(P.$ref&&(_.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"))A.allOf=A.allOf??[],A.allOf.push(P);else Object.assign(A,P);if(Object.assign(A,L),N._zod.parent===z)for(let X in A){if(X==="$ref"||X==="allOf")continue;if(!(X in L))delete A[X]}if(P.$ref&&J.def)for(let X in A){if(X==="$ref"||X==="allOf")continue;if(X in J.def&&JSON.stringify(A[X])===JSON.stringify(J.def[X]))delete A[X]}}let W=N._zod.parent;if(W&&W!==z){U(W);let J=_.seen.get(W);if(J?.schema.$ref){if(A.$ref=J.schema.$ref,J.def)for(let P in A){if(P==="$ref"||P==="allOf")continue;if(P in J.def&&JSON.stringify(A[P])===JSON.stringify(J.def[P]))delete A[P]}}}_.override({zodSchema:N,jsonSchema:A,path:O.path??[]})};for(let N of[..._.seen.entries()].reverse())U(N[0]);let D={};if(_.target==="draft-2020-12")D.$schema="https://json-schema.org/draft/2020-12/schema";else if(_.target==="draft-07")D.$schema="http://json-schema.org/draft-07/schema#";else if(_.target==="draft-04")D.$schema="http://json-schema.org/draft-04/schema#";else if(_.target==="openapi-3.0");if(_.external?.uri){let N=_.external.registry.get($)?.id;if(!N)throw Error("Schema is missing an `id` property");D.$id=_.external.uri(N)}Object.assign(D,g.def??g.schema);let I=_.metadataRegistry.get($)?.id;if(I!==void 0&&D.id===I)delete D.id;let j=_.external?.defs??{};for(let N of _.seen.entries()){let O=N[1];if(O.def&&O.defId){if(O.def.id===O.defId)delete O.def.id;j[O.defId]=O.def}}if(_.external);else if(Object.keys(j).length>0)if(_.target==="draft-2020-12")D.$defs=j;else D.definitions=j;try{let N=JSON.parse(JSON.stringify(D));return Object.defineProperty(N,"~standard",{value:{...$["~standard"],jsonSchema:{input:u0($,"input",_.processors),output:u0($,"output",_.processors)}},enumerable:!1,writable:!1}),N}catch(N){throw Error("Error converting schema to JSON.")}}function t_(_,$){let g=$??{seen:new Set};if(g.seen.has(_))return!1;g.seen.add(_);let U=_._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return t_(U.element,g);if(U.type==="set")return t_(U.valueType,g);if(U.type==="lazy")return t_(U.getter(),g);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return t_(U.innerType,g);if(U.type==="intersection")return t_(U.left,g)||t_(U.right,g);if(U.type==="record"||U.type==="map")return t_(U.keyType,g)||t_(U.valueType,g);if(U.type==="pipe"){if(_._zod.traits.has("$ZodCodec"))return!0;return t_(U.in,g)||t_(U.out,g)}if(U.type==="object"){for(let D in U.shape)if(t_(U.shape[D],g))return!0;return!1}if(U.type==="union"){for(let D of U.options)if(t_(D,g))return!0;return!1}if(U.type==="tuple"){for(let D of U.items)if(t_(D,g))return!0;if(U.rest&&t_(U.rest,g))return!0;return!1}return!1}var cL=(_,$={})=>(g)=>{let U=v6({...g,processors:$});return A_(_,U),f6(U,_),w6(U,_)},u0=(_,$,g={})=>(U)=>{let{libraryOptions:D,target:I}=U??{},j=v6({...D??{},target:I,io:$,processors:g});return A_(_,j),f6(j,_),w6(j,_)};var YD=f(()=>{JD()});function QD(_,$){if("_idmap"in _){let U=_,D=v6({...$,processors:X1}),I={};for(let O of U._idmap.entries()){let[A,L]=O;A_(L,D)}let j={},N={registry:U,uri:$?.uri,defs:I};D.external=N;for(let O of U._idmap.entries()){let[A,L]=O;f6(D,L),j[A]=w6(D,L)}if(Object.keys(I).length>0){let O=D.target==="draft-2020-12"?"$defs":"definitions";j.__shared={[O]:I}}return{schemas:j}}let g=v6({...$,processors:X1});return A_(_,g),f6(g,_),w6(g,_)}var RF,nL=(_,$,g,U)=>{let D=g;D.type="string";let{minimum:I,maximum:j,format:N,patterns:O,contentEncoding:A}=_._zod.bag;if(typeof I==="number")D.minLength=I;if(typeof j==="number")D.maxLength=j;if(N){if(D.format=RF[N]??N,D.format==="")delete D.format;if(N==="time")delete D.format}if(A)D.contentEncoding=A;if(O&&O.size>0){let L=[...O];if(L.length===1)D.pattern=L[0].source;else if(L.length>1)D.allOf=[...L.map((z)=>({...$.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"?{type:"string"}:{},pattern:z.source}))]}},dL=(_,$,g,U)=>{let D=g,{minimum:I,maximum:j,format:N,multipleOf:O,exclusiveMaximum:A,exclusiveMinimum:L}=_._zod.bag;if(typeof N==="string"&&N.includes("int"))D.type="integer";else D.type="number";let z=typeof L==="number"&&L>=(I??Number.NEGATIVE_INFINITY),W=typeof A==="number"&&A<=(j??Number.POSITIVE_INFINITY),J=$.target==="draft-04"||$.target==="openapi-3.0";if(z)if(J)D.minimum=L,D.exclusiveMinimum=!0;else D.exclusiveMinimum=L;else if(typeof I==="number")D.minimum=I;if(W)if(J)D.maximum=A,D.exclusiveMaximum=!0;else D.exclusiveMaximum=A;else if(typeof j==="number")D.maximum=j;if(typeof O==="number")D.multipleOf=O},mL=(_,$,g,U)=>{g.type="boolean"},iL=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},lL=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},tL=(_,$,g,U)=>{if($.target==="openapi-3.0")g.type="string",g.nullable=!0,g.enum=[null];else g.type="null"},oL=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},pL=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},eL=(_,$,g,U)=>{g.not={}},aL=(_,$,g,U)=>{},sL=(_,$,g,U)=>{},_J=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},$J=(_,$,g,U)=>{let D=_._zod.def,I=og(D.entries);if(I.every((j)=>typeof j==="number"))g.type="number";if(I.every((j)=>typeof j==="string"))g.type="string";g.enum=I},gJ=(_,$,g,U)=>{let D=_._zod.def,I=[];for(let j of D.values)if(j===void 0){if($.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if($.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else I.push(Number(j));else I.push(j);if(I.length===0);else if(I.length===1){let j=I[0];if(g.type=j===null?"null":typeof j,$.target==="draft-04"||$.target==="openapi-3.0")g.enum=[j];else g.const=j}else{if(I.every((j)=>typeof j==="number"))g.type="number";if(I.every((j)=>typeof j==="string"))g.type="string";if(I.every((j)=>typeof j==="boolean"))g.type="boolean";if(I.every((j)=>j===null))g.type="null";g.enum=I}},DJ=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},UJ=(_,$,g,U)=>{let D=g,I=_._zod.pattern;if(!I)throw Error("Pattern not found in template literal");D.type="string",D.pattern=I.source},IJ=(_,$,g,U)=>{let D=g,I={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:N,mime:O}=_._zod.bag;if(j!==void 0)I.minLength=j;if(N!==void 0)I.maxLength=N;if(O)if(O.length===1)I.contentMediaType=O[0],Object.assign(D,I);else Object.assign(D,I),D.anyOf=O.map((A)=>({contentMediaType:A}));else Object.assign(D,I)},jJ=(_,$,g,U)=>{g.type="boolean"},NJ=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},EJ=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},OJ=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},AJ=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},LJ=(_,$,g,U)=>{if($.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},JJ=(_,$,g,U)=>{let D=g,I=_._zod.def,{minimum:j,maximum:N}=_._zod.bag;if(typeof j==="number")D.minItems=j;if(typeof N==="number")D.maxItems=N;D.type="array",D.items=A_(I.element,$,{...U,path:[...U.path,"items"]})},PJ=(_,$,g,U)=>{let D=g,I=_._zod.def;D.type="object",D.properties={};let j=I.shape;for(let A in j)D.properties[A]=A_(j[A],$,{...U,path:[...U.path,"properties",A]});let N=new Set(Object.keys(j)),O=new Set([...N].filter((A)=>{let L=I.shape[A]._zod;if($.io==="input")return L.optin===void 0;else return L.optout===void 0}));if(O.size>0)D.required=Array.from(O);if(I.catchall?._zod.def.type==="never")D.additionalProperties=!1;else if(!I.catchall){if($.io==="output")D.additionalProperties=!1}else if(I.catchall)D.additionalProperties=A_(I.catchall,$,{...U,path:[...U.path,"additionalProperties"]})},R1=(_,$,g,U)=>{let D=_._zod.def,I=D.inclusive===!1,j=D.options.map((N,O)=>A_(N,$,{...U,path:[...U.path,I?"oneOf":"anyOf",O]}));if(I)g.oneOf=j;else g.anyOf=j},zJ=(_,$,g,U)=>{let D=_._zod.def,I=A_(D.left,$,{...U,path:[...U.path,"allOf",0]}),j=A_(D.right,$,{...U,path:[...U.path,"allOf",1]}),N=(A)=>("allOf"in A)&&Object.keys(A).length===1,O=[...N(I)?I.allOf:[I],...N(j)?j.allOf:[j]];g.allOf=O},SJ=(_,$,g,U)=>{let D=g,I=_._zod.def;D.type="array";let j=$.target==="draft-2020-12"?"prefixItems":"items",N=$.target==="draft-2020-12"?"items":$.target==="openapi-3.0"?"items":"additionalItems",O=I.items.map((W,J)=>A_(W,$,{...U,path:[...U.path,j,J]})),A=I.rest?A_(I.rest,$,{...U,path:[...U.path,N,...$.target==="openapi-3.0"?[I.items.length]:[]]}):null;if($.target==="draft-2020-12"){if(D.prefixItems=O,A)D.items=A}else if($.target==="openapi-3.0"){if(D.items={anyOf:O},A)D.items.anyOf.push(A);if(D.minItems=O.length,!A)D.maxItems=O.length}else if(D.items=O,A)D.additionalItems=A;let{minimum:L,maximum:z}=_._zod.bag;if(typeof L==="number")D.minItems=L;if(typeof z==="number")D.maxItems=z},WJ=(_,$,g,U)=>{let D=g,I=_._zod.def;D.type="object";let j=I.keyType,O=j._zod.bag?.patterns;if(I.mode==="loose"&&O&&O.size>0){let L=A_(I.valueType,$,{...U,path:[...U.path,"patternProperties","*"]});D.patternProperties={};for(let z of O)D.patternProperties[z.source]=L}else{if($.target==="draft-07"||$.target==="draft-2020-12")D.propertyNames=A_(I.keyType,$,{...U,path:[...U.path,"propertyNames"]});D.additionalProperties=A_(I.valueType,$,{...U,path:[...U.path,"additionalProperties"]})}let A=j._zod.values;if(A){let L=[...A].filter((z)=>typeof z==="string"||typeof z==="number");if(L.length>0)D.required=L}},XJ=(_,$,g,U)=>{let D=_._zod.def,I=A_(D.innerType,$,U),j=$.seen.get(_);if($.target==="openapi-3.0")j.ref=D.innerType,g.nullable=!0;else g.anyOf=[I,{type:"null"}]},RJ=(_,$,g,U)=>{let D=_._zod.def;A_(D.innerType,$,U);let I=$.seen.get(_);I.ref=D.innerType},GJ=(_,$,g,U)=>{let D=_._zod.def;A_(D.innerType,$,U);let I=$.seen.get(_);I.ref=D.innerType,g.default=JSON.parse(JSON.stringify(D.defaultValue))},YJ=(_,$,g,U)=>{let D=_._zod.def;A_(D.innerType,$,U);let I=$.seen.get(_);if(I.ref=D.innerType,$.io==="input")g._prefault=JSON.parse(JSON.stringify(D.defaultValue))},QJ=(_,$,g,U)=>{let D=_._zod.def;A_(D.innerType,$,U);let I=$.seen.get(_);I.ref=D.innerType;let j;try{j=D.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}g.default=j},TJ=(_,$,g,U)=>{let D=_._zod.def,I=D.in._zod.traits.has("$ZodTransform"),j=$.io==="input"?I?D.out:D.in:D.out;A_(j,$,U);let N=$.seen.get(_);N.ref=j},qJ=(_,$,g,U)=>{let D=_._zod.def;A_(D.innerType,$,U);let I=$.seen.get(_);I.ref=D.innerType,g.readOnly=!0},BJ=(_,$,g,U)=>{let D=_._zod.def;A_(D.innerType,$,U);let I=$.seen.get(_);I.ref=D.innerType},G1=(_,$,g,U)=>{let D=_._zod.def;A_(D.innerType,$,U);let I=$.seen.get(_);I.ref=D.innerType},KJ=(_,$,g,U)=>{let D=_._zod.innerType;A_(D,$,U);let I=$.seen.get(_);I.ref=D},X1;var TD=f(()=>{YD();c();RF={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},X1={string:nL,number:dL,boolean:mL,bigint:iL,symbol:lL,null:tL,undefined:oL,void:pL,never:eL,any:aL,unknown:sL,date:_J,enum:$J,literal:gJ,nan:DJ,template_literal:UJ,file:IJ,success:jJ,custom:NJ,function:EJ,transform:OJ,map:AJ,set:LJ,array:JJ,object:PJ,union:R1,intersection:zJ,tuple:SJ,record:WJ,nullable:XJ,nonoptional:RJ,default:GJ,prefault:YJ,catch:QJ,pipe:TJ,readonly:qJ,promise:BJ,optional:G1,lazy:KJ}});class VJ{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(_){this.ctx.counter=_}get seen(){return this.ctx.seen}constructor(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";this.ctx=v6({processors:X1,target:$,..._?.metadata&&{metadata:_.metadata},..._?.unrepresentable&&{unrepresentable:_.unrepresentable},..._?.override&&{override:_.override},..._?.io&&{io:_.io}})}process(_,$={path:[],schemaPath:[]}){return A_(_,this.ctx,$)}emit(_,$){if($){if($.cycles)this.ctx.cycles=$.cycles;if($.reused)this.ctx.reused=$.reused;if($.external)this.ctx.external=$.external}f6(this.ctx,_);let g=w6(this.ctx,_),{"~standard":U,...D}=g;return D}}var s5=f(()=>{TD();YD()});var _R={};var $R=()=>{};var h$={};r$(h$,{version:()=>m2,util:()=>H,treeifyError:()=>QI,toJSONSchema:()=>QD,toDotPath:()=>KX,safeParseAsync:()=>pE,safeParse:()=>oE,safeEncodeAsync:()=>QK,safeEncode:()=>GK,safeDecodeAsync:()=>TK,safeDecode:()=>YK,registry:()=>LD,regexes:()=>$$,process:()=>A_,prettifyError:()=>TI,parseAsync:()=>BI,parse:()=>qI,meta:()=>yL,locales:()=>f0,isValidJWT:()=>lX,isValidBase64URL:()=>iX,isValidBase64:()=>zO,initializeContext:()=>v6,globalRegistry:()=>w_,globalConfig:()=>A4,formatError:()=>Z0,flattenError:()=>M0,finalize:()=>w6,extractDefs:()=>f6,encodeAsync:()=>XK,encode:()=>SK,describe:()=>xL,decodeAsync:()=>RK,decode:()=>WK,createToJSONSchemaMethod:()=>cL,createStandardJSONSchemaMethod:()=>u0,config:()=>Z_,clone:()=>y_,_xor:()=>pV,_xid:()=>j1,_void:()=>bL,_uuidv7:()=>_1,_uuidv6:()=>sI,_uuidv4:()=>aI,_uuid:()=>eI,_url:()=>zD,_uppercase:()=>R4,_unknown:()=>ML,_union:()=>oV,_undefined:()=>KL,_ulid:()=>I1,_uint64:()=>qL,_uint32:()=>XL,_tuple:()=>sV,_trim:()=>B4,_transform:()=>jF,_toUpperCase:()=>V4,_toLowerCase:()=>K4,_templateLiteral:()=>SF,_symbol:()=>BL,_superRefine:()=>uL,_success:()=>LF,_stringbool:()=>hL,_stringFormat:()=>w0,_string:()=>UL,_startsWith:()=>Y4,_slugify:()=>F4,_size:()=>k6,_set:()=>gF,_safeParseAsync:()=>C0,_safeParse:()=>k0,_safeEncodeAsync:()=>HI,_safeEncode:()=>ZI,_safeDecodeAsync:()=>kI,_safeDecode:()=>bI,_regex:()=>W4,_refine:()=>wL,_record:()=>_F,_readonly:()=>zF,_property:()=>GD,_promise:()=>XF,_positive:()=>SD,_pipe:()=>PF,_parseAsync:()=>H0,_parse:()=>b0,_overwrite:()=>z$,_optional:()=>NF,_number:()=>LL,_nullable:()=>EF,_null:()=>VL,_normalize:()=>q4,_nonpositive:()=>XD,_nonoptional:()=>AF,_nonnegative:()=>RD,_never:()=>ZL,_negative:()=>WD,_nativeEnum:()=>UF,_nanoid:()=>g1,_nan:()=>CL,_multipleOf:()=>U6,_minSize:()=>q$,_minLength:()=>y$,_min:()=>h_,_mime:()=>T4,_maxSize:()=>I6,_maxLength:()=>C6,_max:()=>g$,_map:()=>$F,_mac:()=>jL,_lte:()=>g$,_lt:()=>Q$,_lowercase:()=>X4,_literal:()=>IF,_length:()=>r6,_lazy:()=>WF,_ksuid:()=>N1,_jwt:()=>S1,_isoTime:()=>OL,_isoDuration:()=>AL,_isoDateTime:()=>NL,_isoDate:()=>EL,_ipv6:()=>O1,_ipv4:()=>E1,_intersection:()=>aV,_int64:()=>TL,_int32:()=>WL,_int:()=>PL,_includes:()=>G4,_guid:()=>PD,_gte:()=>h_,_gt:()=>T$,_float64:()=>SL,_float32:()=>zL,_file:()=>vL,_enum:()=>DF,_endsWith:()=>Q4,_encodeAsync:()=>FI,_encode:()=>KI,_emoji:()=>$1,_email:()=>pI,_e164:()=>z1,_discriminatedUnion:()=>eV,_default:()=>OF,_decodeAsync:()=>MI,_decode:()=>VI,_date:()=>HL,_custom:()=>fL,_cuid2:()=>U1,_cuid:()=>D1,_coercedString:()=>IL,_coercedNumber:()=>JL,_coercedDate:()=>kL,_coercedBoolean:()=>GL,_coercedBigint:()=>QL,_cidrv6:()=>L1,_cidrv4:()=>A1,_check:()=>e5,_catch:()=>JF,_boolean:()=>RL,_bigint:()=>YL,_base64url:()=>P1,_base64:()=>J1,_array:()=>rL,_any:()=>FL,TimePrecision:()=>W1,NEVER:()=>XI,JSONSchemaGenerator:()=>VJ,JSONSchema:()=>_R,Doc:()=>uI,$output:()=>tI,$input:()=>oI,$constructor:()=>Y,$brand:()=>RI,$ZodXor:()=>kO,$ZodXID:()=>DO,$ZodVoid:()=>MO,$ZodUnknown:()=>VO,$ZodUnion:()=>ID,$ZodUndefined:()=>qO,$ZodUUID:()=>o2,$ZodURL:()=>e2,$ZodULID:()=>gO,$ZodType:()=>l,$ZodTuple:()=>mI,$ZodTransform:()=>hO,$ZodTemplateLiteral:()=>aO,$ZodSymbol:()=>TO,$ZodSuccess:()=>lO,$ZodStringFormat:()=>R_,$ZodString:()=>S4,$ZodSet:()=>wO,$ZodRegistry:()=>DL,$ZodRecord:()=>vO,$ZodRealError:()=>_$,$ZodReadonly:()=>eO,$ZodPromise:()=>_A,$ZodPreprocess:()=>pO,$ZodPrefault:()=>mO,$ZodPipe:()=>lI,$ZodOptional:()=>iI,$ZodObjectJIT:()=>HO,$ZodObject:()=>pX,$ZodNumberFormat:()=>YO,$ZodNumber:()=>nI,$ZodNullable:()=>nO,$ZodNull:()=>BO,$ZodNonOptional:()=>iO,$ZodNever:()=>FO,$ZodNanoID:()=>s2,$ZodNaN:()=>oO,$ZodMap:()=>fO,$ZodMAC:()=>LO,$ZodLiteral:()=>xO,$ZodLazy:()=>$A,$ZodKSUID:()=>UO,$ZodJWT:()=>RO,$ZodIntersection:()=>rO,$ZodISOTime:()=>NO,$ZodISODuration:()=>EO,$ZodISODateTime:()=>IO,$ZodISODate:()=>jO,$ZodIPv6:()=>AO,$ZodIPv4:()=>OO,$ZodGUID:()=>t2,$ZodFunction:()=>sO,$ZodFile:()=>yO,$ZodExactOptional:()=>cO,$ZodError:()=>_D,$ZodEnum:()=>uO,$ZodEncodeError:()=>L4,$ZodEmoji:()=>a2,$ZodEmail:()=>p2,$ZodE164:()=>XO,$ZodDiscriminatedUnion:()=>CO,$ZodDefault:()=>dO,$ZodDate:()=>ZO,$ZodCustomStringFormat:()=>GO,$ZodCustom:()=>gA,$ZodCodec:()=>jD,$ZodCheckUpperCase:()=>u2,$ZodCheckStringFormat:()=>r0,$ZodCheckStartsWith:()=>y2,$ZodCheckSizeEquals:()=>k2,$ZodCheckRegex:()=>f2,$ZodCheckProperty:()=>c2,$ZodCheckOverwrite:()=>d2,$ZodCheckNumberFormat:()=>M2,$ZodCheckMultipleOf:()=>F2,$ZodCheckMinSize:()=>H2,$ZodCheckMinLength:()=>r2,$ZodCheckMimeType:()=>n2,$ZodCheckMaxSize:()=>b2,$ZodCheckMaxLength:()=>C2,$ZodCheckLowerCase:()=>w2,$ZodCheckLessThan:()=>vI,$ZodCheckLengthEquals:()=>v2,$ZodCheckIncludes:()=>x2,$ZodCheckGreaterThan:()=>fI,$ZodCheckEndsWith:()=>h2,$ZodCheckBigIntFormat:()=>Z2,$ZodCheck:()=>Y_,$ZodCatch:()=>tO,$ZodCUID2:()=>$O,$ZodCUID:()=>_O,$ZodCIDRv6:()=>PO,$ZodCIDRv4:()=>JO,$ZodBoolean:()=>UD,$ZodBigIntFormat:()=>QO,$ZodBigInt:()=>dI,$ZodBase64URL:()=>WO,$ZodBase64:()=>SO,$ZodAsyncError:()=>x$,$ZodArray:()=>bO,$ZodAny:()=>KO});var N$=f(()=>{c();rI();gL();TD();s5();$R();J4();eE();tE();DA();wI();i2();JD();a5();YD()});var Y1={};r$(Y1,{uppercase:()=>R4,trim:()=>B4,toUpperCase:()=>V4,toLowerCase:()=>K4,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,regex:()=>W4,property:()=>GD,positive:()=>SD,overwrite:()=>z$,normalize:()=>q4,nonpositive:()=>XD,nonnegative:()=>RD,negative:()=>WD,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,maxSize:()=>I6,maxLength:()=>C6,lte:()=>g$,lt:()=>Q$,lowercase:()=>X4,length:()=>r6,includes:()=>G4,gte:()=>h_,gt:()=>T$,endsWith:()=>Q4});var Q1=f(()=>{N$()});var M4={};r$(M4,{time:()=>ZJ,duration:()=>bJ,datetime:()=>FJ,date:()=>MJ,ZodISOTime:()=>KD,ZodISODuration:()=>VD,ZodISODateTime:()=>qD,ZodISODate:()=>BD});function FJ(_){return NL(qD,_)}function MJ(_){return EL(BD,_)}function ZJ(_){return OL(KD,_)}function bJ(_){return AL(VD,_)}var qD,BD,KD,VD;var FD=f(()=>{N$();ZD();qD=Y("ZodISODateTime",(_,$)=>{IO.init(_,$),z_.init(_,$)});BD=Y("ZodISODate",(_,$)=>{jO.init(_,$),z_.init(_,$)});KD=Y("ZodISOTime",(_,$)=>{NO.init(_,$),z_.init(_,$)});VD=Y("ZodISODuration",(_,$)=>{EO.init(_,$),z_.init(_,$)})});var gR=(_,$)=>{_D.init(_,$),_.name="ZodError",Object.defineProperties(_,{format:{value:(g)=>Z0(_,g)},flatten:{value:(g)=>M0(_,g)},addIssue:{value:(g)=>{_.issues.push(g),_.message=JSON.stringify(_.issues,K0,2)}},addIssues:{value:(g)=>{_.issues.push(...g),_.message=JSON.stringify(_.issues,K0,2)}},isEmpty:{get(){return _.issues.length===0}}})},DR,o_;var HJ=f(()=>{N$();N$();c();DR=Y("ZodError",gR),o_=Y("ZodError",gR,{Parent:Error})});var T1,q1,B1,K1,V1,F1,M1,Z1,b1,H1,k1,C1;var kJ=f(()=>{N$();HJ();T1=b0(o_),q1=H0(o_),B1=k0(o_),K1=C0(o_),V1=KI(o_),F1=VI(o_),M1=FI(o_),Z1=MI(o_),b1=ZI(o_),H1=bI(o_),k1=HI(o_),C1=kI(o_)});var MD={};r$(MD,{xor:()=>qP,xid:()=>iJ,void:()=>XP,uuidv7:()=>uJ,uuidv6:()=>wJ,uuidv4:()=>fJ,uuid:()=>vJ,url:()=>xJ,unknown:()=>u6,union:()=>aD,undefined:()=>SP,ulid:()=>mJ,uint64:()=>PP,uint32:()=>AP,tuple:()=>e1,transform:()=>_U,templateLiteral:()=>wP,symbol:()=>zP,superRefine:()=>Kj,success:()=>CP,stringbool:()=>mP,stringFormat:()=>DP,string:()=>x0,strictObject:()=>QP,set:()=>MP,refine:()=>Bj,record:()=>a1,readonly:()=>Rj,promise:()=>uP,preprocess:()=>lP,prefault:()=>Aj,pipe:()=>HD,partialRecord:()=>KP,optional:()=>h0,object:()=>YP,number:()=>v1,nullish:()=>kP,nullable:()=>c0,null:()=>y1,nonoptional:()=>Lj,never:()=>eD,nativeEnum:()=>ZP,nanoid:()=>cJ,nan:()=>rP,meta:()=>nP,map:()=>FP,mac:()=>oJ,looseRecord:()=>VP,looseObject:()=>TP,literal:()=>bP,lazy:()=>Qj,ksuid:()=>lJ,keyof:()=>GP,jwt:()=>gP,json:()=>iP,ipv6:()=>pJ,ipv4:()=>tJ,invertCodec:()=>fP,intersection:()=>o1,int64:()=>JP,int32:()=>OP,int:()=>bD,instanceof:()=>dP,httpUrl:()=>yJ,hostname:()=>UP,hex:()=>IP,hash:()=>jP,guid:()=>rJ,function:()=>xP,float64:()=>EP,float32:()=>NP,file:()=>HP,exactOptional:()=>Ij,enum:()=>sD,emoji:()=>hJ,email:()=>CJ,e164:()=>$P,discriminatedUnion:()=>BP,describe:()=>cP,date:()=>RP,custom:()=>hP,cuid2:()=>dJ,cuid:()=>nJ,codec:()=>vP,cidrv6:()=>aJ,cidrv4:()=>eJ,check:()=>yP,catch:()=>zj,boolean:()=>f1,bigint:()=>LP,base64url:()=>_P,base64:()=>sJ,array:()=>m0,any:()=>WP,_function:()=>xP,_default:()=>Ej,_ZodString:()=>CD,ZodXor:()=>i1,ZodXID:()=>yD,ZodVoid:()=>d1,ZodUnknown:()=>c1,ZodUnion:()=>l0,ZodUndefined:()=>u1,ZodUUID:()=>B$,ZodURL:()=>n0,ZodULID:()=>xD,ZodType:()=>o,ZodTuple:()=>p1,ZodTransform:()=>Dj,ZodTemplateLiteral:()=>Gj,ZodSymbol:()=>w1,ZodSuccess:()=>Jj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>_j,ZodRecord:()=>Z4,ZodReadonly:()=>Xj,ZodPromise:()=>Tj,ZodPreprocess:()=>Wj,ZodPrefault:()=>Oj,ZodPipe:()=>t0,ZodOptional:()=>$U,ZodObject:()=>i0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>jj,ZodNull:()=>x1,ZodNonOptional:()=>gU,ZodNever:()=>n1,ZodNanoID:()=>fD,ZodNaN:()=>Sj,ZodMap:()=>s1,ZodMAC:()=>r1,ZodLiteral:()=>$j,ZodLazy:()=>Yj,ZodKSUID:()=>hD,ZodJWT:()=>oD,ZodIntersection:()=>t1,ZodIPv6:()=>nD,ZodIPv4:()=>cD,ZodGUID:()=>y0,ZodFunction:()=>qj,ZodFile:()=>gj,ZodExactOptional:()=>Uj,ZodEnum:()=>b4,ZodEmoji:()=>vD,ZodEmail:()=>rD,ZodE164:()=>tD,ZodDiscriminatedUnion:()=>l1,ZodDefault:()=>Nj,ZodDate:()=>d0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>p0,ZodCodec:()=>o0,ZodCatch:()=>Pj,ZodCUID2:()=>uD,ZodCUID:()=>wD,ZodCIDRv6:()=>mD,ZodCIDRv4:()=>dD,ZodBoolean:()=>r4,ZodBigIntFormat:()=>pD,ZodBigInt:()=>v4,ZodBase64URL:()=>lD,ZodBase64:()=>iD,ZodArray:()=>m1,ZodAny:()=>h1});function kD(_,$,g){let U=Object.getPrototypeOf(_),D=UR.get(U);if(!D)D=new Set,UR.set(U,D);if(D.has($))return;D.add($);for(let I in g){let j=g[I];Object.defineProperty(U,I,{configurable:!0,enumerable:!1,get(){let N=j.bind(this);return Object.defineProperty(this,I,{configurable:!0,writable:!0,enumerable:!0,value:N}),N},set(N){Object.defineProperty(this,I,{configurable:!0,writable:!0,enumerable:!0,value:N})}})}}function x0(_){return UL(H4,_)}function CJ(_){return pI(rD,_)}function rJ(_){return PD(y0,_)}function vJ(_){return eI(B$,_)}function fJ(_){return aI(B$,_)}function wJ(_){return sI(B$,_)}function uJ(_){return _1(B$,_)}function xJ(_){return zD(n0,_)}function yJ(_){return zD(n0,{protocol:$$.httpProtocol,hostname:$$.domain,...H.normalizeParams(_)})}function hJ(_){return $1(vD,_)}function cJ(_){return g1(fD,_)}function nJ(_){return D1(wD,_)}function dJ(_){return U1(uD,_)}function mJ(_){return I1(xD,_)}function iJ(_){return j1(yD,_)}function lJ(_){return N1(hD,_)}function tJ(_){return E1(cD,_)}function oJ(_){return jL(r1,_)}function pJ(_){return O1(nD,_)}function eJ(_){return A1(dD,_)}function aJ(_){return L1(mD,_)}function sJ(_){return J1(iD,_)}function _P(_){return P1(lD,_)}function $P(_){return z1(tD,_)}function gP(_){return S1(oD,_)}function DP(_,$,g={}){return w0(k4,_,$,g)}function UP(_){return w0(k4,"hostname",$$.hostname,_)}function IP(_){return w0(k4,"hex",$$.hex,_)}function jP(_,$){let g=$?.enc??"hex",U=`${_}_${g}`,D=$$[U];if(!D)throw Error(`Unrecognized hash format: ${U}`);return w0(k4,U,D,$)}function v1(_){return LL(C4,_)}function bD(_){return PL(x6,_)}function NP(_){return zL(x6,_)}function EP(_){return SL(x6,_)}function OP(_){return WL(x6,_)}function AP(_){return XL(x6,_)}function f1(_){return RL(r4,_)}function LP(_){return YL(v4,_)}function JP(_){return TL(pD,_)}function PP(_){return qL(pD,_)}function zP(_){return BL(w1,_)}function SP(_){return KL(u1,_)}function y1(_){return VL(x1,_)}function WP(){return FL(h1)}function u6(){return ML(c1)}function eD(_){return ZL(n1,_)}function XP(_){return bL(d1,_)}function RP(_){return HL(d0,_)}function m0(_,$){return rL(m1,_,$)}function GP(_){let $=_._zod.def.shape;return sD(Object.keys($))}function YP(_,$){let g={type:"object",shape:_??{},...H.normalizeParams($)};return new i0(g)}function QP(_,$){return new i0({type:"object",shape:_,catchall:eD(),...H.normalizeParams($)})}function TP(_,$){return new i0({type:"object",shape:_,catchall:u6(),...H.normalizeParams($)})}function aD(_,$){return new l0({type:"union",options:_,...H.normalizeParams($)})}function qP(_,$){return new i1({type:"union",options:_,inclusive:!1,...H.normalizeParams($)})}function BP(_,$,g){return new l1({type:"union",options:$,discriminator:_,...H.normalizeParams(g)})}function o1(_,$){return new t1({type:"intersection",left:_,right:$})}function e1(_,$,g){let U=$ instanceof l,D=U?g:$;return new p1({type:"tuple",items:_,rest:U?$:null,...H.normalizeParams(D)})}function a1(_,$,g){if(!$||!$._zod)return new Z4({type:"record",keyType:x0(),valueType:_,...H.normalizeParams($)});return new Z4({type:"record",keyType:_,valueType:$,...H.normalizeParams(g)})}function KP(_,$,g){let U=y_(_);return U._zod.values=void 0,new Z4({type:"record",keyType:U,valueType:$,...H.normalizeParams(g)})}function VP(_,$,g){return new Z4({type:"record",keyType:_,valueType:$,mode:"loose",...H.normalizeParams(g)})}function FP(_,$,g){return new s1({type:"map",keyType:_,valueType:$,...H.normalizeParams(g)})}function MP(_,$){return new _j({type:"set",valueType:_,...H.normalizeParams($)})}function sD(_,$){let g=Array.isArray(_)?Object.fromEntries(_.map((U)=>[U,U])):_;return new b4({type:"enum",entries:g,...H.normalizeParams($)})}function ZP(_,$){return new b4({type:"enum",entries:_,...H.normalizeParams($)})}function bP(_,$){return new $j({type:"literal",values:Array.isArray(_)?_:[_],...H.normalizeParams($)})}function HP(_){return vL(gj,_)}function _U(_){return new Dj({type:"transform",transform:_})}function h0(_){return new $U({type:"optional",innerType:_})}function Ij(_){return new Uj({type:"optional",innerType:_})}function c0(_){return new jj({type:"nullable",innerType:_})}function kP(_){return h0(c0(_))}function Ej(_,$){return new Nj({type:"default",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Aj(_,$){return new Oj({type:"prefault",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Lj(_,$){return new gU({type:"nonoptional",innerType:_,...H.normalizeParams($)})}function CP(_){return new Jj({type:"success",innerType:_})}function zj(_,$){return new Pj({type:"catch",innerType:_,catchValue:typeof $==="function"?$:()=>$})}function rP(_){return CL(Sj,_)}function HD(_,$){return new t0({type:"pipe",in:_,out:$})}function vP(_,$,g){return new o0({type:"pipe",in:_,out:$,transform:g.decode,reverseTransform:g.encode})}function fP(_){let $=_._zod.def;return new o0({type:"pipe",in:$.out,out:$.in,transform:$.reverseTransform,reverseTransform:$.transform})}function Rj(_){return new Xj({type:"readonly",innerType:_})}function wP(_,$){return new Gj({type:"template_literal",parts:_,...H.normalizeParams($)})}function Qj(_){return new Yj({type:"lazy",getter:_})}function uP(_){return new Tj({type:"promise",innerType:_})}function xP(_){return new qj({type:"function",input:Array.isArray(_?.input)?e1(_?.input):_?.input??m0(u6()),output:_?.output??u6()})}function yP(_){let $=new Y_({check:"custom"});return $._zod.check=_,$}function hP(_,$){return fL(p0,_??(()=>!0),$)}function Bj(_,$={}){return wL(p0,_,$)}function Kj(_,$){return uL(_,$)}function dP(_,$={}){let g=new p0({type:"custom",check:"custom",fn:(U)=>U instanceof _,abort:!0,...H.normalizeParams($)});return g._zod.bag.Class=_,g._zod.check=(U)=>{if(!(U.value instanceof _))U.issues.push({code:"invalid_type",expected:_.name,input:U.value,inst:g,path:[...g._zod.def.path??[]]})},g}function iP(_){let $=Qj(()=>{return aD([x0(_),v1(),f1(),y1(),m0($),a1(x0(),$)])});return $}function lP(_,$){return new Wj({type:"pipe",in:_U(_),out:$})}var UR,o,CD,H4,z_,rD,y0,B$,n0,vD,fD,wD,uD,xD,yD,hD,cD,r1,nD,dD,mD,iD,lD,tD,oD,k4,C4,x6,r4,v4,pD,w1,u1,x1,h1,c1,n1,d1,d0,m1,i0,l0,i1,l1,t1,p1,Z4,s1,_j,b4,$j,gj,Dj,$U,Uj,jj,Nj,Oj,gU,Jj,Pj,Sj,t0,o0,Wj,Xj,Gj,Yj,Tj,qj,p0,cP,nP,mP=(..._)=>hL({Codec:o0,Boolean:r4,String:H4},..._);var ZD=f(()=>{N$();N$();TD();YD();Q1();FD();kJ();UR=new WeakMap;o=Y("ZodType",(_,$)=>{return l.init(_,$),Object.assign(_["~standard"],{jsonSchema:{input:u0(_,"input"),output:u0(_,"output")}}),_.toJSONSchema=cL(_,{}),_.def=$,_.type=$.type,Object.defineProperty(_,"_def",{value:$}),_.parse=(g,U)=>T1(_,g,U,{callee:_.parse}),_.safeParse=(g,U)=>B1(_,g,U),_.parseAsync=async(g,U)=>q1(_,g,U,{callee:_.parseAsync}),_.safeParseAsync=async(g,U)=>K1(_,g,U),_.spa=_.safeParseAsync,_.encode=(g,U)=>V1(_,g,U),_.decode=(g,U)=>F1(_,g,U),_.encodeAsync=async(g,U)=>M1(_,g,U),_.decodeAsync=async(g,U)=>Z1(_,g,U),_.safeEncode=(g,U)=>b1(_,g,U),_.safeDecode=(g,U)=>H1(_,g,U),_.safeEncodeAsync=async(g,U)=>k1(_,g,U),_.safeDecodeAsync=async(g,U)=>C1(_,g,U),kD(_,"ZodType",{check(...g){let U=this.def;return this.clone(H.mergeDefs(U,{checks:[...U.checks??[],...g.map((D)=>typeof D==="function"?{_zod:{check:D,def:{check:"custom"},onattach:[]}}:D)]}),{parent:!0})},with(...g){return this.check(...g)},clone(g,U){return y_(this,g,U)},brand(){return this},register(g,U){return g.add(this,U),this},refine(g,U){return this.check(Bj(g,U))},superRefine(g,U){return this.check(Kj(g,U))},overwrite(g){return this.check(z$(g))},optional(){return h0(this)},exactOptional(){return Ij(this)},nullable(){return c0(this)},nullish(){return h0(c0(this))},nonoptional(g){return Lj(this,g)},array(){return m0(this)},or(g){return aD([this,g])},and(g){return o1(this,g)},transform(g){return HD(this,_U(g))},default(g){return Ej(this,g)},prefault(g){return Aj(this,g)},catch(g){return zj(this,g)},pipe(g){return HD(this,g)},readonly(){return Rj(this)},describe(g){let U=this.clone();return w_.add(U,{description:g}),U},meta(...g){if(g.length===0)return w_.get(this);let U=this.clone();return w_.add(U,g[0]),U},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(g){return g(this)}}),Object.defineProperty(_,"description",{get(){return w_.get(_)?.description},configurable:!0}),_}),CD=Y("_ZodString",(_,$)=>{S4.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,D,I)=>nL(_,U,D,I);let g=_._zod.bag;_.format=g.format??null,_.minLength=g.minimum??null,_.maxLength=g.maximum??null,kD(_,"_ZodString",{regex(...U){return this.check(W4(...U))},includes(...U){return this.check(G4(...U))},startsWith(...U){return this.check(Y4(...U))},endsWith(...U){return this.check(Q4(...U))},min(...U){return this.check(y$(...U))},max(...U){return this.check(C6(...U))},length(...U){return this.check(r6(...U))},nonempty(...U){return this.check(y$(1,...U))},lowercase(U){return this.check(X4(U))},uppercase(U){return this.check(R4(U))},trim(){return this.check(B4())},normalize(...U){return this.check(q4(...U))},toLowerCase(){return this.check(K4())},toUpperCase(){return this.check(V4())},slugify(){return this.check(F4())}})}),H4=Y("ZodString",(_,$)=>{S4.init(_,$),CD.init(_,$),_.email=(g)=>_.check(pI(rD,g)),_.url=(g)=>_.check(zD(n0,g)),_.jwt=(g)=>_.check(S1(oD,g)),_.emoji=(g)=>_.check($1(vD,g)),_.guid=(g)=>_.check(PD(y0,g)),_.uuid=(g)=>_.check(eI(B$,g)),_.uuidv4=(g)=>_.check(aI(B$,g)),_.uuidv6=(g)=>_.check(sI(B$,g)),_.uuidv7=(g)=>_.check(_1(B$,g)),_.nanoid=(g)=>_.check(g1(fD,g)),_.guid=(g)=>_.check(PD(y0,g)),_.cuid=(g)=>_.check(D1(wD,g)),_.cuid2=(g)=>_.check(U1(uD,g)),_.ulid=(g)=>_.check(I1(xD,g)),_.base64=(g)=>_.check(J1(iD,g)),_.base64url=(g)=>_.check(P1(lD,g)),_.xid=(g)=>_.check(j1(yD,g)),_.ksuid=(g)=>_.check(N1(hD,g)),_.ipv4=(g)=>_.check(E1(cD,g)),_.ipv6=(g)=>_.check(O1(nD,g)),_.cidrv4=(g)=>_.check(A1(dD,g)),_.cidrv6=(g)=>_.check(L1(mD,g)),_.e164=(g)=>_.check(z1(tD,g)),_.datetime=(g)=>_.check(FJ(g)),_.date=(g)=>_.check(MJ(g)),_.time=(g)=>_.check(ZJ(g)),_.duration=(g)=>_.check(bJ(g))});z_=Y("ZodStringFormat",(_,$)=>{R_.init(_,$),CD.init(_,$)}),rD=Y("ZodEmail",(_,$)=>{p2.init(_,$),z_.init(_,$)});y0=Y("ZodGUID",(_,$)=>{t2.init(_,$),z_.init(_,$)});B$=Y("ZodUUID",(_,$)=>{o2.init(_,$),z_.init(_,$)});n0=Y("ZodURL",(_,$)=>{e2.init(_,$),z_.init(_,$)});vD=Y("ZodEmoji",(_,$)=>{a2.init(_,$),z_.init(_,$)});fD=Y("ZodNanoID",(_,$)=>{s2.init(_,$),z_.init(_,$)});wD=Y("ZodCUID",(_,$)=>{_O.init(_,$),z_.init(_,$)});uD=Y("ZodCUID2",(_,$)=>{$O.init(_,$),z_.init(_,$)});xD=Y("ZodULID",(_,$)=>{gO.init(_,$),z_.init(_,$)});yD=Y("ZodXID",(_,$)=>{DO.init(_,$),z_.init(_,$)});hD=Y("ZodKSUID",(_,$)=>{UO.init(_,$),z_.init(_,$)});cD=Y("ZodIPv4",(_,$)=>{OO.init(_,$),z_.init(_,$)});r1=Y("ZodMAC",(_,$)=>{LO.init(_,$),z_.init(_,$)});nD=Y("ZodIPv6",(_,$)=>{AO.init(_,$),z_.init(_,$)});dD=Y("ZodCIDRv4",(_,$)=>{JO.init(_,$),z_.init(_,$)});mD=Y("ZodCIDRv6",(_,$)=>{PO.init(_,$),z_.init(_,$)});iD=Y("ZodBase64",(_,$)=>{SO.init(_,$),z_.init(_,$)});lD=Y("ZodBase64URL",(_,$)=>{WO.init(_,$),z_.init(_,$)});tD=Y("ZodE164",(_,$)=>{XO.init(_,$),z_.init(_,$)});oD=Y("ZodJWT",(_,$)=>{RO.init(_,$),z_.init(_,$)});k4=Y("ZodCustomStringFormat",(_,$)=>{GO.init(_,$),z_.init(_,$)});C4=Y("ZodNumber",(_,$)=>{nI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,D,I)=>dL(_,U,D,I),kD(_,"ZodNumber",{gt(U,D){return this.check(T$(U,D))},gte(U,D){return this.check(h_(U,D))},min(U,D){return this.check(h_(U,D))},lt(U,D){return this.check(Q$(U,D))},lte(U,D){return this.check(g$(U,D))},max(U,D){return this.check(g$(U,D))},int(U){return this.check(bD(U))},safe(U){return this.check(bD(U))},positive(U){return this.check(T$(0,U))},nonnegative(U){return this.check(h_(0,U))},negative(U){return this.check(Q$(0,U))},nonpositive(U){return this.check(g$(0,U))},multipleOf(U,D){return this.check(U6(U,D))},step(U,D){return this.check(U6(U,D))},finite(){return this}});let g=_._zod.bag;_.minValue=Math.max(g.minimum??Number.NEGATIVE_INFINITY,g.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,_.maxValue=Math.min(g.maximum??Number.POSITIVE_INFINITY,g.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,_.isInt=(g.format??"").includes("int")||Number.isSafeInteger(g.multipleOf??0.5),_.isFinite=!0,_.format=g.format??null});x6=Y("ZodNumberFormat",(_,$)=>{YO.init(_,$),C4.init(_,$)});r4=Y("ZodBoolean",(_,$)=>{UD.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>mL(_,g,U,D)});v4=Y("ZodBigInt",(_,$)=>{dI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,D,I)=>iL(_,U,D,I),_.gte=(U,D)=>_.check(h_(U,D)),_.min=(U,D)=>_.check(h_(U,D)),_.gt=(U,D)=>_.check(T$(U,D)),_.gte=(U,D)=>_.check(h_(U,D)),_.min=(U,D)=>_.check(h_(U,D)),_.lt=(U,D)=>_.check(Q$(U,D)),_.lte=(U,D)=>_.check(g$(U,D)),_.max=(U,D)=>_.check(g$(U,D)),_.positive=(U)=>_.check(T$(BigInt(0),U)),_.negative=(U)=>_.check(Q$(BigInt(0),U)),_.nonpositive=(U)=>_.check(g$(BigInt(0),U)),_.nonnegative=(U)=>_.check(h_(BigInt(0),U)),_.multipleOf=(U,D)=>_.check(U6(U,D));let g=_._zod.bag;_.minValue=g.minimum??null,_.maxValue=g.maximum??null,_.format=g.format??null});pD=Y("ZodBigIntFormat",(_,$)=>{QO.init(_,$),v4.init(_,$)});w1=Y("ZodSymbol",(_,$)=>{TO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>lL(_,g,U,D)});u1=Y("ZodUndefined",(_,$)=>{qO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>oL(_,g,U,D)});x1=Y("ZodNull",(_,$)=>{BO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>tL(_,g,U,D)});h1=Y("ZodAny",(_,$)=>{KO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>aL(_,g,U,D)});c1=Y("ZodUnknown",(_,$)=>{VO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>sL(_,g,U,D)});n1=Y("ZodNever",(_,$)=>{FO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>eL(_,g,U,D)});d1=Y("ZodVoid",(_,$)=>{MO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>pL(_,g,U,D)});d0=Y("ZodDate",(_,$)=>{ZO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,D,I)=>_J(_,U,D,I),_.min=(U,D)=>_.check(h_(U,D)),_.max=(U,D)=>_.check(g$(U,D));let g=_._zod.bag;_.minDate=g.minimum?new Date(g.minimum):null,_.maxDate=g.maximum?new Date(g.maximum):null});m1=Y("ZodArray",(_,$)=>{bO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>JJ(_,g,U,D),_.element=$.element,kD(_,"ZodArray",{min(g,U){return this.check(y$(g,U))},nonempty(g){return this.check(y$(1,g))},max(g,U){return this.check(C6(g,U))},length(g,U){return this.check(r6(g,U))},unwrap(){return this.element}})});i0=Y("ZodObject",(_,$)=>{HO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>PJ(_,g,U,D),H.defineLazy(_,"shape",()=>{return $.shape}),kD(_,"ZodObject",{keyof(){return sD(Object.keys(this._zod.def.shape))},catchall(g){return this.clone({...this._zod.def,catchall:g})},passthrough(){return this.clone({...this._zod.def,catchall:u6()})},loose(){return this.clone({...this._zod.def,catchall:u6()})},strict(){return this.clone({...this._zod.def,catchall:eD()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(g){return H.extend(this,g)},safeExtend(g){return H.safeExtend(this,g)},merge(g){return H.merge(this,g)},pick(g){return H.pick(this,g)},omit(g){return H.omit(this,g)},partial(...g){return H.partial($U,this,g[0])},required(...g){return H.required(gU,this,g[0])}})});l0=Y("ZodUnion",(_,$)=>{ID.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>R1(_,g,U,D),_.options=$.options});i1=Y("ZodXor",(_,$)=>{l0.init(_,$),kO.init(_,$),_._zod.processJSONSchema=(g,U,D)=>R1(_,g,U,D),_.options=$.options});l1=Y("ZodDiscriminatedUnion",(_,$)=>{l0.init(_,$),CO.init(_,$)});t1=Y("ZodIntersection",(_,$)=>{rO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>zJ(_,g,U,D)});p1=Y("ZodTuple",(_,$)=>{mI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>SJ(_,g,U,D),_.rest=(g)=>_.clone({..._._zod.def,rest:g})});Z4=Y("ZodRecord",(_,$)=>{vO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>WJ(_,g,U,D),_.keyType=$.keyType,_.valueType=$.valueType});s1=Y("ZodMap",(_,$)=>{fO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>AJ(_,g,U,D),_.keyType=$.keyType,_.valueType=$.valueType,_.min=(...g)=>_.check(q$(...g)),_.nonempty=(g)=>_.check(q$(1,g)),_.max=(...g)=>_.check(I6(...g)),_.size=(...g)=>_.check(k6(...g))});_j=Y("ZodSet",(_,$)=>{wO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>LJ(_,g,U,D),_.min=(...g)=>_.check(q$(...g)),_.nonempty=(g)=>_.check(q$(1,g)),_.max=(...g)=>_.check(I6(...g)),_.size=(...g)=>_.check(k6(...g))});b4=Y("ZodEnum",(_,$)=>{uO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,D,I)=>$J(_,U,D,I),_.enum=$.entries,_.options=Object.values($.entries);let g=new Set(Object.keys($.entries));_.extract=(U,D)=>{let I={};for(let j of U)if(g.has(j))I[j]=$.entries[j];else throw Error(`Key ${j} not found in enum`);return new b4({...$,checks:[],...H.normalizeParams(D),entries:I})},_.exclude=(U,D)=>{let I={...$.entries};for(let j of U)if(g.has(j))delete I[j];else throw Error(`Key ${j} not found in enum`);return new b4({...$,checks:[],...H.normalizeParams(D),entries:I})}});$j=Y("ZodLiteral",(_,$)=>{xO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>gJ(_,g,U,D),_.values=new Set($.values),Object.defineProperty(_,"value",{get(){if($.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return $.values[0]}})});gj=Y("ZodFile",(_,$)=>{yO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>IJ(_,g,U,D),_.min=(g,U)=>_.check(q$(g,U)),_.max=(g,U)=>_.check(I6(g,U)),_.mime=(g,U)=>_.check(T4(Array.isArray(g)?g:[g],U))});Dj=Y("ZodTransform",(_,$)=>{hO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>OJ(_,g,U,D),_._zod.parse=(g,U)=>{if(U.direction==="backward")throw new L4(_.constructor.name);g.addIssue=(I)=>{if(typeof I==="string")g.issues.push(H.issue(I,g.value,$));else{let j=I;if(j.fatal)j.continue=!1;j.code??(j.code="custom"),j.input??(j.input=g.value),j.inst??(j.inst=_),g.issues.push(H.issue(j))}};let D=$.transform(g.value,g);if(D instanceof Promise)return D.then((I)=>{return g.value=I,g.fallback=!0,g});return g.value=D,g.fallback=!0,g}});$U=Y("ZodOptional",(_,$)=>{iI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>G1(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});Uj=Y("ZodExactOptional",(_,$)=>{cO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>G1(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});jj=Y("ZodNullable",(_,$)=>{nO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>XJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});Nj=Y("ZodDefault",(_,$)=>{dO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>GJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType,_.removeDefault=_.unwrap});Oj=Y("ZodPrefault",(_,$)=>{mO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>YJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});gU=Y("ZodNonOptional",(_,$)=>{iO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>RJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});Jj=Y("ZodSuccess",(_,$)=>{lO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>jJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});Pj=Y("ZodCatch",(_,$)=>{tO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>QJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType,_.removeCatch=_.unwrap});Sj=Y("ZodNaN",(_,$)=>{oO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>DJ(_,g,U,D)});t0=Y("ZodPipe",(_,$)=>{lI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>TJ(_,g,U,D),_.in=$.in,_.out=$.out});o0=Y("ZodCodec",(_,$)=>{t0.init(_,$),jD.init(_,$)});Wj=Y("ZodPreprocess",(_,$)=>{t0.init(_,$),pO.init(_,$)}),Xj=Y("ZodReadonly",(_,$)=>{eO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>qJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});Gj=Y("ZodTemplateLiteral",(_,$)=>{aO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>UJ(_,g,U,D)});Yj=Y("ZodLazy",(_,$)=>{$A.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>KJ(_,g,U,D),_.unwrap=()=>_._zod.def.getter()});Tj=Y("ZodPromise",(_,$)=>{_A.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>BJ(_,g,U,D),_.unwrap=()=>_._zod.def.innerType});qj=Y("ZodFunction",(_,$)=>{sO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>EJ(_,g,U,D)});p0=Y("ZodCustom",(_,$)=>{gA.init(_,$),o.init(_,$),_._zod.processJSONSchema=(g,U,D)=>NJ(_,g,U,D)});cP=xL,nP=yL});function jR(_){Z_({customError:_})}function NR(){return Z_().customError}var IR,Vj;var ER=f(()=>{N$();IR={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(_){})(Vj||(Vj={}))});function TF(_,$){let g=_.$schema;if(g==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(g==="http://json-schema.org/draft-07/schema#")return"draft-7";if(g==="http://json-schema.org/draft-04/schema#")return"draft-4";return $??"draft-2020-12"}function qF(_,$){if(!_.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let g=_.slice(1).split("/").filter(Boolean);if(g.length===0)return $.rootSchema;let U=$.version==="draft-2020-12"?"$defs":"definitions";if(g[0]===U){let D=g[1];if(!D||!$.defs[D])throw Error(`Reference not found: ${_}`);return $.defs[D]}throw Error(`Reference not found: ${_}`)}function OR(_,$){if(_.not!==void 0){if(typeof _.not==="object"&&Object.keys(_.not).length===0)return w.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(_.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(_.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(_.if!==void 0||_.then!==void 0||_.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(_.dependentSchemas!==void 0||_.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(_.$ref){let D=_.$ref;if($.refs.has(D))return $.refs.get(D);if($.processing.has(D))return w.lazy(()=>{if(!$.refs.has(D))throw Error(`Circular reference not resolved: ${D}`);return $.refs.get(D)});$.processing.add(D);let I=qF(D,$),j=c_(I,$);return $.refs.set(D,j),$.processing.delete(D),j}if(_.enum!==void 0){let D=_.enum;if($.version==="openapi-3.0"&&_.nullable===!0&&D.length===1&&D[0]===null)return w.null();if(D.length===0)return w.never();if(D.length===1)return w.literal(D[0]);if(D.every((j)=>typeof j==="string"))return w.enum(D);let I=D.map((j)=>w.literal(j));if(I.length<2)return I[0];return w.union([I[0],I[1],...I.slice(2)])}if(_.const!==void 0)return w.literal(_.const);let g=_.type;if(Array.isArray(g)){let D=g.map((I)=>{let j={..._,type:I};return OR(j,$)});if(D.length===0)return w.never();if(D.length===1)return D[0];return w.union(D)}if(!g)return w.any();let U;switch(g){case"string":{let D=w.string();if(_.format){let I=_.format;if(I==="email")D=D.check(w.email());else if(I==="uri"||I==="uri-reference")D=D.check(w.url());else if(I==="uuid"||I==="guid")D=D.check(w.uuid());else if(I==="date-time")D=D.check(w.iso.datetime());else if(I==="date")D=D.check(w.iso.date());else if(I==="time")D=D.check(w.iso.time());else if(I==="duration")D=D.check(w.iso.duration());else if(I==="ipv4")D=D.check(w.ipv4());else if(I==="ipv6")D=D.check(w.ipv6());else if(I==="mac")D=D.check(w.mac());else if(I==="cidr")D=D.check(w.cidrv4());else if(I==="cidr-v6")D=D.check(w.cidrv6());else if(I==="base64")D=D.check(w.base64());else if(I==="base64url")D=D.check(w.base64url());else if(I==="e164")D=D.check(w.e164());else if(I==="jwt")D=D.check(w.jwt());else if(I==="emoji")D=D.check(w.emoji());else if(I==="nanoid")D=D.check(w.nanoid());else if(I==="cuid")D=D.check(w.cuid());else if(I==="cuid2")D=D.check(w.cuid2());else if(I==="ulid")D=D.check(w.ulid());else if(I==="xid")D=D.check(w.xid());else if(I==="ksuid")D=D.check(w.ksuid())}if(typeof _.minLength==="number")D=D.min(_.minLength);if(typeof _.maxLength==="number")D=D.max(_.maxLength);if(_.pattern)D=D.regex(new RegExp(_.pattern));U=D;break}case"number":case"integer":{let D=g==="integer"?w.number().int():w.number();if(typeof _.minimum==="number")D=D.min(_.minimum);if(typeof _.maximum==="number")D=D.max(_.maximum);if(typeof _.exclusiveMinimum==="number")D=D.gt(_.exclusiveMinimum);else if(_.exclusiveMinimum===!0&&typeof _.minimum==="number")D=D.gt(_.minimum);if(typeof _.exclusiveMaximum==="number")D=D.lt(_.exclusiveMaximum);else if(_.exclusiveMaximum===!0&&typeof _.maximum==="number")D=D.lt(_.maximum);if(typeof _.multipleOf==="number")D=D.multipleOf(_.multipleOf);U=D;break}case"boolean":{U=w.boolean();break}case"null":{U=w.null();break}case"object":{let D={},I=_.properties||{},j=new Set(_.required||[]);for(let[O,A]of Object.entries(I)){let L=c_(A,$);D[O]=j.has(O)?L:L.optional()}if(_.propertyNames){let O=c_(_.propertyNames,$),A=_.additionalProperties&&typeof _.additionalProperties==="object"?c_(_.additionalProperties,$):w.any();if(Object.keys(D).length===0){U=w.record(O,A);break}let L=w.object(D).passthrough(),z=w.looseRecord(O,A);U=w.intersection(L,z);break}if(_.patternProperties){let O=_.patternProperties,A=Object.keys(O),L=[];for(let W of A){let J=c_(O[W],$),P=w.string().regex(new RegExp(W));L.push(w.looseRecord(P,J))}let z=[];if(Object.keys(D).length>0)z.push(w.object(D).passthrough());if(z.push(...L),z.length===0)U=w.object({}).passthrough();else if(z.length===1)U=z[0];else{let W=w.intersection(z[0],z[1]);for(let J=2;Jc_(O,$)),N=I&&typeof I==="object"&&!Array.isArray(I)?c_(I,$):void 0;if(N)U=w.tuple(j).rest(N);else U=w.tuple(j);if(typeof _.minItems==="number")U=U.check(w.minLength(_.minItems));if(typeof _.maxItems==="number")U=U.check(w.maxLength(_.maxItems))}else if(Array.isArray(I)){let j=I.map((O)=>c_(O,$)),N=_.additionalItems&&typeof _.additionalItems==="object"?c_(_.additionalItems,$):void 0;if(N)U=w.tuple(j).rest(N);else U=w.tuple(j);if(typeof _.minItems==="number")U=U.check(w.minLength(_.minItems));if(typeof _.maxItems==="number")U=U.check(w.maxLength(_.maxItems))}else if(I!==void 0){let j=c_(I,$),N=w.array(j);if(typeof _.minItems==="number")N=N.min(_.minItems);if(typeof _.maxItems==="number")N=N.max(_.maxItems);U=N}else U=w.array(w.any());break}default:throw Error(`Unsupported type: ${g}`)}return U}function c_(_,$){if(typeof _==="boolean")return _?w.any():w.never();let g=OR(_,$),U=_.type||_.enum!==void 0||_.const!==void 0;if(_.anyOf&&Array.isArray(_.anyOf)){let N=_.anyOf.map((A)=>c_(A,$)),O=w.union(N);g=U?w.intersection(g,O):O}if(_.oneOf&&Array.isArray(_.oneOf)){let N=_.oneOf.map((A)=>c_(A,$)),O=w.xor(N);g=U?w.intersection(g,O):O}if(_.allOf&&Array.isArray(_.allOf))if(_.allOf.length===0)g=U?g:w.any();else{let N=U?g:c_(_.allOf[0],$),O=U?0:1;for(let A=O;A<_.allOf.length;A++)N=w.intersection(N,c_(_.allOf[A],$));g=N}if(_.nullable===!0&&$.version==="openapi-3.0")g=w.nullable(g);if(_.readOnly===!0)g=w.readonly(g);if(_.default!==void 0)g=g.default(_.default);let D={},I=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let N of I)if(N in _)D[N]=_[N];let j=["contentEncoding","contentMediaType","contentSchema"];for(let N of j)if(N in _)D[N]=_[N];for(let N of Object.keys(_))if(!QF.has(N))D[N]=_[N];if(Object.keys(D).length>0)$.registry.add(g,D);if(_.description)g=g.describe(_.description);return g}function tP(_,$){if(typeof _==="boolean")return _?w.any():w.never();let g;try{g=JSON.parse(JSON.stringify(_))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let U=TF(g,$?.defaultTarget),D=g.$defs||g.definitions||{},I={version:U,defs:D,refs:new Map,processing:new Set,rootSchema:g,registry:$?.registry??w_};return c_(g,I)}var w,QF;var AR=f(()=>{JD();Q1();FD();ZD();w={...MD,...Y1,iso:M4},QF=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var Fj={};r$(Fj,{string:()=>BF,number:()=>KF,date:()=>MF,boolean:()=>VF,bigint:()=>FF});function BF(_){return IL(H4,_)}function KF(_){return JL(C4,_)}function VF(_){return GL(r4,_)}function FF(_){return QL(v4,_)}function MF(_){return kL(d0,_)}var LR=f(()=>{N$();ZD()});var Mj={};r$(Mj,{xor:()=>qP,xid:()=>iJ,void:()=>XP,uuidv7:()=>uJ,uuidv6:()=>wJ,uuidv4:()=>fJ,uuid:()=>vJ,util:()=>H,url:()=>xJ,uppercase:()=>R4,unknown:()=>u6,union:()=>aD,undefined:()=>SP,ulid:()=>mJ,uint64:()=>PP,uint32:()=>AP,tuple:()=>e1,trim:()=>B4,treeifyError:()=>QI,transform:()=>_U,toUpperCase:()=>V4,toLowerCase:()=>K4,toJSONSchema:()=>QD,templateLiteral:()=>wP,symbol:()=>zP,superRefine:()=>Kj,success:()=>CP,stringbool:()=>mP,stringFormat:()=>DP,string:()=>x0,strictObject:()=>QP,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,setErrorMap:()=>jR,set:()=>MP,safeParseAsync:()=>K1,safeParse:()=>B1,safeEncodeAsync:()=>k1,safeEncode:()=>b1,safeDecodeAsync:()=>C1,safeDecode:()=>H1,registry:()=>LD,regexes:()=>$$,regex:()=>W4,refine:()=>Bj,record:()=>a1,readonly:()=>Rj,property:()=>GD,promise:()=>uP,prettifyError:()=>TI,preprocess:()=>lP,prefault:()=>Aj,positive:()=>SD,pipe:()=>HD,partialRecord:()=>KP,parseAsync:()=>q1,parse:()=>T1,overwrite:()=>z$,optional:()=>h0,object:()=>YP,number:()=>v1,nullish:()=>kP,nullable:()=>c0,null:()=>y1,normalize:()=>q4,nonpositive:()=>XD,nonoptional:()=>Lj,nonnegative:()=>RD,never:()=>eD,negative:()=>WD,nativeEnum:()=>ZP,nanoid:()=>cJ,nan:()=>rP,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,meta:()=>nP,maxSize:()=>I6,maxLength:()=>C6,map:()=>FP,mac:()=>oJ,lte:()=>g$,lt:()=>Q$,lowercase:()=>X4,looseRecord:()=>VP,looseObject:()=>TP,locales:()=>f0,literal:()=>bP,length:()=>r6,lazy:()=>Qj,ksuid:()=>lJ,keyof:()=>GP,jwt:()=>gP,json:()=>iP,iso:()=>M4,ipv6:()=>pJ,ipv4:()=>tJ,invertCodec:()=>fP,intersection:()=>o1,int64:()=>JP,int32:()=>OP,int:()=>bD,instanceof:()=>dP,includes:()=>G4,httpUrl:()=>yJ,hostname:()=>UP,hex:()=>IP,hash:()=>jP,guid:()=>rJ,gte:()=>h_,gt:()=>T$,globalRegistry:()=>w_,getErrorMap:()=>NR,function:()=>xP,fromJSONSchema:()=>tP,formatError:()=>Z0,float64:()=>EP,float32:()=>NP,flattenError:()=>M0,file:()=>HP,exactOptional:()=>Ij,enum:()=>sD,endsWith:()=>Q4,encodeAsync:()=>M1,encode:()=>V1,emoji:()=>hJ,email:()=>CJ,e164:()=>$P,discriminatedUnion:()=>BP,describe:()=>cP,decodeAsync:()=>Z1,decode:()=>F1,date:()=>RP,custom:()=>hP,cuid2:()=>dJ,cuid:()=>nJ,core:()=>h$,config:()=>Z_,coerce:()=>Fj,codec:()=>vP,clone:()=>y_,cidrv6:()=>aJ,cidrv4:()=>eJ,check:()=>yP,catch:()=>zj,boolean:()=>f1,bigint:()=>LP,base64url:()=>_P,base64:()=>sJ,array:()=>m0,any:()=>WP,_function:()=>xP,_default:()=>Ej,_ZodString:()=>CD,ZodXor:()=>i1,ZodXID:()=>yD,ZodVoid:()=>d1,ZodUnknown:()=>c1,ZodUnion:()=>l0,ZodUndefined:()=>u1,ZodUUID:()=>B$,ZodURL:()=>n0,ZodULID:()=>xD,ZodType:()=>o,ZodTuple:()=>p1,ZodTransform:()=>Dj,ZodTemplateLiteral:()=>Gj,ZodSymbol:()=>w1,ZodSuccess:()=>Jj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>_j,ZodRecord:()=>Z4,ZodRealError:()=>o_,ZodReadonly:()=>Xj,ZodPromise:()=>Tj,ZodPreprocess:()=>Wj,ZodPrefault:()=>Oj,ZodPipe:()=>t0,ZodOptional:()=>$U,ZodObject:()=>i0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>jj,ZodNull:()=>x1,ZodNonOptional:()=>gU,ZodNever:()=>n1,ZodNanoID:()=>fD,ZodNaN:()=>Sj,ZodMap:()=>s1,ZodMAC:()=>r1,ZodLiteral:()=>$j,ZodLazy:()=>Yj,ZodKSUID:()=>hD,ZodJWT:()=>oD,ZodIssueCode:()=>IR,ZodIntersection:()=>t1,ZodISOTime:()=>KD,ZodISODuration:()=>VD,ZodISODateTime:()=>qD,ZodISODate:()=>BD,ZodIPv6:()=>nD,ZodIPv4:()=>cD,ZodGUID:()=>y0,ZodFunction:()=>qj,ZodFirstPartyTypeKind:()=>Vj,ZodFile:()=>gj,ZodExactOptional:()=>Uj,ZodError:()=>DR,ZodEnum:()=>b4,ZodEmoji:()=>vD,ZodEmail:()=>rD,ZodE164:()=>tD,ZodDiscriminatedUnion:()=>l1,ZodDefault:()=>Nj,ZodDate:()=>d0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>p0,ZodCodec:()=>o0,ZodCatch:()=>Pj,ZodCUID2:()=>uD,ZodCUID:()=>wD,ZodCIDRv6:()=>mD,ZodCIDRv4:()=>dD,ZodBoolean:()=>r4,ZodBigIntFormat:()=>pD,ZodBigInt:()=>v4,ZodBase64URL:()=>lD,ZodBase64:()=>iD,ZodArray:()=>m1,ZodAny:()=>h1,TimePrecision:()=>W1,NEVER:()=>XI,$output:()=>tI,$input:()=>oI,$brand:()=>RI});var oP=f(()=>{N$();N$();PA();N$();TD();AR();gL();FD();FD();LR();ZD();Q1();HJ();kJ();ER();Z_(ND())});var JR={};r$(JR,{z:()=>Mj,xor:()=>qP,xid:()=>iJ,void:()=>XP,uuidv7:()=>uJ,uuidv6:()=>wJ,uuidv4:()=>fJ,uuid:()=>vJ,util:()=>H,url:()=>xJ,uppercase:()=>R4,unknown:()=>u6,union:()=>aD,undefined:()=>SP,ulid:()=>mJ,uint64:()=>PP,uint32:()=>AP,tuple:()=>e1,trim:()=>B4,treeifyError:()=>QI,transform:()=>_U,toUpperCase:()=>V4,toLowerCase:()=>K4,toJSONSchema:()=>QD,templateLiteral:()=>wP,symbol:()=>zP,superRefine:()=>Kj,success:()=>CP,stringbool:()=>mP,stringFormat:()=>DP,string:()=>x0,strictObject:()=>QP,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,setErrorMap:()=>jR,set:()=>MP,safeParseAsync:()=>K1,safeParse:()=>B1,safeEncodeAsync:()=>k1,safeEncode:()=>b1,safeDecodeAsync:()=>C1,safeDecode:()=>H1,registry:()=>LD,regexes:()=>$$,regex:()=>W4,refine:()=>Bj,record:()=>a1,readonly:()=>Rj,property:()=>GD,promise:()=>uP,prettifyError:()=>TI,preprocess:()=>lP,prefault:()=>Aj,positive:()=>SD,pipe:()=>HD,partialRecord:()=>KP,parseAsync:()=>q1,parse:()=>T1,overwrite:()=>z$,optional:()=>h0,object:()=>YP,number:()=>v1,nullish:()=>kP,nullable:()=>c0,null:()=>y1,normalize:()=>q4,nonpositive:()=>XD,nonoptional:()=>Lj,nonnegative:()=>RD,never:()=>eD,negative:()=>WD,nativeEnum:()=>ZP,nanoid:()=>cJ,nan:()=>rP,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,meta:()=>nP,maxSize:()=>I6,maxLength:()=>C6,map:()=>FP,mac:()=>oJ,lte:()=>g$,lt:()=>Q$,lowercase:()=>X4,looseRecord:()=>VP,looseObject:()=>TP,locales:()=>f0,literal:()=>bP,length:()=>r6,lazy:()=>Qj,ksuid:()=>lJ,keyof:()=>GP,jwt:()=>gP,json:()=>iP,iso:()=>M4,ipv6:()=>pJ,ipv4:()=>tJ,invertCodec:()=>fP,intersection:()=>o1,int64:()=>JP,int32:()=>OP,int:()=>bD,instanceof:()=>dP,includes:()=>G4,httpUrl:()=>yJ,hostname:()=>UP,hex:()=>IP,hash:()=>jP,guid:()=>rJ,gte:()=>h_,gt:()=>T$,globalRegistry:()=>w_,getErrorMap:()=>NR,function:()=>xP,fromJSONSchema:()=>tP,formatError:()=>Z0,float64:()=>EP,float32:()=>NP,flattenError:()=>M0,file:()=>HP,exactOptional:()=>Ij,enum:()=>sD,endsWith:()=>Q4,encodeAsync:()=>M1,encode:()=>V1,emoji:()=>hJ,email:()=>CJ,e164:()=>$P,discriminatedUnion:()=>BP,describe:()=>cP,default:()=>ZF,decodeAsync:()=>Z1,decode:()=>F1,date:()=>RP,custom:()=>hP,cuid2:()=>dJ,cuid:()=>nJ,core:()=>h$,config:()=>Z_,coerce:()=>Fj,codec:()=>vP,clone:()=>y_,cidrv6:()=>aJ,cidrv4:()=>eJ,check:()=>yP,catch:()=>zj,boolean:()=>f1,bigint:()=>LP,base64url:()=>_P,base64:()=>sJ,array:()=>m0,any:()=>WP,_function:()=>xP,_default:()=>Ej,_ZodString:()=>CD,ZodXor:()=>i1,ZodXID:()=>yD,ZodVoid:()=>d1,ZodUnknown:()=>c1,ZodUnion:()=>l0,ZodUndefined:()=>u1,ZodUUID:()=>B$,ZodURL:()=>n0,ZodULID:()=>xD,ZodType:()=>o,ZodTuple:()=>p1,ZodTransform:()=>Dj,ZodTemplateLiteral:()=>Gj,ZodSymbol:()=>w1,ZodSuccess:()=>Jj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>_j,ZodRecord:()=>Z4,ZodRealError:()=>o_,ZodReadonly:()=>Xj,ZodPromise:()=>Tj,ZodPreprocess:()=>Wj,ZodPrefault:()=>Oj,ZodPipe:()=>t0,ZodOptional:()=>$U,ZodObject:()=>i0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>jj,ZodNull:()=>x1,ZodNonOptional:()=>gU,ZodNever:()=>n1,ZodNanoID:()=>fD,ZodNaN:()=>Sj,ZodMap:()=>s1,ZodMAC:()=>r1,ZodLiteral:()=>$j,ZodLazy:()=>Yj,ZodKSUID:()=>hD,ZodJWT:()=>oD,ZodIssueCode:()=>IR,ZodIntersection:()=>t1,ZodISOTime:()=>KD,ZodISODuration:()=>VD,ZodISODateTime:()=>qD,ZodISODate:()=>BD,ZodIPv6:()=>nD,ZodIPv4:()=>cD,ZodGUID:()=>y0,ZodFunction:()=>qj,ZodFirstPartyTypeKind:()=>Vj,ZodFile:()=>gj,ZodExactOptional:()=>Uj,ZodError:()=>DR,ZodEnum:()=>b4,ZodEmoji:()=>vD,ZodEmail:()=>rD,ZodE164:()=>tD,ZodDiscriminatedUnion:()=>l1,ZodDefault:()=>Nj,ZodDate:()=>d0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>p0,ZodCodec:()=>o0,ZodCatch:()=>Pj,ZodCUID2:()=>uD,ZodCUID:()=>wD,ZodCIDRv6:()=>mD,ZodCIDRv4:()=>dD,ZodBoolean:()=>r4,ZodBigIntFormat:()=>pD,ZodBigInt:()=>v4,ZodBase64URL:()=>lD,ZodBase64:()=>iD,ZodArray:()=>m1,ZodAny:()=>h1,TimePrecision:()=>W1,NEVER:()=>XI,$output:()=>tI,$input:()=>oI,$brand:()=>RI});var ZF;var PR=f(()=>{oP();oP();ZF=Mj});var qU=e6((Qr)=>{class o3 extends Error{constructor(_,$,g){super(g);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=_,this.nestedError=void 0}}class _8 extends o3{constructor(_){super(1,"commander.invalidArgument",_);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Qr.CommanderError=o3;Qr.InvalidArgumentError=_8});var zN=e6((Vr)=>{var{InvalidArgumentError:Br}=qU();class $8{constructor(_,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,_[0]){case"<":this.required=!0,this._name=_.slice(1,-1);break;case"[":this.required=!1,this._name=_.slice(1,-1);break;default:this.required=!0,this._name=_;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(_,$){if($===this.defaultValue||!Array.isArray($))return[_];return $.concat(_)}default(_,$){return this.defaultValue=_,this.defaultValueDescription=$,this}argParser(_){return this.parseArg=_,this}choices(_){return this.argChoices=_.slice(),this.parseArg=($,g)=>{if(!this.argChoices.includes($))throw new Br(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,g);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Kr(_){let $=_.name()+(_.variadic===!0?"...":"");return _.required?"<"+$+">":"["+$+"]"}Vr.Argument=$8;Vr.humanReadableArgName=Kr});var p3=e6((br)=>{var{humanReadableArgName:Zr}=zN();class g8{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(_){this.helpWidth=this.helpWidth??_.helpWidth??80}visibleCommands(_){let $=_.commands.filter((U)=>!U._hidden),g=_._getHelpCommand();if(g&&!g._hidden)$.push(g);if(this.sortSubcommands)$.sort((U,D)=>{return U.name().localeCompare(D.name())});return $}compareOptions(_,$){let g=(U)=>{return U.short?U.short.replace(/^-/,""):U.long.replace(/^--/,"")};return g(_).localeCompare(g($))}visibleOptions(_){let $=_.options.filter((U)=>!U.hidden),g=_._getHelpOption();if(g&&!g.hidden){let U=g.short&&_._findOption(g.short),D=g.long&&_._findOption(g.long);if(!U&&!D)$.push(g);else if(g.long&&!D)$.push(_.createOption(g.long,g.description));else if(g.short&&!U)$.push(_.createOption(g.short,g.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(_){if(!this.showGlobalOptions)return[];let $=[];for(let g=_.parent;g;g=g.parent){let U=g.options.filter((D)=>!D.hidden);$.push(...U)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(_){if(_._argsDescription)_.registeredArguments.forEach(($)=>{$.description=$.description||_._argsDescription[$.name()]||""});if(_.registeredArguments.find(($)=>$.description))return _.registeredArguments;return[]}subcommandTerm(_){let $=_.registeredArguments.map((g)=>Zr(g)).join(" ");return _._name+(_._aliases[0]?"|"+_._aliases[0]:"")+(_.options.length?" [options]":"")+($?" "+$:"")}optionTerm(_){return _.flags}argumentTerm(_){return _.name()}longestSubcommandTermLength(_,$){return $.visibleCommands(_).reduce((g,U)=>{return Math.max(g,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(U))))},0)}longestOptionTermLength(_,$){return $.visibleOptions(_).reduce((g,U)=>{return Math.max(g,this.displayWidth($.styleOptionTerm($.optionTerm(U))))},0)}longestGlobalOptionTermLength(_,$){return $.visibleGlobalOptions(_).reduce((g,U)=>{return Math.max(g,this.displayWidth($.styleOptionTerm($.optionTerm(U))))},0)}longestArgumentTermLength(_,$){return $.visibleArguments(_).reduce((g,U)=>{return Math.max(g,this.displayWidth($.styleArgumentTerm($.argumentTerm(U))))},0)}commandUsage(_){let $=_._name;if(_._aliases[0])$=$+"|"+_._aliases[0];let g="";for(let U=_.parent;U;U=U.parent)g=U.name()+" "+g;return g+$+" "+_.usage()}commandDescription(_){return _.description()}subcommandDescription(_){return _.summary()||_.description()}optionDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((g)=>JSON.stringify(g)).join(", ")}`);if(_.defaultValue!==void 0){if(_.required||_.optional||_.isBoolean()&&typeof _.defaultValue==="boolean")$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`)}if(_.presetArg!==void 0&&_.optional)$.push(`preset: ${JSON.stringify(_.presetArg)}`);if(_.envVar!==void 0)$.push(`env: ${_.envVar}`);if($.length>0)return`${_.description} (${$.join(", ")})`;return _.description}argumentDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((g)=>JSON.stringify(g)).join(", ")}`);if(_.defaultValue!==void 0)$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`);if($.length>0){let g=`(${$.join(", ")})`;if(_.description)return`${_.description} ${g}`;return g}return _.description}formatHelp(_,$){let g=$.padWidth(_,$),U=$.helpWidth??80;function D(L,z){return $.formatItem(L,g,z,$)}let I=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(_))}`,""],j=$.commandDescription(_);if(j.length>0)I=I.concat([$.boxWrap($.styleCommandDescription(j),U),""]);let N=$.visibleArguments(_).map((L)=>{return D($.styleArgumentTerm($.argumentTerm(L)),$.styleArgumentDescription($.argumentDescription(L)))});if(N.length>0)I=I.concat([$.styleTitle("Arguments:"),...N,""]);let O=$.visibleOptions(_).map((L)=>{return D($.styleOptionTerm($.optionTerm(L)),$.styleOptionDescription($.optionDescription(L)))});if(O.length>0)I=I.concat([$.styleTitle("Options:"),...O,""]);if($.showGlobalOptions){let L=$.visibleGlobalOptions(_).map((z)=>{return D($.styleOptionTerm($.optionTerm(z)),$.styleOptionDescription($.optionDescription(z)))});if(L.length>0)I=I.concat([$.styleTitle("Global Options:"),...L,""])}let A=$.visibleCommands(_).map((L)=>{return D($.styleSubcommandTerm($.subcommandTerm(L)),$.styleSubcommandDescription($.subcommandDescription(L)))});if(A.length>0)I=I.concat([$.styleTitle("Commands:"),...A,""]);return I.join(` +`)}displayWidth(_){return D8(_).length}styleTitle(_){return _}styleUsage(_){return _.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($==="[command]")return this.styleSubcommandText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleCommandText($)}).join(" ")}styleCommandDescription(_){return this.styleDescriptionText(_)}styleOptionDescription(_){return this.styleDescriptionText(_)}styleSubcommandDescription(_){return this.styleDescriptionText(_)}styleArgumentDescription(_){return this.styleDescriptionText(_)}styleDescriptionText(_){return _}styleOptionTerm(_){return this.styleOptionText(_)}styleSubcommandTerm(_){return _.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleSubcommandText($)}).join(" ")}styleArgumentTerm(_){return this.styleArgumentText(_)}styleOptionText(_){return _}styleArgumentText(_){return _}styleSubcommandText(_){return _}styleCommandText(_){return _}padWidth(_,$){return Math.max($.longestOptionTermLength(_,$),$.longestGlobalOptionTermLength(_,$),$.longestSubcommandTermLength(_,$),$.longestArgumentTermLength(_,$))}preformatted(_){return/\n[^\S\r\n]/.test(_)}formatItem(_,$,g,U){let I=" ".repeat(2);if(!g)return I+_;let j=_.padEnd($+_.length-U.displayWidth(_)),N=2,A=(this.helpWidth??80)-$-N-2,L;if(A{let j=I.match(U);if(j===null){D.push("");return}let N=[j.shift()],O=this.displayWidth(N[0]);j.forEach((A)=>{let L=this.displayWidth(A);if(O+L<=$){N.push(A),O+=L;return}D.push(N.join(""));let z=A.trimStart();N=[z],O=this.displayWidth(z)}),D.push(N.join(""))}),D.join(` +`)}}function D8(_){let $=/\x1b\[\d*(;\d*)*m/g;return _.replace($,"")}br.Help=g8;br.stripColor=D8});var e3=e6((vr)=>{var{InvalidArgumentError:Cr}=qU();class I8{constructor(_,$){this.flags=_,this.description=$||"",this.required=_.includes("<"),this.optional=_.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(_),this.mandatory=!1;let g=rr(_);if(this.short=g.shortFlag,this.long=g.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(_,$){return this.defaultValue=_,this.defaultValueDescription=$,this}preset(_){return this.presetArg=_,this}conflicts(_){return this.conflictsWith=this.conflictsWith.concat(_),this}implies(_){let $=_;if(typeof _==="string")$={[_]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(_){return this.envVar=_,this}argParser(_){return this.parseArg=_,this}makeOptionMandatory(_=!0){return this.mandatory=!!_,this}hideHelp(_=!0){return this.hidden=!!_,this}_concatValue(_,$){if($===this.defaultValue||!Array.isArray($))return[_];return $.concat(_)}choices(_){return this.argChoices=_.slice(),this.parseArg=($,g)=>{if(!this.argChoices.includes($))throw new Cr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,g);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return U8(this.name().replace(/^no-/,""));return U8(this.name())}is(_){return this.short===_||this.long===_}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class j8{constructor(_){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,_.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,g)=>{if(this.positiveOptions.has(g))this.dualOptions.add(g)})}valueFromOption(_,$){let g=$.attributeName();if(!this.dualOptions.has(g))return!0;let U=this.negativeOptions.get(g).presetArg,D=U!==void 0?U:!1;return $.negate===(D===_)}}function U8(_){return _.split("-").reduce(($,g)=>{return $+g[0].toUpperCase()+g.slice(1)})}function rr(_){let $,g,U=/^-[^-]$/,D=/^--[^-]/,I=_.split(/[ |,]+/).concat("guard");if(U.test(I[0]))$=I.shift();if(D.test(I[0]))g=I.shift();if(!$&&U.test(I[0]))$=I.shift();if(!$&&D.test(I[0]))$=g,g=I.shift();if(I[0].startsWith("-")){let j=I[0],N=`option creation failed due to '${j}' in option flags '${_}'`;if(/^-[^-][^-]/.test(j))throw Error(`${N} - a short flag is a single dash and a single character - either use a single dash and a single character (for a short flag) - - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(U.test(G))throw Error(`${Y} -- too many short flags`);if(W.test(G))throw Error(`${Y} -- too many long flags`);throw Error(`${Y} -- unrecognised flag format`)}if(_===void 0&&J===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:_,longFlag:J}}sr.Option=vM;sr.DualOptions=yM});var hM=t0((Wp)=>{function _p($,_){if(Math.abs($.length-_.length)>3)return Math.max($.length,_.length);let J=[];for(let U=0;U<=$.length;U++)J[U]=[U];for(let U=0;U<=_.length;U++)J[0][U]=U;for(let U=1;U<=_.length;U++)for(let W=1;W<=$.length;W++){let X=1;if($[W-1]===_[U-1])X=0;else X=1;if(J[W][U]=Math.min(J[W-1][U]+1,J[W][U-1]+1,J[W-1][U-1]+X),W>1&&U>1&&$[W-1]===_[U-2]&&$[W-2]===_[U-1])J[W][U]=Math.min(J[W][U],J[W-2][U-2]+1)}return J[$.length][_.length]}function Jp($,_){if(!_||_.length===0)return"";_=Array.from(new Set(_));let J=$.startsWith("--");if(J)$=$.slice(2),_=_.map((G)=>G.slice(2));let U=[],W=3,X=0.4;if(_.forEach((G)=>{if(G.length<=1)return;let Y=_p($,G),Q=Math.max($.length,G.length);if((Q-Y)/Q>X){if(YG.localeCompare(Y)),J)U=U.map((G)=>`--${G}`);if(U.length>1)return` + - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(U.test(j))throw Error(`${N} +- too many short flags`);if(D.test(j))throw Error(`${N} +- too many long flags`);throw Error(`${N} +- unrecognised flag format`)}if($===void 0&&g===void 0)throw Error(`option creation failed due to no flags found in '${_}'.`);return{shortFlag:$,longFlag:g}}vr.Option=I8;vr.DualOptions=j8});var N8=e6((yr)=>{function ur(_,$){if(Math.abs(_.length-$.length)>3)return Math.max(_.length,$.length);let g=[];for(let U=0;U<=_.length;U++)g[U]=[U];for(let U=0;U<=$.length;U++)g[0][U]=U;for(let U=1;U<=$.length;U++)for(let D=1;D<=_.length;D++){let I=1;if(_[D-1]===$[U-1])I=0;else I=1;if(g[D][U]=Math.min(g[D-1][U]+1,g[D][U-1]+1,g[D-1][U-1]+I),D>1&&U>1&&_[D-1]===$[U-2]&&_[D-2]===$[U-1])g[D][U]=Math.min(g[D][U],g[D-2][U-2]+1)}return g[_.length][$.length]}function xr(_,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let g=_.startsWith("--");if(g)_=_.slice(2),$=$.map((j)=>j.slice(2));let U=[],D=3,I=0.4;if($.forEach((j)=>{if(j.length<=1)return;let N=ur(_,j),O=Math.max(_.length,j.length);if((O-N)/O>I){if(Nj.localeCompare(N)),g)U=U.map((j)=>`--${j}`);if(U.length>1)return` (Did you mean one of ${U.join(", ")}?)`;if(U.length===1)return` -(Did you mean ${U[0]}?)`;return""}Wp.suggestSimilar=Jp});var dM=t0((jp)=>{var Xp=i$("events").EventEmitter,OB=i$("child_process"),U0=i$("path"),YY=i$("fs"),n$=i$("process"),{Argument:Gp,humanReadableArgName:Yp}=GY(),{CommanderError:LB}=Y9(),{Help:Qp,stripColor:qp}=jB(),{Option:mM,DualOptions:zp}=DB(),{suggestSimilar:xM}=hM();class HB extends Xp{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(_)=>n$.stdout.write(_),writeErr:(_)=>n$.stderr.write(_),outputError:(_,J)=>J(_),getOutHelpWidth:()=>n$.stdout.isTTY?n$.stdout.columns:void 0,getErrHelpWidth:()=>n$.stderr.isTTY?n$.stderr.columns:void 0,getOutHasColors:()=>BB()??(n$.stdout.isTTY&&n$.stdout.hasColors?.()),getErrHasColors:()=>BB()??(n$.stderr.isTTY&&n$.stderr.hasColors?.()),stripColor:(_)=>qp(_)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let _=this;_;_=_.parent)$.push(_);return $}command($,_,J){let U=_,W=J;if(typeof U==="object"&&U!==null)W=U,U=null;W=W||{};let[,X,G]=$.match(/([^ ]+) *(.*)/),Y=this.createCommand(X);if(U)Y.description(U),Y._executableHandler=!0;if(W.isDefault)this._defaultCommandName=Y._name;if(Y._hidden=!!(W.noHelp||W.hidden),Y._executableFile=W.executableFile||null,G)Y.arguments(G);if(this._registerCommand(Y),Y.parent=this,Y.copyInheritedSettings(this),U)return this;return Y}createCommand($){return new HB($)}createHelp(){return Object.assign(new Qp,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,_){if(!$._name)throw Error(`Command passed to .addCommand() must have a name -- specify the name in Command constructor or using .name()`);if(_=_||{},_.isDefault)this._defaultCommandName=$._name;if(_.noHelp||_.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,_){return new Gp($,_)}argument($,_,J,U){let W=this.createArgument($,_);if(typeof J==="function")W.default(U).argParser(J);else W.default(J);return this.addArgument(W),this}arguments($){return $.trim().split(/ +/).forEach((_)=>{this.argument(_)}),this}addArgument($){let _=this.registeredArguments.slice(-1)[0];if(_&&_.variadic)throw Error(`only the last argument can be variadic '${_.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,_){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,J,U]=$.match(/([^ ]+) *(.*)/),W=_??"display help for command",X=this.createCommand(J);if(X.helpOption(!1),U)X.arguments(U);if(W)X.description(W);return this._addImplicitHelpCommand=!0,this._helpCommand=X,this}addHelpCommand($,_){if(typeof $!=="object")return this.helpCommand($,_),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,_){let J=["preSubcommand","preAction","postAction"];if(!J.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'. -Expecting one of '${J.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(_);else this._lifeCycleHooks[$]=[_];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(_)=>{if(_.code!=="commander.executeSubCommandAsync")throw _};return this}_exit($,_,J){if(this._exitCallback)this._exitCallback(new LB($,_,J));n$.exit($)}action($){let _=(J)=>{let U=this.registeredArguments.length,W=J.slice(0,U);if(this._storeOptionsAsProperties)W[U]=this;else W[U]=this.opts();return W.push(this),$.apply(this,W)};return this._actionHandler=_,this}createOption($,_){return new mM($,_)}_callParseArg($,_,J,U){try{return $.parseArg(_,J)}catch(W){if(W.code==="commander.invalidArgument"){let X=`${U} ${W.message}`;this.error(X,{exitCode:W.exitCode,code:W.code})}throw W}}_registerOption($){let _=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(_){let J=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${J}' -- already used by option '${_.flags}'`)}this.options.push($)}_registerCommand($){let _=(U)=>{return[U.name()].concat(U.aliases())},J=_($).find((U)=>this._findCommand(U));if(J){let U=_(this._findCommand(J)).join("|"),W=_($).join("|");throw Error(`cannot add command '${W}' as already have command '${U}'`)}this.commands.push($)}addOption($){this._registerOption($);let _=$.name(),J=$.attributeName();if($.negate){let W=$.long.replace(/^--no-/,"--");if(!this._findOption(W))this.setOptionValueWithSource(J,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(J,$.defaultValue,"default");let U=(W,X,G)=>{if(W==null&&$.presetArg!==void 0)W=$.presetArg;let Y=this.getOptionValue(J);if(W!==null&&$.parseArg)W=this._callParseArg($,W,Y,X);else if(W!==null&&$.variadic)W=$._concatValue(W,Y);if(W==null)if($.negate)W=!1;else if($.isBoolean()||$.optional)W=!0;else W="";this.setOptionValueWithSource(J,W,G)};if(this.on("option:"+_,(W)=>{let X=`error: option '${$.flags}' argument '${W}' is invalid.`;U(W,X,"cli")}),$.envVar)this.on("optionEnv:"+_,(W)=>{let X=`error: option '${$.flags}' value '${W}' from env '${$.envVar}' is invalid.`;U(W,X,"env")});return this}_optionEx($,_,J,U,W){if(typeof _==="object"&&_ instanceof mM)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let X=this.createOption(_,J);if(X.makeOptionMandatory(!!$.mandatory),typeof U==="function")X.default(W).argParser(U);else if(U instanceof RegExp){let G=U;U=(Y,Q)=>{let q=G.exec(Y);return q?q[0]:Q},X.default(W).argParser(U)}else X.default(U);return this.addOption(X)}option($,_,J,U){return this._optionEx({},$,_,J,U)}requiredOption($,_,J,U){return this._optionEx({mandatory:!0},$,_,J,U)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,_){return this.setOptionValueWithSource($,_,void 0)}setOptionValueWithSource($,_,J){if(this._storeOptionsAsProperties)this[$]=_;else this._optionValues[$]=_;return this._optionValueSources[$]=J,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let _;return this._getCommandAndAncestors().forEach((J)=>{if(J.getOptionValueSource($)!==void 0)_=J.getOptionValueSource($)}),_}_prepareUserArgs($,_){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(_=_||{},$===void 0&&_.from===void 0){if(n$.versions?.electron)_.from="electron";let U=n$.execArgv??[];if(U.includes("-e")||U.includes("--eval")||U.includes("-p")||U.includes("--print"))_.from="eval"}if($===void 0)$=n$.argv;this.rawArgs=$.slice();let J;switch(_.from){case void 0:case"node":this._scriptPath=$[1],J=$.slice(2);break;case"electron":if(n$.defaultApp)this._scriptPath=$[1],J=$.slice(2);else J=$.slice(1);break;case"user":J=$.slice(0);break;case"eval":J=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${_.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",J}parse($,_){this._prepareForParse();let J=this._prepareUserArgs($,_);return this._parseCommand([],J),this}async parseAsync($,_){this._prepareForParse();let J=this._prepareUserArgs($,_);return await this._parseCommand([],J),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true. -- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,_,J){if(YY.existsSync($))return;let U=_?`searched for local subcommand relative to directory '${_}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",W=`'${$}' does not exist - - if '${J}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead +(Did you mean ${U[0]}?)`;return""}yr.suggestSimilar=xr});var L8=e6((tr)=>{var cr=O_("events").EventEmitter,a3=O_("child_process"),S6=O_("path"),SN=O_("fs"),E_=O_("process"),{Argument:nr,humanReadableArgName:dr}=zN(),{CommanderError:s3}=qU(),{Help:mr,stripColor:ir}=p3(),{Option:E8,DualOptions:lr}=e3(),{suggestSimilar:O8}=N8();class $z extends cr{constructor(_){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=_||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:($)=>E_.stdout.write($),writeErr:($)=>E_.stderr.write($),outputError:($,g)=>g($),getOutHelpWidth:()=>E_.stdout.isTTY?E_.stdout.columns:void 0,getErrHelpWidth:()=>E_.stderr.isTTY?E_.stderr.columns:void 0,getOutHasColors:()=>_z()??(E_.stdout.isTTY&&E_.stdout.hasColors?.()),getErrHasColors:()=>_z()??(E_.stderr.isTTY&&E_.stderr.hasColors?.()),stripColor:($)=>ir($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(_){return this._outputConfiguration=_._outputConfiguration,this._helpOption=_._helpOption,this._helpCommand=_._helpCommand,this._helpConfiguration=_._helpConfiguration,this._exitCallback=_._exitCallback,this._storeOptionsAsProperties=_._storeOptionsAsProperties,this._combineFlagAndOptionalValue=_._combineFlagAndOptionalValue,this._allowExcessArguments=_._allowExcessArguments,this._enablePositionalOptions=_._enablePositionalOptions,this._showHelpAfterError=_._showHelpAfterError,this._showSuggestionAfterError=_._showSuggestionAfterError,this}_getCommandAndAncestors(){let _=[];for(let $=this;$;$=$.parent)_.push($);return _}command(_,$,g){let U=$,D=g;if(typeof U==="object"&&U!==null)D=U,U=null;D=D||{};let[,I,j]=_.match(/([^ ]+) *(.*)/),N=this.createCommand(I);if(U)N.description(U),N._executableHandler=!0;if(D.isDefault)this._defaultCommandName=N._name;if(N._hidden=!!(D.noHelp||D.hidden),N._executableFile=D.executableFile||null,j)N.arguments(j);if(this._registerCommand(N),N.parent=this,N.copyInheritedSettings(this),U)return this;return N}createCommand(_){return new $z(_)}createHelp(){return Object.assign(new mr,this.configureHelp())}configureHelp(_){if(_===void 0)return this._helpConfiguration;return this._helpConfiguration=_,this}configureOutput(_){if(_===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,_),this}showHelpAfterError(_=!0){if(typeof _!=="string")_=!!_;return this._showHelpAfterError=_,this}showSuggestionAfterError(_=!0){return this._showSuggestionAfterError=!!_,this}addCommand(_,$){if(!_._name)throw Error(`Command passed to .addCommand() must have a name +- specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=_._name;if($.noHelp||$.hidden)_._hidden=!0;return this._registerCommand(_),_.parent=this,_._checkForBrokenPassThrough(),this}createArgument(_,$){return new nr(_,$)}argument(_,$,g,U){let D=this.createArgument(_,$);if(typeof g==="function")D.default(U).argParser(g);else D.default(g);return this.addArgument(D),this}arguments(_){return _.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(_){let $=this.registeredArguments.slice(-1)[0];if($&&$.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(_.required&&_.defaultValue!==void 0&&_.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${_.name()}'`);return this.registeredArguments.push(_),this}helpCommand(_,$){if(typeof _==="boolean")return this._addImplicitHelpCommand=_,this;_=_??"help [command]";let[,g,U]=_.match(/([^ ]+) *(.*)/),D=$??"display help for command",I=this.createCommand(g);if(I.helpOption(!1),U)I.arguments(U);if(D)I.description(D);return this._addImplicitHelpCommand=!0,this._helpCommand=I,this}addHelpCommand(_,$){if(typeof _!=="object")return this.helpCommand(_,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=_,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(_,$){let g=["preSubcommand","preAction","postAction"];if(!g.includes(_))throw Error(`Unexpected value for event passed to hook : '${_}'. +Expecting one of '${g.join("', '")}'`);if(this._lifeCycleHooks[_])this._lifeCycleHooks[_].push($);else this._lifeCycleHooks[_]=[$];return this}exitOverride(_){if(_)this._exitCallback=_;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(_,$,g){if(this._exitCallback)this._exitCallback(new s3(_,$,g));E_.exit(_)}action(_){let $=(g)=>{let U=this.registeredArguments.length,D=g.slice(0,U);if(this._storeOptionsAsProperties)D[U]=this;else D[U]=this.opts();return D.push(this),_.apply(this,D)};return this._actionHandler=$,this}createOption(_,$){return new E8(_,$)}_callParseArg(_,$,g,U){try{return _.parseArg($,g)}catch(D){if(D.code==="commander.invalidArgument"){let I=`${U} ${D.message}`;this.error(I,{exitCode:D.exitCode,code:D.code})}throw D}}_registerOption(_){let $=_.short&&this._findOption(_.short)||_.long&&this._findOption(_.long);if($){let g=_.long&&this._findOption(_.long)?_.long:_.short;throw Error(`Cannot add option '${_.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${g}' +- already used by option '${$.flags}'`)}this.options.push(_)}_registerCommand(_){let $=(U)=>{return[U.name()].concat(U.aliases())},g=$(_).find((U)=>this._findCommand(U));if(g){let U=$(this._findCommand(g)).join("|"),D=$(_).join("|");throw Error(`cannot add command '${D}' as already have command '${U}'`)}this.commands.push(_)}addOption(_){this._registerOption(_);let $=_.name(),g=_.attributeName();if(_.negate){let D=_.long.replace(/^--no-/,"--");if(!this._findOption(D))this.setOptionValueWithSource(g,_.defaultValue===void 0?!0:_.defaultValue,"default")}else if(_.defaultValue!==void 0)this.setOptionValueWithSource(g,_.defaultValue,"default");let U=(D,I,j)=>{if(D==null&&_.presetArg!==void 0)D=_.presetArg;let N=this.getOptionValue(g);if(D!==null&&_.parseArg)D=this._callParseArg(_,D,N,I);else if(D!==null&&_.variadic)D=_._concatValue(D,N);if(D==null)if(_.negate)D=!1;else if(_.isBoolean()||_.optional)D=!0;else D="";this.setOptionValueWithSource(g,D,j)};if(this.on("option:"+$,(D)=>{let I=`error: option '${_.flags}' argument '${D}' is invalid.`;U(D,I,"cli")}),_.envVar)this.on("optionEnv:"+$,(D)=>{let I=`error: option '${_.flags}' value '${D}' from env '${_.envVar}' is invalid.`;U(D,I,"env")});return this}_optionEx(_,$,g,U,D){if(typeof $==="object"&&$ instanceof E8)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let I=this.createOption($,g);if(I.makeOptionMandatory(!!_.mandatory),typeof U==="function")I.default(D).argParser(U);else if(U instanceof RegExp){let j=U;U=(N,O)=>{let A=j.exec(N);return A?A[0]:O},I.default(D).argParser(U)}else I.default(U);return this.addOption(I)}option(_,$,g,U){return this._optionEx({},_,$,g,U)}requiredOption(_,$,g,U){return this._optionEx({mandatory:!0},_,$,g,U)}combineFlagAndOptionalValue(_=!0){return this._combineFlagAndOptionalValue=!!_,this}allowUnknownOption(_=!0){return this._allowUnknownOption=!!_,this}allowExcessArguments(_=!0){return this._allowExcessArguments=!!_,this}enablePositionalOptions(_=!0){return this._enablePositionalOptions=!!_,this}passThroughOptions(_=!0){return this._passThroughOptions=!!_,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(_=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!_,this}getOptionValue(_){if(this._storeOptionsAsProperties)return this[_];return this._optionValues[_]}setOptionValue(_,$){return this.setOptionValueWithSource(_,$,void 0)}setOptionValueWithSource(_,$,g){if(this._storeOptionsAsProperties)this[_]=$;else this._optionValues[_]=$;return this._optionValueSources[_]=g,this}getOptionValueSource(_){return this._optionValueSources[_]}getOptionValueSourceWithGlobals(_){let $;return this._getCommandAndAncestors().forEach((g)=>{if(g.getOptionValueSource(_)!==void 0)$=g.getOptionValueSource(_)}),$}_prepareUserArgs(_,$){if(_!==void 0&&!Array.isArray(_))throw Error("first parameter to parse must be array or undefined");if($=$||{},_===void 0&&$.from===void 0){if(E_.versions?.electron)$.from="electron";let U=E_.execArgv??[];if(U.includes("-e")||U.includes("--eval")||U.includes("-p")||U.includes("--print"))$.from="eval"}if(_===void 0)_=E_.argv;this.rawArgs=_.slice();let g;switch($.from){case void 0:case"node":this._scriptPath=_[1],g=_.slice(2);break;case"electron":if(E_.defaultApp)this._scriptPath=_[1],g=_.slice(2);else g=_.slice(1);break;case"user":g=_.slice(0);break;case"eval":g=_.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",g}parse(_,$){this._prepareForParse();let g=this._prepareUserArgs(_,$);return this._parseCommand([],g),this}async parseAsync(_,$){this._prepareForParse();let g=this._prepareUserArgs(_,$);return await this._parseCommand([],g),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true. +- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(_,$,g){if(SN.existsSync(_))return;let U=$?`searched for local subcommand relative to directory '${$}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",D=`'${_}' does not exist + - if '${g}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - - ${U}`;throw Error(W)}_executeSubCommand($,_){_=_.slice();let J=!1,U=[".js",".ts",".tsx",".mjs",".cjs"];function W(q,L){let N=U0.resolve(q,L);if(YY.existsSync(N))return N;if(U.includes(U0.extname(L)))return;let R=U.find((B)=>YY.existsSync(`${N}${B}`));if(R)return`${N}${R}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=$._executableFile||`${this._name}-${$._name}`,G=this._executableDir||"";if(this._scriptPath){let q;try{q=YY.realpathSync(this._scriptPath)}catch{q=this._scriptPath}G=U0.resolve(U0.dirname(q),G)}if(G){let q=W(G,X);if(!q&&!$._executableFile&&this._scriptPath){let L=U0.basename(this._scriptPath,U0.extname(this._scriptPath));if(L!==this._name)q=W(G,`${L}-${$._name}`)}X=q||X}J=U.includes(U0.extname(X));let Y;if(n$.platform!=="win32")if(J)_.unshift(X),_=uM(n$.execArgv).concat(_),Y=OB.spawn(n$.argv[0],_,{stdio:"inherit"});else Y=OB.spawn(X,_,{stdio:"inherit"});else this._checkForMissingExecutable(X,G,$._name),_.unshift(X),_=uM(n$.execArgv).concat(_),Y=OB.spawn(n$.execPath,_,{stdio:"inherit"});if(!Y.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((L)=>{n$.on(L,()=>{if(Y.killed===!1&&Y.exitCode===null)Y.kill(L)})});let Q=this._exitCallback;Y.on("close",(q)=>{if(q=q??1,!Q)n$.exit(q);else Q(new LB(q,"commander.executeSubCommandAsync","(close)"))}),Y.on("error",(q)=>{if(q.code==="ENOENT")this._checkForMissingExecutable(X,G,$._name);else if(q.code==="EACCES")throw Error(`'${X}' not executable`);if(!Q)n$.exit(1);else{let L=new LB(1,"commander.executeSubCommandAsync","(error)");L.nestedError=q,Q(L)}}),this.runningCommand=Y}_dispatchSubcommand($,_,J){let U=this._findCommand($);if(!U)this.help({error:!0});U._prepareForParse();let W;return W=this._chainOrCallSubCommandHook(W,U,"preSubcommand"),W=this._chainOrCall(W,()=>{if(U._executableHandler)this._executeSubCommand(U,_.concat(J));else return U._parseCommand(_,J)}),W}_dispatchHelpCommand($){if(!$)this.help();let _=this._findCommand($);if(_&&!_._executableHandler)_.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,_)=>{if($.required&&this.args[_]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(J,U,W)=>{let X=U;if(U!==null&&J.parseArg){let G=`error: command-argument value '${U}' is invalid for argument '${J.name()}'.`;X=this._callParseArg(J,U,W,G)}return X};this._checkNumberOfArguments();let _=[];this.registeredArguments.forEach((J,U)=>{let W=J.defaultValue;if(J.variadic){if(U{return $(J,G,X)},J.defaultValue)}else if(W===void 0)W=[]}else if(U_());return _()}_chainOrCallHooks($,_){let J=$,U=[];if(this._getCommandAndAncestors().reverse().filter((W)=>W._lifeCycleHooks[_]!==void 0).forEach((W)=>{W._lifeCycleHooks[_].forEach((X)=>{U.push({hookedCommand:W,callback:X})})}),_==="postAction")U.reverse();return U.forEach((W)=>{J=this._chainOrCall(J,()=>{return W.callback(W.hookedCommand,this)})}),J}_chainOrCallSubCommandHook($,_,J){let U=$;if(this._lifeCycleHooks[J]!==void 0)this._lifeCycleHooks[J].forEach((W)=>{U=this._chainOrCall(U,()=>{return W(this,_)})});return U}_parseCommand($,_){let J=this.parseOptions(_);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(J.operands),_=J.unknown,this.args=$.concat(_),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),_);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(_),this._dispatchSubcommand(this._defaultCommandName,$,_);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(J.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let U=()=>{if(J.unknown.length>0)this.unknownOption(J.unknown[0])},W=`command:${this.name()}`;if(this._actionHandler){U(),this._processArguments();let X;if(X=this._chainOrCallHooks(X,"preAction"),X=this._chainOrCall(X,()=>this._actionHandler(this.processedArgs)),this.parent)X=this._chainOrCall(X,()=>{this.parent.emit(W,$,_)});return X=this._chainOrCallHooks(X,"postAction"),X}if(this.parent&&this.parent.listenerCount(W))U(),this._processArguments(),this.parent.emit(W,$,_);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,_);if(this.listenerCount("command:*"))this.emit("command:*",$,_);else if(this.commands.length)this.unknownCommand();else U(),this._processArguments()}else if(this.commands.length)U(),this.help({error:!0});else U(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((_)=>_._name===$||_._aliases.includes($))}_findOption($){return this.options.find((_)=>_.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((_)=>{if(_.mandatory&&$.getOptionValue(_.attributeName())===void 0)$.missingMandatoryOptionValue(_)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((J)=>{let U=J.attributeName();if(this.getOptionValue(U)===void 0)return!1;return this.getOptionValueSource(U)!=="default"});$.filter((J)=>J.conflictsWith.length>0).forEach((J)=>{let U=$.find((W)=>J.conflictsWith.includes(W.attributeName()));if(U)this._conflictingOption(J,U)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let _=[],J=[],U=_,W=$.slice();function X(Y){return Y.length>1&&Y[0]==="-"}let G=null;while(W.length){let Y=W.shift();if(Y==="--"){if(U===J)U.push(Y);U.push(...W);break}if(G&&!X(Y)){this.emit(`option:${G.name()}`,Y);continue}if(G=null,X(Y)){let Q=this._findOption(Y);if(Q){if(Q.required){let q=W.shift();if(q===void 0)this.optionMissingArgument(Q);this.emit(`option:${Q.name()}`,q)}else if(Q.optional){let q=null;if(W.length>0&&!X(W[0]))q=W.shift();this.emit(`option:${Q.name()}`,q)}else this.emit(`option:${Q.name()}`);G=Q.variadic?Q:null;continue}}if(Y.length>2&&Y[0]==="-"&&Y[1]!=="-"){let Q=this._findOption(`-${Y[1]}`);if(Q){if(Q.required||Q.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${Q.name()}`,Y.slice(2));else this.emit(`option:${Q.name()}`),W.unshift(`-${Y.slice(2)}`);continue}}if(/^--[^=]+=/.test(Y)){let Q=Y.indexOf("="),q=this._findOption(Y.slice(0,Q));if(q&&(q.required||q.optional)){this.emit(`option:${q.name()}`,Y.slice(Q+1));continue}}if(X(Y))U=J;if((this._enablePositionalOptions||this._passThroughOptions)&&_.length===0&&J.length===0){if(this._findCommand(Y)){if(_.push(Y),W.length>0)J.push(...W);break}else if(this._getHelpCommand()&&Y===this._getHelpCommand().name()){if(_.push(Y),W.length>0)_.push(...W);break}else if(this._defaultCommandName){if(J.push(Y),W.length>0)J.push(...W);break}}if(this._passThroughOptions){if(U.push(Y),W.length>0)U.push(...W);break}U.push(Y)}return{operands:_,unknown:J}}opts(){if(this._storeOptionsAsProperties){let $={},_=this.options.length;for(let J=0;J<_;J++){let U=this.options[J].attributeName();$[U]=U===this._versionOptionName?this._version:this[U]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,_)=>Object.assign($,_.opts()),{})}error($,_){if(this._outputConfiguration.outputError(`${$} + - ${U}`;throw Error(D)}_executeSubCommand(_,$){$=$.slice();let g=!1,U=[".js",".ts",".tsx",".mjs",".cjs"];function D(A,L){let z=S6.resolve(A,L);if(SN.existsSync(z))return z;if(U.includes(S6.extname(L)))return;let W=U.find((J)=>SN.existsSync(`${z}${J}`));if(W)return`${z}${W}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let I=_._executableFile||`${this._name}-${_._name}`,j=this._executableDir||"";if(this._scriptPath){let A;try{A=SN.realpathSync(this._scriptPath)}catch{A=this._scriptPath}j=S6.resolve(S6.dirname(A),j)}if(j){let A=D(j,I);if(!A&&!_._executableFile&&this._scriptPath){let L=S6.basename(this._scriptPath,S6.extname(this._scriptPath));if(L!==this._name)A=D(j,`${L}-${_._name}`)}I=A||I}g=U.includes(S6.extname(I));let N;if(E_.platform!=="win32")if(g)$.unshift(I),$=A8(E_.execArgv).concat($),N=a3.spawn(E_.argv[0],$,{stdio:"inherit"});else N=a3.spawn(I,$,{stdio:"inherit"});else this._checkForMissingExecutable(I,j,_._name),$.unshift(I),$=A8(E_.execArgv).concat($),N=a3.spawn(E_.execPath,$,{stdio:"inherit"});if(!N.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((L)=>{E_.on(L,()=>{if(N.killed===!1&&N.exitCode===null)N.kill(L)})});let O=this._exitCallback;N.on("close",(A)=>{if(A=A??1,!O)E_.exit(A);else O(new s3(A,"commander.executeSubCommandAsync","(close)"))}),N.on("error",(A)=>{if(A.code==="ENOENT")this._checkForMissingExecutable(I,j,_._name);else if(A.code==="EACCES")throw Error(`'${I}' not executable`);if(!O)E_.exit(1);else{let L=new s3(1,"commander.executeSubCommandAsync","(error)");L.nestedError=A,O(L)}}),this.runningCommand=N}_dispatchSubcommand(_,$,g){let U=this._findCommand(_);if(!U)this.help({error:!0});U._prepareForParse();let D;return D=this._chainOrCallSubCommandHook(D,U,"preSubcommand"),D=this._chainOrCall(D,()=>{if(U._executableHandler)this._executeSubCommand(U,$.concat(g));else return U._parseCommand($,g)}),D}_dispatchHelpCommand(_){if(!_)this.help();let $=this._findCommand(_);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(_,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((_,$)=>{if(_.required&&this.args[$]==null)this.missingArgument(_.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let _=(g,U,D)=>{let I=U;if(U!==null&&g.parseArg){let j=`error: command-argument value '${U}' is invalid for argument '${g.name()}'.`;I=this._callParseArg(g,U,D,j)}return I};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((g,U)=>{let D=g.defaultValue;if(g.variadic){if(U{return _(g,j,I)},g.defaultValue)}else if(D===void 0)D=[]}else if(U$());return $()}_chainOrCallHooks(_,$){let g=_,U=[];if(this._getCommandAndAncestors().reverse().filter((D)=>D._lifeCycleHooks[$]!==void 0).forEach((D)=>{D._lifeCycleHooks[$].forEach((I)=>{U.push({hookedCommand:D,callback:I})})}),$==="postAction")U.reverse();return U.forEach((D)=>{g=this._chainOrCall(g,()=>{return D.callback(D.hookedCommand,this)})}),g}_chainOrCallSubCommandHook(_,$,g){let U=_;if(this._lifeCycleHooks[g]!==void 0)this._lifeCycleHooks[g].forEach((D)=>{U=this._chainOrCall(U,()=>{return D(this,$)})});return U}_parseCommand(_,$){let g=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),_=_.concat(g.operands),$=g.unknown,this.args=_.concat($),_&&this._findCommand(_[0]))return this._dispatchSubcommand(_[0],_.slice(1),$);if(this._getHelpCommand()&&_[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(_[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,_,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(g.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let U=()=>{if(g.unknown.length>0)this.unknownOption(g.unknown[0])},D=`command:${this.name()}`;if(this._actionHandler){U(),this._processArguments();let I;if(I=this._chainOrCallHooks(I,"preAction"),I=this._chainOrCall(I,()=>this._actionHandler(this.processedArgs)),this.parent)I=this._chainOrCall(I,()=>{this.parent.emit(D,_,$)});return I=this._chainOrCallHooks(I,"postAction"),I}if(this.parent&&this.parent.listenerCount(D))U(),this._processArguments(),this.parent.emit(D,_,$);else if(_.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",_,$);if(this.listenerCount("command:*"))this.emit("command:*",_,$);else if(this.commands.length)this.unknownCommand();else U(),this._processArguments()}else if(this.commands.length)U(),this.help({error:!0});else U(),this._processArguments()}_findCommand(_){if(!_)return;return this.commands.find(($)=>$._name===_||$._aliases.includes(_))}_findOption(_){return this.options.find(($)=>$.is(_))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((_)=>{_.options.forEach(($)=>{if($.mandatory&&_.getOptionValue($.attributeName())===void 0)_.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let _=this.options.filter((g)=>{let U=g.attributeName();if(this.getOptionValue(U)===void 0)return!1;return this.getOptionValueSource(U)!=="default"});_.filter((g)=>g.conflictsWith.length>0).forEach((g)=>{let U=_.find((D)=>g.conflictsWith.includes(D.attributeName()));if(U)this._conflictingOption(g,U)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((_)=>{_._checkForConflictingLocalOptions()})}parseOptions(_){let $=[],g=[],U=$,D=_.slice();function I(N){return N.length>1&&N[0]==="-"}let j=null;while(D.length){let N=D.shift();if(N==="--"){if(U===g)U.push(N);U.push(...D);break}if(j&&!I(N)){this.emit(`option:${j.name()}`,N);continue}if(j=null,I(N)){let O=this._findOption(N);if(O){if(O.required){let A=D.shift();if(A===void 0)this.optionMissingArgument(O);this.emit(`option:${O.name()}`,A)}else if(O.optional){let A=null;if(D.length>0&&!I(D[0]))A=D.shift();this.emit(`option:${O.name()}`,A)}else this.emit(`option:${O.name()}`);j=O.variadic?O:null;continue}}if(N.length>2&&N[0]==="-"&&N[1]!=="-"){let O=this._findOption(`-${N[1]}`);if(O){if(O.required||O.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${O.name()}`,N.slice(2));else this.emit(`option:${O.name()}`),D.unshift(`-${N.slice(2)}`);continue}}if(/^--[^=]+=/.test(N)){let O=N.indexOf("="),A=this._findOption(N.slice(0,O));if(A&&(A.required||A.optional)){this.emit(`option:${A.name()}`,N.slice(O+1));continue}}if(I(N))U=g;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&g.length===0){if(this._findCommand(N)){if($.push(N),D.length>0)g.push(...D);break}else if(this._getHelpCommand()&&N===this._getHelpCommand().name()){if($.push(N),D.length>0)$.push(...D);break}else if(this._defaultCommandName){if(g.push(N),D.length>0)g.push(...D);break}}if(this._passThroughOptions){if(U.push(N),D.length>0)U.push(...D);break}U.push(N)}return{operands:$,unknown:g}}opts(){if(this._storeOptionsAsProperties){let _={},$=this.options.length;for(let g=0;g<$;g++){let U=this.options[g].attributeName();_[U]=U===this._versionOptionName?this._version:this[U]}return _}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((_,$)=>Object.assign(_,$.opts()),{})}error(_,$){if(this._outputConfiguration.outputError(`${_} `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError} `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(` -`),this.outputHelp({error:!0});let J=_||{},U=J.exitCode||1,W=J.code||"commander.error";this._exit(U,W,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in n$.env){let _=$.attributeName();if(this.getOptionValue(_)===void 0||["default","config","env"].includes(this.getOptionValueSource(_)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,n$.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new zp(this.options),_=(J)=>{return this.getOptionValue(J)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(J))};this.options.filter((J)=>J.implied!==void 0&&_(J.attributeName())&&$.valueFromOption(this.getOptionValue(J.attributeName()),J)).forEach((J)=>{Object.keys(J.implied).filter((U)=>!_(U)).forEach((U)=>{this.setOptionValueWithSource(U,J.implied[U],"implied")})})}missingArgument($){let _=`error: missing required argument '${$}'`;this.error(_,{code:"commander.missingArgument"})}optionMissingArgument($){let _=`error: option '${$.flags}' argument missing`;this.error(_,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let _=`error: required option '${$.flags}' not specified`;this.error(_,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,_){let J=(X)=>{let G=X.attributeName(),Y=this.getOptionValue(G),Q=this.options.find((L)=>L.negate&&G===L.attributeName()),q=this.options.find((L)=>!L.negate&&G===L.attributeName());if(Q&&(Q.presetArg===void 0&&Y===!1||Q.presetArg!==void 0&&Y===Q.presetArg))return Q;return q||X},U=(X)=>{let G=J(X),Y=G.attributeName();if(this.getOptionValueSource(Y)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},W=`error: ${U($)} cannot be used with ${U(_)}`;this.error(W,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let _="";if($.startsWith("--")&&this._showSuggestionAfterError){let U=[],W=this;do{let X=W.createHelp().visibleOptions(W).filter((G)=>G.long).map((G)=>G.long);U=U.concat(X),W=W.parent}while(W&&!W._enablePositionalOptions);_=xM($,U)}let J=`error: unknown option '${$}'${_}`;this.error(J,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let _=this.registeredArguments.length,J=_===1?"":"s",W=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${_} argument${J} but got ${$.length}.`;this.error(W,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],_="";if(this._showSuggestionAfterError){let U=[];this.createHelp().visibleCommands(this).forEach((W)=>{if(U.push(W.name()),W.alias())U.push(W.alias())}),_=xM($,U)}let J=`error: unknown command '${$}'${_}`;this.error(J,{code:"commander.unknownCommand"})}version($,_,J){if($===void 0)return this._version;this._version=$,_=_||"-V, --version",J=J||"output the version number";let U=this.createOption(_,J);return this._versionOptionName=U.attributeName(),this._registerOption(U),this.on("option:"+U.name(),()=>{this._outputConfiguration.writeOut(`${$} -`),this._exit(0,"commander.version",$)}),this}description($,_){if($===void 0&&_===void 0)return this._description;if(this._description=$,_)this._argsDescription=_;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let _=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)_=this.commands[this.commands.length-1];if($===_._name)throw Error("Command alias can't be the same as its name");let J=this.parent?._findCommand($);if(J){let U=[J.name()].concat(J.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${U}'`)}return _._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((_)=>this.alias(_)),this}usage($){if($===void 0){if(this._usage)return this._usage;let _=this.registeredArguments.map((J)=>{return Yp(J)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?_:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=U0.basename($,U0.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let _=this.createHelp(),J=this._getOutputContext($);_.prepareContext({error:J.error,helpWidth:J.helpWidth,outputHasColors:J.hasColors});let U=_.formatHelp(this,_);if(J.hasColors)return U;return this._outputConfiguration.stripColor(U)}_getOutputContext($){$=$||{};let _=!!$.error,J,U,W;if(_)J=(G)=>this._outputConfiguration.writeErr(G),U=this._outputConfiguration.getErrHasColors(),W=this._outputConfiguration.getErrHelpWidth();else J=(G)=>this._outputConfiguration.writeOut(G),U=this._outputConfiguration.getOutHasColors(),W=this._outputConfiguration.getOutHelpWidth();return{error:_,write:(G)=>{if(!U)G=this._outputConfiguration.stripColor(G);return J(G)},hasColors:U,helpWidth:W}}outputHelp($){let _;if(typeof $==="function")_=$,$=void 0;let J=this._getOutputContext($),U={error:J.error,write:J.write,command:this};this._getCommandAndAncestors().reverse().forEach((X)=>X.emit("beforeAllHelp",U)),this.emit("beforeHelp",U);let W=this.helpInformation({error:J.error});if(_){if(W=_(W),typeof W!=="string"&&!Buffer.isBuffer(W))throw Error("outputHelp callback must return a string or a Buffer")}if(J.write(W),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",U),this._getCommandAndAncestors().forEach((X)=>X.emit("afterAllHelp",U))}helpOption($,_){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",_=_??"display help for command",this._helpOption=this.createOption($,_),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let _=Number(n$.exitCode??0);if(_===0&&$&&typeof $!=="function"&&$.error)_=1;this._exit(_,"commander.help","(outputHelp)")}addHelpText($,_){let J=["beforeAll","before","after","afterAll"];if(!J.includes($))throw Error(`Unexpected value for position to addHelpText. -Expecting one of '${J.join("', '")}'`);let U=`${$}Help`;return this.on(U,(W)=>{let X;if(typeof _==="function")X=_({error:W.error,command:W.command});else X=_;if(X)W.write(`${X} -`)}),this}_outputHelpIfRequested($){let _=this._getHelpOption();if(_&&$.find((U)=>_.is(U)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function uM($){return $.map((_)=>{if(!_.startsWith("--inspect"))return _;let J,U="127.0.0.1",W="9229",X;if((X=_.match(/^(--inspect(-brk)?)$/))!==null)J=X[1];else if((X=_.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(J=X[1],/^\d+$/.test(X[3]))W=X[3];else U=X[3];else if((X=_.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)J=X[1],U=X[3],W=X[4];if(J&&W!=="0")return`${J}=${U}:${parseInt(W)+1}`;return _})}function BB(){if(n$.env.NO_COLOR||n$.env.FORCE_COLOR==="0"||n$.env.FORCE_COLOR==="false")return!1;if(n$.env.FORCE_COLOR||n$.env.CLICOLOR_FORCE!==void 0)return!0;return}jp.Command=HB;jp.useColor=BB});var lM=t0((Hp)=>{var{Argument:nM}=GY(),{Command:NB}=dM(),{CommanderError:Lp,InvalidArgumentError:cM}=Y9(),{Help:Bp}=jB(),{Option:iM}=DB();Hp.program=new NB;Hp.createCommand=($)=>new NB($);Hp.createOption=($,_)=>new iM($,_);Hp.createArgument=($,_)=>new nM($,_);Hp.Command=NB;Hp.Option=iM;Hp.Argument=nM;Hp.Help=Bp;Hp.CommanderError=Lp;Hp.InvalidArgumentError=cM;Hp.InvalidOptionArgumentError=cM});import{chmodSync as vB,closeSync as nW,existsSync as w2,fsyncSync as AY,lstatSync as mA,openSync as bY,readFileSync as cW,renameSync as yB,unlinkSync as wY,writeFileSync as gY}from"fs";import{randomUUID as iW}from"crypto";import{basename as xA,dirname as hB,join as MY}from"path";import{chmodSync as gB,existsSync as SA,mkdirSync as HY,readFileSync as ZA,writeFileSync as kB}from"fs";import{homedir as NY}from"os";import{dirname as vA,join as I_,resolve as IB}from"path";var K4=I_(".hasna","knowledge"),fB=I_(".hasna","apps","knowledge"),r$={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:K4,s3:{bucket:"example-knowledge-prod",region:"us-east-1",profile:"example-infra",prefix:".hasna/knowledge",server_side_encryption:"AES256"},secrets:{env:"example/knowledge/prod/env",aws:"example/knowledge/prod/aws",s3:"example/knowledge/prod/s3",rds:null,future_rds:"example/knowledge/prod/rds"},source_owner:"open-files",evidence_doc:"docs/canonical-secrets-bootstrap-2026-06-08.md"};function CB(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:r$.s3.bucket,prefix:r$.s3.prefix,region:r$.s3.region,profile:r$.s3.profile,server_side_encryption:r$.s3.server_side_encryption}}}function uW(){return I_(NY(),".open-knowledge","db.json")}function D9(){return I_(NY(),".hasna","knowledge")}function VY($=process.cwd()){return IB($,K4)}function yA(){return I_(NY(),fB)}function hA($=process.cwd()){return IB($,fB)}function RY($,_=process.cwd()){if($==="project"||$==="local")return s_(hA(_));return s_(yA())}function s_($){return{home:$,configPath:I_($,"config.json"),jsonStorePath:I_($,"db.json"),knowledgeDbPath:I_($,"knowledge.db"),artifactsDir:I_($,"artifacts"),cacheDir:I_($,"cache"),exportsDir:I_($,"exports"),indexesDir:I_($,"indexes"),logsDir:I_($,"logs"),runsDir:I_($,"runs"),schemasDir:I_($,"schemas"),wikiDir:I_($,"wiki")}}function dW(){return{version:1,mode:"local",hosted:{api_url:"https://knowledge.md"},storage:{type:"local",artifacts_root:"artifacts"},sources:{preferred_ref:"open-files",allowed_schemes:["open-files","s3","file","https","http"]},providers:{default_model:"openai:gpt-5.2",aliases:{fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"},openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},embeddings:{default_model:"openai:text-embedding-3-small",dimensions:1536,batch_size:64,max_parallel_calls:4},safety:{network:{web_search_enabled:!1,s3_reads_enabled:!1,allowed_s3_buckets:[]},redaction:{enabled:!0},approvals:{generated_writes_require_approval:!0}}}}function b2($){let _=s_($);HY(_.home,{recursive:!0,mode:448});for(let J of[_.artifactsDir,_.cacheDir,_.exportsDir,_.indexesDir,_.logsDir,_.runsDir,_.schemasDir,_.wikiDir])HY(J,{recursive:!0,mode:448});if(!SA(_.configPath))kB(_.configPath,`${JSON.stringify(dW(),null,2)} -`,{mode:384}),gB(_.configPath,384);return _}function O9($,_=process.cwd()){if($==="project"||$==="local")return s_(VY(_));return s_(D9())}function G0($){HY(vA($),{recursive:!0})}function KY($){let _=ZA($,"utf8");return JSON.parse(_)}function PB($,_){G0($),kB($,`${JSON.stringify(_,null,2)} -`,{mode:384}),gB($,384)}function B9(){return s_(D9()).jsonStorePath}function lW($){if($===B9()&&w2(uW()))IY();if(!w2($))G0($),uB($,`${JSON.stringify({items:[]},null,2)} -`)}function uA($){return $.toISOString().replace(/[:.]/g,"-")}function kY($){let _=[`id:${$.id}`];if(typeof $.short_id==="string"&&$.short_id.length>0)_.push(`short_id:${$.short_id}`);return _}function dA($){let _=new Set;for(let J of $)for(let U of kY(J))_.add(U);return _}function nA($,_){return kY(_).some((J)=>$.has(J))}function FY($,_){G0($),gY($,`${JSON.stringify(_,null,2)} -`,{mode:384}),vB($,384)}function TB($){let _=JSON.parse(cW($,"utf8"));if(!_||typeof _!=="object"||!Array.isArray(_.items))return{store:{items:[]},skippedInvalid:0};let J={items:[]},U=0;for(let W of _.items)if(W&&typeof W==="object"&&typeof W.id==="string"&&W.id.length>0)J.items.push(W);else U+=1;return{store:J,skippedInvalid:U}}function IY($={}){if($.dryRun===!0)return SB($);return $4(B9(),()=>SB($),{createParent:!0})}function SB($={}){let _=$.dryRun===!0,J=$.now??new Date,U=s_(D9()),W=uW(),X=U.jsonStorePath,G=w2(W),Y=w2(X),Q={ok:!0,dry_run:_,legacy_path:W,canonical_path:X,legacy_exists:G,canonical_existed:Y,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:G?"Legacy global store already imported":"No legacy global store found"};if(!G)return Q;let q;try{let H=TB(W);q=H.store,Q.skipped_invalid=H.skippedInvalid}catch(H){return Q.ok=!1,Q.errors.push(`Could not read legacy store: ${H instanceof Error?H.message:String(H)}`),Q.message="Legacy global store import failed",Q}let L={items:[]};if(Y)try{L=TB(X).store}catch(H){return Q.ok=!1,Q.errors.push(`Could not read canonical store: ${H instanceof Error?H.message:String(H)}`),Q.message="Legacy global store import failed",Q}let N=dA(L.items),R={items:[...L.items]};for(let H of q.items){if(!H?.id){Q.skipped_invalid+=1;continue}if(nA(N,H)){Q.skipped_existing+=1;continue}R.items.push(H);for(let V of kY(H))N.add(V);Q.imported+=1}if(Q.would_create_canonical=!Y&&Q.imported>0,Q.canonical_created=!_&&Q.would_create_canonical,Q.message=Q.imported>0?`Imported ${Q.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",_||Q.imported===0)return Q;let B=`${uA(J)}-${iW().slice(0,8)}`;if(Y)Q.backup_path=MY(U.exportsDir,`legacy-open-knowledge-db-before-import-${B}.json`),FY(Q.backup_path,L);return FY(X,R),Q.report_path=MY(U.runsDir,`legacy-open-knowledge-import-${B}.json`),FY(Q.report_path,Q),Q}function g2($){if(!w2($))return{exists:!1,items:[]};let _=cW($,"utf8"),J=JSON.parse(_);if(!J||!Array.isArray(J.items))return{exists:!0,items:[]};return{exists:!0,items:J.items}}function cA($){return`${$}.lock`}var L9=1e4,mB=25,ZB=120000,iA=new Int32Array(new SharedArrayBuffer(4));function fY($){return typeof $==="object"&&$!==null&&"code"in $?String($.code):void 0}function xB($){let _=null;try{_=bY(hB($),"r"),AY(_)}catch{}finally{if(_!==null)try{nW(_)}catch{}}}var EY=new Set;function uB($,_){G0($);let J=MY(hB($),`.${xA($)}.tmp.${iW()}`),U=null;try{U=bY(J,"wx",384),gY(U,_),AY(U),nW(U),U=null,yB(J,$);try{vB($,384)}catch{}xB($)}catch(W){if(U!==null)try{nW(U)}catch{}try{wY(J)}catch{}throw W}}function dB($){Atomics.wait(iA,0,0,$)}function lA($){if(typeof $!=="number"||!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch(_){return fY(_)!=="ESRCH"}}function nB($,_){try{let J=cW($,"utf8"),U=JSON.parse(J);if(typeof U.ts==="number")return _-U.ts>ZB&&!lA(U.pid)}catch{}try{return _-mA($).mtimeMs>ZB}catch{return!1}}function rA($){let _=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),J=`${$}.stale.${_}.${iW()}`;try{yB($,J)}catch(U){if(fY(U)!=="ENOENT")throw U;return}}function pA($){let _=iW(),J=`${$}.breaker`,U=Date.now();while(Date.now()-U$;function sA($,_){this[$]=aA.bind(null,_)}var eA=($,_)=>{for(var J in _)tA($,J,{get:_[J],enumerable:!0,configurable:!0,set:sA.bind(_,J)})},z={};eA(z,{void:()=>yb,util:()=>y$,unknown:()=>Zb,union:()=>ub,undefined:()=>Pb,tuple:()=>cb,transformer:()=>tB,symbol:()=>Cb,string:()=>GH,strictObject:()=>xb,setErrorMap:()=>Jb,set:()=>rb,record:()=>ib,quotelessJson:()=>$b,promise:()=>eb,preprocess:()=>Jw,pipeline:()=>Ww,ostring:()=>Uw,optional:()=>$w,onumber:()=>Xw,oboolean:()=>Gw,objectUtil:()=>ZY,object:()=>mb,number:()=>YH,nullable:()=>_w,null:()=>Tb,never:()=>vb,nativeEnum:()=>sb,nan:()=>kb,map:()=>lb,makeIssue:()=>V9,literal:()=>tb,lazy:()=>ob,late:()=>wb,isValid:()=>a0,isDirty:()=>yY,isAsync:()=>pW,isAborted:()=>vY,intersection:()=>nb,instanceof:()=>gb,getParsedType:()=>M4,getErrorMap:()=>N9,function:()=>pb,enum:()=>ab,effect:()=>tB,discriminatedUnion:()=>db,defaultErrorMap:()=>C2,datetimeRegex:()=>WH,date:()=>fb,custom:()=>XH,coerce:()=>Yw,boolean:()=>QH,bigint:()=>Ib,array:()=>hb,any:()=>Sb,addIssueToContext:()=>d,ZodVoid:()=>tW,ZodUnknown:()=>Y0,ZodUnion:()=>Z2,ZodUndefined:()=>T2,ZodType:()=>k$,ZodTuple:()=>J4,ZodTransformer:()=>D6,ZodSymbol:()=>oW,ZodString:()=>M6,ZodSet:()=>$1,ZodSchema:()=>k$,ZodRecord:()=>aW,ZodReadonly:()=>d2,ZodPromise:()=>_1,ZodPipeline:()=>$U,ZodParsedType:()=>r,ZodOptional:()=>b6,ZodObject:()=>O_,ZodNumber:()=>Q0,ZodNullable:()=>A4,ZodNull:()=>S2,ZodNever:()=>_4,ZodNativeEnum:()=>m2,ZodNaN:()=>eW,ZodMap:()=>sW,ZodLiteral:()=>h2,ZodLazy:()=>y2,ZodIssueCode:()=>P,ZodIntersection:()=>v2,ZodFunction:()=>f2,ZodFirstPartyTypeKind:()=>D$,ZodError:()=>e_,ZodEnum:()=>z0,ZodEffects:()=>D6,ZodDiscriminatedUnion:()=>K9,ZodDefault:()=>x2,ZodDate:()=>s0,ZodCatch:()=>u2,ZodBranded:()=>F9,ZodBoolean:()=>P2,ZodBigInt:()=>q0,ZodArray:()=>A6,ZodAny:()=>e0,Schema:()=>k$,ParseStatus:()=>f_,OK:()=>x_,NEVER:()=>Qw,INVALID:()=>Q$,EMPTY_PATH:()=>Wb,DIRTY:()=>I2,BRAND:()=>bb});var y$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(y$||(y$={}));var ZY;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(ZY||(ZY={}));var r=y$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),M4=($)=>{switch(typeof $){case"undefined":return r.undefined;case"string":return r.string;case"number":return Number.isNaN($)?r.nan:r.number;case"boolean":return r.boolean;case"function":return r.function;case"bigint":return r.bigint;case"symbol":return r.symbol;case"object":if(Array.isArray($))return r.array;if($===null)return r.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return r.promise;if(typeof Map<"u"&&$ instanceof Map)return r.map;if(typeof Set<"u"&&$ instanceof Set)return r.set;if(typeof Date<"u"&&$ instanceof Date)return r.date;return r.object;default:return r.unknown}},P=y$.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$b=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class e_ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}e_.create=($)=>{return new e_($)};var _b=($,_)=>{let J;switch($.code){case P.invalid_type:if($.received===r.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case P.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,y$.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:J=`Unrecognized key(s) in object: ${y$.joinValues($.keys,", ")}`;break;case P.invalid_union:J="Invalid input";break;case P.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${y$.joinValues($.options)}`;break;case P.invalid_enum_value:J=`Invalid enum value. Expected ${y$.joinValues($.options)}, received '${$.received}'`;break;case P.invalid_arguments:J="Invalid function arguments";break;case P.invalid_return_type:J="Invalid function return type";break;case P.invalid_date:J="Invalid date";break;case P.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else y$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case P.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case P.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case P.custom:J="Invalid input";break;case P.invalid_intersection_types:J="Intersection results could not be merged";break;case P.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case P.not_finite:J="Number must be finite";break;default:J=_.defaultError,y$.assertNever($)}return{message:J}},C2=_b,$H=C2;function Jb($){$H=$}function N9(){return $H}var V9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},Wb=[];function d($,_){let J=N9(),U=V9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===C2?void 0:C2].filter((W)=>!!W)});$.common.issues.push(U)}class f_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return Q$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return f_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return Q$;if(X.status==="aborted")return Q$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var Q$=Object.freeze({status:"aborted"}),I2=($)=>({status:"dirty",value:$}),x_=($)=>({status:"valid",value:$}),vY=($)=>$.status==="aborted",yY=($)=>$.status==="dirty",a0=($)=>$.status==="valid",pW=($)=>typeof Promise<"u"&&$ instanceof Promise,_$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(_$||(_$={}));class w6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var pB=($,_)=>{if(a0(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new e_($.common.issues);return this._error=J,this._error}}}};function M$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class k${get description(){return this._def.description}_getType($){return M4($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:M4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new f_,ctx:{common:$.parent.common,data:$.data,parsedType:M4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(pW(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M4($)},U=this._parseSync({data:$,path:J.path,parent:J});return pB(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M4($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return a0(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>a0(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M4($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(pW(U)?U:Promise.resolve(U));return pB(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:P.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new D6({schema:this,typeName:D$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(_)=>this["~validate"](_)}}optional(){return b6.create(this,this._def)}nullable(){return A4.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return A6.create(this)}promise(){return _1.create(this,this._def)}or($){return Z2.create([this,$],this._def)}and($){return v2.create(this,$,this._def)}transform($){return new D6({...M$(this._def),schema:this,typeName:D$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new x2({...M$(this._def),innerType:this,defaultValue:_,typeName:D$.ZodDefault})}brand(){return new F9({typeName:D$.ZodBranded,type:this,...M$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new u2({...M$(this._def),innerType:this,catchValue:_,typeName:D$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return $U.create(this,$)}readonly(){return d2.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Ub=/^c[^\s-]{8,}$/i,Xb=/^[0-9a-z]+$/,Gb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Qb=/^[a-z0-9_-]{21}$/i,qb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zb=/^[-+]?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)?)??$/,jb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Db="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",CY,Ob=/^(?:(?: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])$/,Lb=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Bb=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Hb=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_H="((\\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])))",Rb=new RegExp(`^${_H}$`);function JH($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function Kb($){return new RegExp(`^${JH($)}$`)}function WH($){let _=`${_H}T${JH($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function Fb($,_){if((_==="v4"||!_)&&Ob.test($))return!0;if((_==="v6"||!_)&&Bb.test($))return!0;return!1}function Eb($,_){if(!qb.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function Mb($,_){if((_==="v4"||!_)&&Lb.test($))return!0;if((_==="v6"||!_)&&Hb.test($))return!0;return!1}class M6 extends k${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==r.string){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_type,expected:r.string,received:W.parsedType}),Q$}let J=new f_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),d(U,{code:P.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:P.invalid_string,..._$.errToObj(J)})}_addCheck($){return new M6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",..._$.errToObj($)})}url($){return this._addCheck({kind:"url",..._$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",..._$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",..._$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",..._$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",..._$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",..._$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",..._$.errToObj($)})}base64($){return this._addCheck({kind:"base64",..._$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",..._$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",..._$.errToObj($)})}ip($){return this._addCheck({kind:"ip",..._$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",..._$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,..._$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,..._$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",..._$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,..._$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,..._$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,..._$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,..._$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,..._$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,..._$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,..._$.errToObj(_)})}nonempty($){return this.min(1,_$.errToObj($))}trim(){return new M6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new M6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new M6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}M6.create=($)=>{return new M6({checks:[],typeName:D$.ZodString,coerce:$?.coerce??!1,...M$($)})};function Ab($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class Q0 extends k${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==r.number){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_type,expected:r.number,received:W.parsedType}),Q$}let J=void 0,U=new f_;for(let W of this._def.checks)if(W.kind==="int"){if(!y$.isInteger($.data))J=this._getOrReturnCtx($,J),d(J,{code:P.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),d(J,{code:P.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(Ab($.data,W.value)!==0)J=this._getOrReturnCtx($,J),d(J,{code:P.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),d(J,{code:P.not_finite,message:W.message}),U.dirty()}else y$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,_$.toString(_))}gt($,_){return this.setLimit("min",$,!1,_$.toString(_))}lte($,_){return this.setLimit("max",$,!0,_$.toString(_))}lt($,_){return this.setLimit("max",$,!1,_$.toString(_))}setLimit($,_,J,U){return new Q0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:_$.toString(U)}]})}_addCheck($){return new Q0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:_$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:_$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:_$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&y$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}Q0.create=($)=>{return new Q0({checks:[],typeName:D$.ZodNumber,coerce:$?.coerce||!1,...M$($)})};class q0 extends k${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==r.bigint)return this._getInvalidInput($);let J=void 0,U=new f_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),d(J,{code:P.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),d(J,{code:P.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else y$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return d(_,{code:P.invalid_type,expected:r.bigint,received:_.parsedType}),Q$}gte($,_){return this.setLimit("min",$,!0,_$.toString(_))}gt($,_){return this.setLimit("min",$,!1,_$.toString(_))}lte($,_){return this.setLimit("max",$,!0,_$.toString(_))}lt($,_){return this.setLimit("max",$,!1,_$.toString(_))}setLimit($,_,J,U){return new q0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:_$.toString(U)}]})}_addCheck($){return new q0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:_$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}q0.create=($)=>{return new q0({checks:[],typeName:D$.ZodBigInt,coerce:$?.coerce??!1,...M$($)})};class P2 extends k${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==r.boolean){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.boolean,received:J.parsedType}),Q$}return x_($.data)}}P2.create=($)=>{return new P2({typeName:D$.ZodBoolean,coerce:$?.coerce||!1,...M$($)})};class s0 extends k${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==r.date){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_type,expected:r.date,received:W.parsedType}),Q$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_date}),Q$}let J=new f_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),d(U,{code:P.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else y$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new s0({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:_$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:_$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}s0.create=($)=>{return new s0({checks:[],coerce:$?.coerce||!1,typeName:D$.ZodDate,...M$($)})};class oW extends k${_parse($){if(this._getType($)!==r.symbol){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.symbol,received:J.parsedType}),Q$}return x_($.data)}}oW.create=($)=>{return new oW({typeName:D$.ZodSymbol,...M$($)})};class T2 extends k${_parse($){if(this._getType($)!==r.undefined){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.undefined,received:J.parsedType}),Q$}return x_($.data)}}T2.create=($)=>{return new T2({typeName:D$.ZodUndefined,...M$($)})};class S2 extends k${_parse($){if(this._getType($)!==r.null){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.null,received:J.parsedType}),Q$}return x_($.data)}}S2.create=($)=>{return new S2({typeName:D$.ZodNull,...M$($)})};class e0 extends k${constructor(){super(...arguments);this._any=!0}_parse($){return x_($.data)}}e0.create=($)=>{return new e0({typeName:D$.ZodAny,...M$($)})};class Y0 extends k${constructor(){super(...arguments);this._unknown=!0}_parse($){return x_($.data)}}Y0.create=($)=>{return new Y0({typeName:D$.ZodUnknown,...M$($)})};class _4 extends k${_parse($){let _=this._getOrReturnCtx($);return d(_,{code:P.invalid_type,expected:r.never,received:_.parsedType}),Q$}}_4.create=($)=>{return new _4({typeName:D$.ZodNever,...M$($)})};class tW extends k${_parse($){if(this._getType($)!==r.undefined){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.void,received:J.parsedType}),Q$}return x_($.data)}}tW.create=($)=>{return new tW({typeName:D$.ZodVoid,...M$($)})};class A6 extends k${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==r.array)return d(_,{code:P.invalid_type,expected:r.array,received:_.parsedType}),Q$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)d(_,{code:P.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new w6(_,X,_.path,G))})).then((X)=>{return f_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new w6(_,X,_.path,G))});return f_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new A6({...this._def,minLength:{value:$,message:_$.toString(_)}})}max($,_){return new A6({...this._def,maxLength:{value:$,message:_$.toString(_)}})}length($,_){return new A6({...this._def,exactLength:{value:$,message:_$.toString(_)}})}nonempty($){return this.min(1,$)}}A6.create=($,_)=>{return new A6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:D$.ZodArray,...M$(_)})};function k2($){if($ instanceof O_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=b6.create(k2(U))}return new O_({...$._def,shape:()=>_})}else if($ instanceof A6)return new A6({...$._def,type:k2($.element)});else if($ instanceof b6)return b6.create(k2($.unwrap()));else if($ instanceof A4)return A4.create(k2($.unwrap()));else if($ instanceof J4)return J4.create($.items.map((_)=>k2(_)));else return $}class O_ extends k${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=y$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==r.object){let Q=this._getOrReturnCtx($);return d(Q,{code:P.invalid_type,expected:r.object,received:Q.parsedType}),Q$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof _4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new w6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof _4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)d(U,{code:P.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new w6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return f_.mergeObjectSync(J,Q)});else return f_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return _$.errToObj,new O_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:_$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new O_({...this._def,unknownKeys:"strip"})}passthrough(){return new O_({...this._def,unknownKeys:"passthrough"})}extend($){return new O_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new O_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:D$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new O_({...this._def,catchall:$})}pick($){let _={};for(let J of y$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new O_({...this._def,shape:()=>_})}omit($){let _={};for(let J of y$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new O_({...this._def,shape:()=>_})}deepPartial(){return k2(this)}partial($){let _={};for(let J of y$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new O_({...this._def,shape:()=>_})}required($){let _={};for(let J of y$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof b6)W=W._def.innerType;_[J]=W}return new O_({...this._def,shape:()=>_})}keyof(){return UH(y$.objectKeys(this.shape))}}O_.create=($,_)=>{return new O_({shape:()=>$,unknownKeys:"strip",catchall:_4.create(),typeName:D$.ZodObject,...M$(_)})};O_.strictCreate=($,_)=>{return new O_({shape:()=>$,unknownKeys:"strict",catchall:_4.create(),typeName:D$.ZodObject,...M$(_)})};O_.lazycreate=($,_)=>{return new O_({shape:$,unknownKeys:"strip",catchall:_4.create(),typeName:D$.ZodObject,...M$(_)})};class Z2 extends k${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new e_(G.ctx.common.issues));return d(_,{code:P.invalid_union,unionErrors:X}),Q$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new e_(Y));return d(_,{code:P.invalid_union,unionErrors:G}),Q$}}get options(){return this._def.options}}Z2.create=($,_)=>{return new Z2({options:$,typeName:D$.ZodUnion,...M$(_)})};var E4=($)=>{if($ instanceof y2)return E4($.schema);else if($ instanceof D6)return E4($.innerType());else if($ instanceof h2)return[$.value];else if($ instanceof z0)return $.options;else if($ instanceof m2)return y$.objectValues($.enum);else if($ instanceof x2)return E4($._def.innerType);else if($ instanceof T2)return[void 0];else if($ instanceof S2)return[null];else if($ instanceof b6)return[void 0,...E4($.unwrap())];else if($ instanceof A4)return[null,...E4($.unwrap())];else if($ instanceof F9)return E4($.unwrap());else if($ instanceof d2)return E4($.unwrap());else if($ instanceof u2)return E4($._def.innerType);else return[]};class K9 extends k${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.object)return d(_,{code:P.invalid_type,expected:r.object,received:_.parsedType}),Q$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return d(_,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),Q$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=E4(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new K9({typeName:D$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...M$(J)})}}function hY($,_){let J=M4($),U=M4(_);if($===_)return{valid:!0,data:$};else if(J===r.object&&U===r.object){let W=y$.objectKeys(_),X=y$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=hY($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===r.array&&U===r.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=hY(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===r.date&&U===r.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class v2 extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(vY(W)||vY(X))return Q$;let G=hY(W.value,X.value);if(!G.valid)return d(J,{code:P.invalid_intersection_types}),Q$;if(yY(W)||yY(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}v2.create=($,_,J)=>{return new v2({left:$,right:_,typeName:D$.ZodIntersection,...M$(J)})};class J4 extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.array)return d(J,{code:P.invalid_type,expected:r.array,received:J.parsedType}),Q$;if(J.data.lengththis._def.items.length)d(J,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new w6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return f_.mergeArray(_,X)});else return f_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new J4({...this._def,rest:$})}}J4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new J4({items:$,typeName:D$.ZodTuple,rest:null,...M$(_)})};class aW extends k${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.object)return d(J,{code:P.invalid_type,expected:r.object,received:J.parsedType}),Q$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new w6(J,G,J.path,G)),value:X._parse(new w6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return f_.mergeObjectAsync(_,U);else return f_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof k$)return new aW({keyType:$,valueType:_,typeName:D$.ZodRecord,...M$(J)});return new aW({keyType:M6.create(),valueType:$,typeName:D$.ZodRecord,...M$(_)})}}class sW extends k${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.map)return d(J,{code:P.invalid_type,expected:r.map,received:J.parsedType}),Q$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new w6(J,G,J.path,[Q,"key"])),value:W._parse(new w6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return Q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return Q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}sW.create=($,_,J)=>{return new sW({valueType:_,keyType:$,typeName:D$.ZodMap,...M$(J)})};class $1 extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.set)return d(J,{code:P.invalid_type,expected:r.set,received:J.parsedType}),Q$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)d(J,{code:P.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return Q$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new w6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new $1({...this._def,minSize:{value:$,message:_$.toString(_)}})}max($,_){return new $1({...this._def,maxSize:{value:$,message:_$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}$1.create=($,_)=>{return new $1({valueType:$,minSize:null,maxSize:null,typeName:D$.ZodSet,...M$(_)})};class f2 extends k${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.function)return d(_,{code:P.invalid_type,expected:r.function,received:_.parsedType}),Q$;function J(G,Y){return V9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,N9(),C2].filter((Q)=>!!Q),issueData:{code:P.invalid_arguments,argumentsError:Y}})}function U(G,Y){return V9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,N9(),C2].filter((Q)=>!!Q),issueData:{code:P.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof _1){let G=this;return x_(async function(...Y){let Q=new e_([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return x_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new e_([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new e_([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new f2({...this._def,args:J4.create($).rest(Y0.create())})}returns($){return new f2({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new f2({args:$?$:J4.create([]).rest(Y0.create()),returns:_||Y0.create(),typeName:D$.ZodFunction,...M$(J)})}}class y2 extends k${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}y2.create=($,_)=>{return new y2({getter:$,typeName:D$.ZodLazy,...M$(_)})};class h2 extends k${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return d(_,{received:_.data,code:P.invalid_literal,expected:this._def.value}),Q$}return{status:"valid",value:$.data}}get value(){return this._def.value}}h2.create=($,_)=>{return new h2({value:$,typeName:D$.ZodLiteral,...M$(_)})};function UH($,_){return new z0({values:$,typeName:D$.ZodEnum,...M$(_)})}class z0 extends k${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return d(_,{expected:y$.joinValues(J),received:_.parsedType,code:P.invalid_type}),Q$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return d(_,{received:_.data,code:P.invalid_enum_value,options:J}),Q$}return x_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return z0.create($,{...this._def,..._})}exclude($,_=this._def){return z0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}z0.create=UH;class m2 extends k${_parse($){let _=y$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==r.string&&J.parsedType!==r.number){let U=y$.objectValues(_);return d(J,{expected:y$.joinValues(U),received:J.parsedType,code:P.invalid_type}),Q$}if(!this._cache)this._cache=new Set(y$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=y$.objectValues(_);return d(J,{received:J.data,code:P.invalid_enum_value,options:U}),Q$}return x_($.data)}get enum(){return this._def.values}}m2.create=($,_)=>{return new m2({values:$,typeName:D$.ZodNativeEnum,...M$(_)})};class _1 extends k${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.promise&&_.common.async===!1)return d(_,{code:P.invalid_type,expected:r.promise,received:_.parsedType}),Q$;let J=_.parsedType===r.promise?_.data:Promise.resolve(_.data);return x_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}_1.create=($,_)=>{return new _1({type:$,typeName:D$.ZodPromise,...M$(_)})};class D6 extends k${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(d(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return Q$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return Q$;if(Y.status==="dirty")return I2(Y.value);if(_.value==="dirty")return I2(Y.value);return Y});else{if(_.value==="aborted")return Q$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return Q$;if(G.status==="dirty")return I2(G.value);if(_.value==="dirty")return I2(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return Q$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return Q$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!a0(X))return Q$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!a0(X))return Q$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});y$.assertNever(U)}}D6.create=($,_,J)=>{return new D6({schema:$,typeName:D$.ZodEffects,effect:_,...M$(J)})};D6.createWithPreprocess=($,_,J)=>{return new D6({schema:_,effect:{type:"preprocess",transform:$},typeName:D$.ZodEffects,...M$(J)})};class b6 extends k${_parse($){if(this._getType($)===r.undefined)return x_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}b6.create=($,_)=>{return new b6({innerType:$,typeName:D$.ZodOptional,...M$(_)})};class A4 extends k${_parse($){if(this._getType($)===r.null)return x_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}A4.create=($,_)=>{return new A4({innerType:$,typeName:D$.ZodNullable,...M$(_)})};class x2 extends k${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===r.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}x2.create=($,_)=>{return new x2({innerType:$,typeName:D$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...M$(_)})};class u2 extends k${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(pW(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new e_(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new e_(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}u2.create=($,_)=>{return new u2({innerType:$,typeName:D$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...M$(_)})};class eW extends k${_parse($){if(this._getType($)!==r.nan){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.nan,received:J.parsedType}),Q$}return{status:"valid",value:$.data}}}eW.create=($)=>{return new eW({typeName:D$.ZodNaN,...M$($)})};var bb=Symbol("zod_brand");class F9 extends k${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class $U extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return Q$;if(W.status==="dirty")return _.dirty(),I2(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return Q$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new $U({in:$,out:_,typeName:D$.ZodPipeline})}}class d2 extends k${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(a0(U))U.value=Object.freeze(U.value);return U};return pW(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}d2.create=($,_)=>{return new d2({innerType:$,typeName:D$.ZodReadonly,...M$(_)})};function oB($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function XH($,_={},J){if($)return e0.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=oB(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=oB(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return e0.create()}var wb={object:O_.lazycreate},D$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(D$||(D$={}));var gb=($,_={message:`Input not instance of ${$.name}`})=>XH((J)=>J instanceof $,_),GH=M6.create,YH=Q0.create,kb=eW.create,Ib=q0.create,QH=P2.create,fb=s0.create,Cb=oW.create,Pb=T2.create,Tb=S2.create,Sb=e0.create,Zb=Y0.create,vb=_4.create,yb=tW.create,hb=A6.create,mb=O_.create,xb=O_.strictCreate,ub=Z2.create,db=K9.create,nb=v2.create,cb=J4.create,ib=aW.create,lb=sW.create,rb=$1.create,pb=f2.create,ob=y2.create,tb=h2.create,ab=z0.create,sb=m2.create,eb=_1.create,tB=D6.create,$w=b6.create,_w=A4.create,Jw=D6.createWithPreprocess,Ww=$U.create,Uw=()=>GH().optional(),Xw=()=>YH().optional(),Gw=()=>QH().optional(),Yw={string:($)=>M6.create({...$,coerce:!0}),number:($)=>Q0.create({...$,coerce:!0}),boolean:($)=>P2.create({...$,coerce:!0}),bigint:($)=>q0.create({...$,coerce:!0}),date:($)=>s0.create({...$,coerce:!0})},Qw=Q$;var $$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},qH=z.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),$6=z.string().datetime(),H$=z.string().trim().min(1),b4=H$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),zH=z.string().regex(/^[a-fA-F0-9]{64}$/),jH=z.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),w4=z.record(z.unknown()),i2=z.array(z.string().min(1)).default([]),J1=$6.nullable().optional(),qw=new Set(["succeeded","failed","cancelled","blocked","skipped"]),U1=z.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function p$($){return z.object({schema:z.literal($),id:z.string().min(1),createdAt:$6,updatedAt:J1,metadata:w4.optional()}).strict()}var Yt=z.object({schema:qH,id:z.string().min(1),createdAt:$6,updatedAt:J1,metadata:w4.optional()}).strict(),DH=z.enum(["agent","human","service","model","workflow","system"]),zw=p$($$.actorRef).extend({kind:DH,name:z.string().min(1).optional(),provider:z.string().min(1).optional(),accountId:z.string().min(1).optional(),machineId:z.string().min(1).optional(),capabilities:z.array(z.string().min(1)).default([])}).strict(),W4=z.object({kind:DH,id:z.string().min(1),name:z.string().min(1).optional(),provider:z.string().min(1).optional(),accountId:z.string().min(1).optional(),machineId:z.string().min(1).optional()}).strict(),OH=z.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),jw=p$($$.resourceRef).extend({kind:OH,name:z.string().min(1).optional(),uri:b4.optional(),externalId:H$.optional(),sourcePackage:H$.optional(),tags:i2}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:z.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),g$=z.object({kind:OH,id:z.string().min(1),name:z.string().min(1).optional(),uri:b4.optional(),externalId:H$.optional(),sourcePackage:H$.optional(),tags:i2}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:z.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),xY=z.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),Dw=z.enum(["none","partial","full","unknown"]),Ow=p$($$.evidenceRef).extend({kind:xY,uri:b4,sha256:zH.optional(),summary:z.string().min(1).optional(),contentType:z.string().min(1).optional(),sizeBytes:z.number().int().nonnegative().optional(),redaction:Dw.default("unknown"),producer:W4.optional(),resourceRefs:z.array(g$).default([]),tags:i2}).strict(),G_=z.object({id:z.string().min(1),kind:xY.optional(),uri:b4.optional(),sha256:zH.optional(),summary:z.string().min(1).optional()}).strict(),_U=p$($$.costEstimate).extend({currency:z.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:z.number().int().nonnegative(),provider:z.string().min(1).optional(),model:z.string().min(1).optional(),accountId:z.string().min(1).optional(),promptTokens:z.number().int().nonnegative().optional(),completionTokens:z.number().int().nonnegative().optional(),totalTokens:z.number().int().nonnegative().optional(),basis:z.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:z.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),Lw=z.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),LH=p$($$.decisionEnvelope).extend({decisionType:z.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:Lw,actor:W4.optional(),traceId:z.string().min(1).optional(),inputHash:jH.optional(),policyBundleId:z.string().min(1).optional(),selected:z.array(g$).default([]),skipped:z.array(g$).default([]),reason:z.string().min(1),obligations:z.array(z.string().min(1)).default([]),redactions:z.array(z.string().min(1)).default([]),costEstimate:_U.optional(),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),Bw=p$($$.capabilityCard).extend({kind:z.enum(["model","tool","machine","agent","lane","connector","service"]),name:z.string().min(1),version:z.string().min(1).optional(),status:z.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:z.array(z.string().min(1)).default([]),limitations:z.array(z.string().min(1)).default([]),riskLevel:z.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:_U.optional(),evidenceRefs:z.array(G_).default([])}).strict(),n2=z.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),Hw=z.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),Nw=z.object({refName:H$,requiredForModes:z.array(n2).min(1),allowedSecretInputs:z.array(z.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:H$,revocationCheck:z.boolean().default(!0)}).strict(),Vw=z.object({operation:H$,supportedModes:z.array(n2).min(1),sideEffectClass:Hw,requiresApproval:z.boolean().default(!1),requiresIdempotencyKey:z.boolean().default(!1),requiresSandboxEvidence:z.boolean().default(!1),requiresRollbackOrRevocation:z.boolean().default(!1),rollbackOrRevocation:H$.optional(),noSideEffectSmoke:H$.optional(),reconciliation:H$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),Rw=z.object({providerId:H$,appId:H$,adapterId:H$,ownerPackage:H$,modes:z.array(n2).min(1),defaultMode:n2,credentialRequirements:z.array(Nw).default([]),operations:z.array(Vw).min(1),rateLimitPosture:H$,costPosture:H$.optional(),auditEvents:z.array(H$).default([]),redactionRules:z.array(H$).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:z.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),Kw=z.object({appId:H$,repo:H$,priority:z.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:z.array(H$).min(1),firstOperations:z.array(H$).min(1),blockedUntil:z.array(H$).default([])}).strict(),Fw=p$($$.providerLiveModeStandard).extend({name:H$,version:H$,modes:z.array(n2).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:z.array(H$).min(1),liveMutationGate:z.object({requiredMode:z.literal("live_mutating"),requiredChecks:z.array(H$).min(1),forbiddenBypassSignals:z.array(H$).min(1),disabledLiveSmoke:H$}).strict(),noSideEffectSmoke:z.object({requiredForModes:z.array(n2).min(1),commandEvidence:z.array(H$).min(1),secretOutputScan:z.boolean().default(!0)}).strict(),credentialPolicy:z.object({acceptedInputs:z.array(z.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:z.literal(!1),missingCredentialBehavior:z.literal("fail_closed"),revocationCheckRequired:z.boolean().default(!0)}).strict(),operationCards:z.array(Rw).min(1),firstAdoptionTargets:z.array(Kw).min(1),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:z.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),Ew=z.object({id:z.string().min(1),title:z.string().min(1).optional(),summary:z.string().min(1),text:z.string().optional(),tokens:z.number().int().nonnegative().optional(),source:G_,resourceRefs:z.array(g$).default([])}).strict(),BH=p$($$.contextPack).extend({objective:z.string().min(1),budget:z.object({maxTokens:z.number().int().positive().optional(),maxBytes:z.number().int().positive().optional()}).strict().optional(),items:z.array(Ew).default([]),citations:z.array(G_).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),permissions:z.array(z.string().min(1)).default([]),redactions:z.array(z.string().min(1)).default([]),conflicts:z.array(z.string().min(1)).default([]),uncertainty:z.string().min(1).optional()}).strict(),E6=H$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),W1=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),Mw=z.enum(["public","internal","private","sensitive"]),Aw=z.enum(["draft","active","paused","archived"]),uY=z.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),HH=p$($$.integrationRef).extend({kind:uY,name:z.string().min(1),projectId:W1.optional(),sourcePackage:H$.optional(),externalId:H$.optional(),uri:b4.optional(),enabled:z.boolean().default(!0),readOnly:z.boolean().default(!0),capabilities:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:g$.optional(),evidenceRefs:z.array(G_).default([]),config:w4.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:z.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),bw=z.object({schemaRoot:E6.default(".hasna/project"),dashboardManifest:E6.default(".hasna/project/dashboard.render.json"),snapshotsDir:E6.default(".hasna/project/snapshots"),documentsDir:E6.default("documents"),reportsDir:E6.default("reports"),evidenceDir:E6.default(".hasna/project/evidence"),privateDir:E6.default(".hasna/project/private")}).strict(),ww=p$($$.projectManifest).extend({projectId:W1,slug:W1,name:z.string().min(1),summary:z.string().min(1).optional(),status:Aw.default("active"),classification:Mw.default("private"),owner:W4.optional(),layout:bw.default({}),integrations:z.array(HH).default([]),renderManifests:z.array(g$).default([]),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),tags:i2}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:z.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:z.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:z.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),gw=z.enum(["local","package","provider","url"]),dY=z.object({id:z.string().min(1),kind:gw,specifier:z.string().min(1),path:E6.optional(),packageName:z.string().min(1).optional(),uri:b4.optional(),provider:uY.optional(),schemaId:qH.optional(),integrity:jH.optional(),resourceRef:g$.optional(),optional:z.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:z.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:z.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:z.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:z.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),kw=z.enum(["dashboard","canvas","panel","report","document","custom"]),Iw=z.object({id:z.string().min(1),title:z.string().min(1),kind:kw,default:z.boolean().default(!1),entry:E6.optional(),imports:z.array(dY).default([]),panelRefs:z.array(g$).default([]),dataRefs:z.array(g$).default([]),layout:w4.optional()}).strict(),fw=p$($$.renderManifest).extend({projectId:W1,name:z.string().min(1),version:z.string().min(1),manifestPath:E6.default(".hasna/project/dashboard.render.json"),renderer:z.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:z.array(Iw).min(1),imports:z.array(dY).default([]),theme:w4.optional(),compatibility:z.object({minProjectsVersion:z.string().min(1).optional(),minContractsVersion:z.string().min(1).optional()}).strict().optional(),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:z.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),Cw=z.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),Pw=z.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Tw=z.object({id:z.string().min(1),label:z.string().min(1),value:z.union([z.string(),z.number(),z.boolean()]),unit:z.string().min(1).optional(),status:z.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:z.array(g$).default([])}).strict(),Sw=z.object({id:z.string().min(1),title:z.string().min(1),summary:z.string().min(1).optional(),status:z.string().min(1).optional(),priority:z.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:$6.optional(),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),metadata:w4.optional()}).strict(),Zw=z.object({renderer:z.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:z.string().min(1).optional(),entry:E6.optional(),imports:z.array(dY).default([]),spec:w4.default({})}).strict(),NH=p$($$.projectPanel).extend({projectId:W1,provider:z.object({kind:uY,id:z.string().min(1),name:z.string().min(1).optional(),sourcePackage:H$.optional(),externalId:H$.optional()}).strict(),kind:Pw,title:z.string().min(1),summary:z.string().min(1).optional(),state:Cw.default("ready"),stateReason:z.string().min(1).optional(),generatedAt:$6,freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),metrics:z.array(Tw).default([]),items:z.array(Sw).default([]),actions:z.array(g$).default([]),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),renderFragment:Zw.optional(),warnings:z.array(z.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:z.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:z.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),vw=p$($$.projectSnapshot).extend({projectId:W1,generatedAt:$6,status:U1.default("unknown"),manifestRef:g$,renderManifestRef:g$.optional(),panels:z.array(NH).default([]),contextPacks:z.array(BH).default([]),proofBundleRefs:z.array(g$).default([]),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),warnings:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:z.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),VH=z.object({id:z.string().min(1),kind:z.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:z.boolean().default(!0),command:z.string().min(1).optional(),expected:z.string().min(1).optional(),timeoutMs:z.number().int().positive().optional(),resourceRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:z.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),yw=p$($$.validationPlan).extend({objective:z.string().min(1),subject:g$.optional(),checks:z.array(VH).min(1),verifier:W4.optional(),requiredEvidenceKinds:z.array(xY).default([])}).strict(),hw=z.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),mw=z.enum(["draft","active","deprecated","archived"]),xw=z.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),uw=z.object({key:z.string().regex(/^[A-Z][A-Z0-9_]*$/),description:z.string().min(1),required:z.boolean().default(!1),["secret"]:z.boolean().default(!1),group:z.string().min(1).optional(),default:z.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),dw=z.object({name:z.string().min(1),command:z.string().min(1),description:z.string().min(1).optional(),required:z.boolean().default(!1)}).strict(),nw=z.object({packageManager:z.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:z.array(z.string().min(1)).default([]),requiredFiles:z.array(z.string().min(1)).default([]),requiredDirectories:z.array(z.string().min(1)).default([]),optionalDirectories:z.array(z.string().min(1)).default([])}).strict(),cw=p$($$.scaffoldManifest).extend({name:z.string().min(1),version:z.string().min(1),summary:z.string().min(1),type:hw,status:mw.default("draft"),capabilities:z.array(xw).default([]),techStack:z.array(z.string().min(1)).default([]),tags:i2,source:g$.optional(),output:nw,env:z.array(uw).default([]),scripts:z.array(dw).default([]),validationChecks:z.array(VH).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:z.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),iw=z.enum(["installed","failed","cancelled","partial","unknown"]),lw=p$($$.scaffoldInstallRecord).extend({scaffoldId:z.string().min(1),scaffoldVersion:z.string().min(1).optional(),manifestRef:g$.optional(),target:g$,status:iw,installedAt:$6.optional(),installer:W4.optional(),packageManager:z.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:w4.optional(),generatedFiles:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),proofBundleRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:z.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),c2=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),nY=z.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),RH=z.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),rw=z.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),pw=H$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),ow=z.enum(["active","stub","deprecated","archived"]),tw=z.enum(["stable","beta","canary","internal"]),aw=z.object({transport:z.enum(["http","stdio"]).default("http"),bin:z.string().min(1).optional(),url:b4.optional()}).strict(),sw=z.object({healthPath:z.string().min(1).default("/health"),port:z.number().int().positive().optional(),baseUrl:b4.optional()}).strict(),ew=z.object({bins:z.array(z.string().min(1)).default([]),mcp:aw.optional(),http:sw.optional()}).strict(),$g=p$($$.app).extend({appId:c2,npmName:nY,repoFolder:c2,githubUrl:pw,projectSlug:W1,surfaces:ew.default({}),lifecycle:ow,releaseChannel:tw.default("stable"),summary:z.string().min(1).optional(),tags:i2}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:z.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),_g=z.enum(["skill","ci","backfilled"]),Jg=p$($$.release).extend({appId:c2,package:nY,version:RH,gitSha:rw,publishedAt:$6,publishPath:_g,changelogRef:g$.optional(),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Wg=z.enum(["install","update","rollback","freeze-blocked"]),Ug=z.object({cliVersion:z.string().min(1).optional(),mcpHealth:z.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),Xg=p$($$.rolloutRecord).extend({appId:c2,package:nY,version:RH,machine:H$,action:Wg,result:U1,verifiedBy:Ug.optional(),at:$6,evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:z.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),Gg=z.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),Yg=z.enum(["pending","queued","sent","failed","skipped","suppressed"]),Qg=z.object({channel:Gg,status:Yg,deliveredAt:$6.optional(),detail:z.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:z.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),qg=p$($$.announcement).extend({campaignId:H$,appId:c2.optional(),releaseRef:g$.optional(),channels:z.array(Qg).min(1),audienceRef:g$,sentAt:$6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:z.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:z.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),zg=z.enum(["tag","attribute","group"]),jg=z.enum(["eq","neq","in","not_in","exists","not_exists"]),aB=z.union([z.string(),z.number(),z.boolean()]),Dg=z.object({kind:zg,key:z.string().min(1).optional(),op:jg.default("eq"),value:aB.optional(),values:z.array(aB).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:z.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),Og=z.object({match:z.enum(["all","any"]).default("all"),predicates:z.array(Dg).min(1)}).strict(),Lg=z.enum(["opt_in","opt_out","transactional","none"]),Bg=p$($$.audience).extend({audienceId:c2,name:H$,definition:Og,consentPolicy:Lg,suppressionSyncedAt:J1}).strict(),PY=["@hasna/cloud","open-cloud"],Hg=z.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),Ng=z.object({id:z.string().min(1),provider:Hg,kind:z.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:z.string().min(1),region:z.string().min(1).optional(),accountId:z.string().min(1).optional(),uri:b4.optional(),machineScoped:z.boolean().default(!1)}).strict(),KH=p$($$.appCloudManifest).extend({packageName:z.string().min(1),packageVersion:z.string().min(1).optional(),appId:z.string().min(1),repository:g$.optional(),storageMode:z.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:z.enum(["none","app_owned","external_service","local_cache"]),cloudResources:z.array(Ng).default([]),localCache:z.object({path:z.string().min(1).optional(),pullMode:z.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:z.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:z.array(z.string().min(1)).default([...PY]),dependencies:z.array(z.string().min(1)).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...PY,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:z.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of PY)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:z.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:z.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:z.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:z.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:z.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:z.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),FH=z.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),Vg=z.enum(["low","medium","high","critical"]),EH=z.object({id:z.string().min(1),kind:FH,severity:Vg,path:z.string().min(1).optional(),packageName:z.string().min(1).optional(),pattern:z.string().min(1),message:z.string().min(1),evidenceRefs:z.array(G_).default([])}).strict(),Rg=z.object({id:z.string().min(1),kind:FH,status:U1,target:z.string().min(1),command:z.string().min(1).optional(),evidenceRefs:z.array(G_).default([]),findings:z.array(EH).default([])}).strict(),Kg=p$($$.noCloudEvidencePack).extend({subject:g$,packageName:z.string().min(1).optional(),packageVersion:z.string().min(1).optional(),generatedBy:W4.optional(),scanMode:z.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:U1,verdict:z.enum(["passed","failed","warning","not_run"]),appCloudManifest:KH.optional(),checks:z.array(Rg).min(1),findings:z.array(EH).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),Fg=z.object({checkId:z.string().min(1),status:U1,summary:z.string().min(1).optional(),startedAt:J1,finishedAt:J1,evidenceRefs:z.array(G_).default([])}).strict(),Eg=p$($$.proofBundle).extend({subject:g$,validationPlanRef:g$.optional(),status:U1,verdict:z.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:z.array(Fg).default([]),verifier:W4.optional(),evidenceRefs:z.array(G_).default([]),residualRisks:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),Mg=p$($$.workRun).extend({objective:z.string().min(1),status:U1,actor:W4,traceId:z.string().min(1).optional(),startedAt:J1,finishedAt:J1,constraints:z.array(z.string().min(1)).default([]),resourceRefs:z.array(g$).default([]),decisions:z.array(LH).default([]),costEstimates:z.array(_U).default([]),evidenceRefs:z.array(G_).default([]),validationPlanRefs:z.array(g$).default([]),proofBundleRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),Ag=z.object({id:z.string().min(1),at:$6,kind:z.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:z.string().min(1),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),costEstimate:_U.optional()}).strict(),bg=p$($$.agentTrajectory).extend({actor:W4,workRunRef:g$.optional(),events:z.array(Ag).default([]),outcome:z.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:g$.optional()}).strict(),wg="v1",gg=z.enum(["library","cli-with-store","service","saas"]),kg=["local","self-hosted","cloud"],MH=z.enum(kg),Ig=z.enum(["supported","deferred","unsupported"]),fg=z.enum(["none","local-only","api-key","session","service-token","custom"]),TY=z.object({method:z.enum(["GET","POST","PUT","PATCH","DELETE"]),path:z.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:z.boolean().default(!1),description:z.string().min(1).optional()}).strict(),Cg=z.object({id:z.string().min(1),kind:z.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:z.boolean().default(!0),command:z.string().min(1).optional(),evidenceRef:G_.optional(),status:z.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:z.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:z.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),Pg=z.object({name:z.string().min(1),status:Ig,bin:z.string().min(1).optional(),mcpBin:z.string().min(1).optional(),authMode:fg,deploymentModes:z.array(MH).min(1),health:TY.optional(),readiness:TY.optional(),version:TY.optional(),apiBasePath:z.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:z.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:z.string().min(1).optional(),readinessGates:z.array(Cg).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:z.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:z.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:z.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:z.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),Tg=["local","cloud"],AH=z.enum(Tg),Sg=["remote","hybrid","self_hosted"],Zg=z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),vg=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function yg($){return vg.map((_)=>`${$}${_}`)}function sB($){return`hasna/oss/${$}/database-url`}var hg=z.object({mode:AH,envPrefix:z.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:z.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:z.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:z.string().min(1).optional()}).strict(),mg=z.object({$schema:z.string().min(1).optional(),schema:z.literal($$.serviceContract),name:Zg,class:gg,contractVersion:z.literal(wg),kitVersion:z.string().min(1),description:z.string().min(1).optional(),bins:z.array(z.string().min(1)).default([]),storage:hg.optional(),deploymentModes:z.array(MH).default(["local"]),serviceSurfaces:z.array(Pg).default([]),metadata:w4.optional()}).strict().superRefine(($,_)=>{let J=new Set(yg($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:z.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:z.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:z.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==sB($.name))_.addIssue({code:z.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${sB($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:z.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:z.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:z.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:z.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:z.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:z.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),Qt=z.object({status:z.enum(["ok","degraded","unavailable"]),version:z.string().min(1),mode:AH}).strict(),qt=z.object({ready:z.boolean(),reason:z.string().min(1).optional()}).strict(),zt=z.object({version:z.string().min(1)}).strict(),xg=z.enum(["info","notice","breaking","critical"]),ug=z.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),dg=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],ng=z.enum(dg);var cg=z.enum(["fleet","package","machine"]),bH=p$($$.commsEventEnvelope).extend({type:ug,severity:xg,scope:cg,summary:z.string().min(1).optional(),source:W4.optional(),affected_packages:z.array(H$).default([]),affected_machines:z.array(H$).default([]),action_required:z.boolean().default(!1),ack_by:$6.optional(),dedupe_key:H$,resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:z.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),ig=z.enum(["fleet","package","product","loop-lane","initiative","personal"]),lg=z.enum(["quiet","work","firehose"]),rg=H$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),pg=p$($$.commsChannelMetadata).extend({class:ig,noise:lg.optional(),owner:H$.optional(),until:rg.optional(),successor:H$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:z.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:z.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),eB={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},og=p$($$.commsMessageMetadata).extend({tag:ng,envelope:bH}).strict().superRefine(($,_)=>{let J=eB[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:z.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:z.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(eB))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:z.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var jt={[$$.actorRef]:zw,[$$.resourceRef]:jw,[$$.evidenceRef]:Ow,[$$.workRun]:Mg,[$$.decisionEnvelope]:LH,[$$.costEstimate]:_U,[$$.capabilityCard]:Bw,[$$.providerLiveModeStandard]:Fw,[$$.contextPack]:BH,[$$.integrationRef]:HH,[$$.projectManifest]:ww,[$$.projectPanel]:NH,[$$.projectSnapshot]:vw,[$$.renderManifest]:fw,[$$.agentTrajectory]:bg,[$$.validationPlan]:yw,[$$.proofBundle]:Eg,[$$.scaffoldManifest]:cw,[$$.scaffoldInstallRecord]:lw,[$$.appCloudManifest]:KH,[$$.noCloudEvidencePack]:Kg,[$$.serviceContract]:mg,[$$.commsEventEnvelope]:bH,[$$.commsChannelMetadata]:pg,[$$.commsMessageMetadata]:og,[$$.app]:$g,[$$.release]:Jg,[$$.rolloutRecord]:Xg,[$$.announcement]:qg,[$$.audience]:Bg};function tg($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(Sg.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}function ag($){return $.toUpperCase().replace(/-/g,"_")}function sg($){return`https://${$}.hasna.xyz`}function wH($){let _=ag($);return{modeKeys:[`HASNA_${_}_STORAGE_MODE`,`HASNA_${_}_MODE`,`${_}_STORAGE_MODE`,`${_}_MODE`],apiUrlKeys:[`HASNA_${_}_API_URL`,`${_}_API_URL`],apiKeyKeys:[`HASNA_${_}_API_KEY`,`${_}_API_KEY`]}}function H9($,_){for(let J of _){let U=$[J]?.trim();if(U)return{key:J,value:U}}return null}function eg($){let _=new URL($);if(_.protocol!=="http:"&&_.protocol!=="https:")throw Error("API URL must use http or https.");let J=_.pathname.replace(/\/+$/,"");if(J.endsWith("/v1"))J=J.slice(0,-3);return _.pathname=`${J}/v1`,_.search="",_.hash="",_.toString().replace(/\/+$/,"")}function $k($,_=process.env){let J=wH($),U=H9(_,J.modeKeys),W=H9(_,J.apiUrlKeys),X=H9(_,J.apiKeyKeys),G="local",Y=null,Q="default",q=[];if(U){let B=tg(U.value);if(G=B.mode,Y=B.deprecatedAlias,Q=U.key,Y)q.push(`Deprecated mode '${Y}' from ${U.key} is treated as 'cloud'. Prefer ${J.modeKeys[0]}=cloud.`)}else if(W&&X)G="cloud",Q=`${W.key}+${X.key}`;if(G==="local")return{transport:"local",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(X),apiKeySource:X?X.key:null,misconfigured:!1,warning:q.length>0?q.join(" "):null};if(!X)return q.push(`${Q}=cloud but no API key is set (${J.apiKeyKeys[0]}). Refusing to route to cloud; using local store. Set ${J.apiKeyKeys[0]} to enable the cloud client.`),{transport:"local",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,misconfigured:!0,warning:q.join(" ")};let L=W?.value??sg($),N=W?W.key:"default",R;try{R=eg(L)}catch(B){let H=B instanceof Error?B.message:String(B);return q.push(`Invalid API URL from ${N}: ${H}. Using local store.`),{transport:"local",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:X.key,misconfigured:!0,warning:q.join(" ")}}return{transport:"cloud-http",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:R,apiUrlSource:N,apiKeyPresent:!0,apiKeySource:X.key,misconfigured:!1,warning:q.length>0?q.join(" "):null}}class R9 extends Error{status;method;path;body;constructor($,_,J,U){super(`Hasna cloud request failed: ${$} ${_} -> ${J}`);this.name="HasnaHttpError",this.status=J,this.method=$,this.path=_,this.body=U}}var _k=[408,425,429,500,502,503,504],Jk=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]);function Wk($,_){if(!_)return $;let J=_ instanceof URLSearchParams?_:new URLSearchParams;if(!(_ instanceof URLSearchParams))for(let[W,X]of Object.entries(_)){if(X===null||X===void 0)continue;if(Array.isArray(X))for(let G of X)J.append(W,String(G));else J.append(W,String(X))}let U=J.toString();if(!U)return $;return`${$}${$.includes("?")?"&":"?"}${U}`}var Uk=($)=>new Promise((_)=>setTimeout(_,$));function Xk($){let _=$.fetchImpl??((q,L)=>fetch(q,L)),J=$.baseUrl.replace(/\/+$/,""),U=$.timeoutMs??30000,W=$.sleepImpl??Uk,X=$.retry;function G(q){let L=q!==void 0?q:X;if(L===!1)return null;let N=L??{};return{retries:N.retries??2,baseDelayMs:N.baseDelayMs??200,maxDelayMs:N.maxDelayMs??2000,retryStatuses:N.retryStatuses??[..._k]}}async function Y(q,L,N,R,B){let H={"x-api-key":$.apiKey,Authorization:`Bearer ${$.apiKey}`,Accept:"application/json",...$.headers??{},...B.headers??{}};if(B.idempotencyKey)H["Idempotency-Key"]=B.idempotencyKey;let V={method:q,headers:H};if(R!==void 0)H["Content-Type"]="application/json",V.body=JSON.stringify(R);let K=new AbortController,E=()=>K.abort();if(B.signal)if(B.signal.aborted)K.abort();else B.signal.addEventListener("abort",E,{once:!0});let F=setTimeout(()=>K.abort(),B.timeoutMs??U);V.signal=K.signal;let w;try{w=await _(N,V)}catch(v){let k=v instanceof Error?v:Error(String(v));if(B.signal?.aborted)return{ok:!1,retryable:!1,error:k};return{ok:!1,retryable:!0,error:k}}finally{if(clearTimeout(F),B.signal)B.signal.removeEventListener("abort",E)}let A=await w.text(),g=void 0;if(A.length>0)try{g=JSON.parse(A)}catch{g=A}if(!w.ok){let v=G(B.retry);return{ok:!1,retryable:v?v.retryStatuses.includes(w.status):!1,error:new R9(q,L,w.status,g)}}return{ok:!0,value:g}}async function Q(q,L,N,R={}){let B=q.toUpperCase(),H=Wk(L.startsWith("/")?L:`/${L}`,R.query),V=`${J}${H}`,K=G(R.retry),E=Jk.has(B)||Boolean(R.idempotencyKey),F=K&&E?K.retries+1:1,w=null;for(let A=1;A<=F;A++){let g=await Y(B,H,V,N,R);if(g.ok)return g.value;if(w=g,!(K!==null&&E&&g.retryable&&AQ("GET",q,void 0,L),post:(q,L,N)=>Q("POST",q,L,N),put:(q,L,N)=>Q("PUT",q,L,N),patch:(q,L,N)=>Q("PATCH",q,L,N),del:(q,L,N)=>Q("DELETE",q,L,N)}}function Gk($,_=process.env,J){let U=$k($,_);if(U.misconfigured)throw Error(U.warning??`Client for '${$}' is misconfigured for cloud mode.`);if(U.transport==="local"||!U.baseUrl)return{transport:"local",client:null,resolution:U};let W=wH($),X=H9(_,W.apiKeyKeys)?.value;if(!X)throw Error(`Client for '${$}' resolved to cloud-http without an API key.`);return{transport:"cloud-http",client:Xk({name:$,baseUrl:U.baseUrl,apiKey:X,...J?.fetchImpl?{fetchImpl:J.fetchImpl}:{},...J?.headers?{headers:J.headers}:{},...J?.timeoutMs?{timeoutMs:J.timeoutMs}:{},...J?.retry!==void 0?{retry:J.retry}:{},...J?.sleepImpl?{sleepImpl:J.sleepImpl}:{}}),resolution:U}}function mY($){let _=$.replace(/^\/+|\/+$/g,"");if(!_)throw Error("resource must be a non-empty path segment");return`/${_}`}function SY($,_){if(_===void 0||_===null||`${_}`.length===0)throw Error("id must be a non-empty string");return`${mY($)}/${encodeURIComponent(String(_))}`}function Yk(){let $=globalThis;if($.crypto?.randomUUID)return $.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function Qk($){if(Array.isArray($))return $;if($&&typeof $==="object"){let _=$;for(let J of["items","data","results","rows","records"])if(Array.isArray(_[J]))return _[J]}return[]}function qk($){if($&&typeof $==="object"){let _=$;for(let J of["total","count","totalCount","total_count"])if(typeof _[J]==="number")return _[J]}return null}function zk($){if($&&typeof $==="object"){let _=$;for(let J of["cursor","nextCursor","next_cursor","next"])if(typeof _[J]==="string")return _[J]}return null}function jk($,_){return{name:$,baseUrl:_.baseUrl,transport:_,async list(J,U={}){let W=await _.get(mY(J),U);return{items:Qk(W),total:qk(W),cursor:zk(W),raw:W}},async get(J,U,W={}){try{return await _.get(SY(J,U),W)}catch(X){if(X instanceof R9&&X.status===404)return null;throw X}},async create(J,U,W={}){let{idempotencyKey:X,...G}=W;return _.post(mY(J),U,{...G,idempotencyKey:X??Yk()})},async update(J,U,W,X={}){let{method:G="PATCH",idempotencyKey:Y,...Q}=X;return(G==="PUT"?_.put:_.patch)(SY(J,U),W,{...Q,...Y?{idempotencyKey:Y}:{}})},async delete(J,U,W={}){try{await _.del(SY(J,U),void 0,W)}catch(X){if(X instanceof R9&&X.status===404)return;throw X}}}}function cY($,_=process.env,J){let U=Gk($,_,J);if(U.transport==="cloud-http")return{transport:"cloud-http",client:jk($,U.client)};return{transport:"local",client:null}}var Dk=Object.defineProperty,Ok=($)=>$;function Lk($,_){this[$]=Ok.bind(null,_)}var Bk=($,_)=>{for(var J in _)Dk($,J,{get:_[J],enumerable:!0,configurable:!0,set:Lk.bind(_,J)})},j={};Bk(j,{void:()=>ek,util:()=>h$,unknown:()=>ak,union:()=>WI,undefined:()=>pk,tuple:()=>GI,transformer:()=>IH,symbol:()=>rk,string:()=>mH,strictObject:()=>JI,setErrorMap:()=>Vk,set:()=>qI,record:()=>YI,quotelessJson:()=>Hk,promise:()=>BI,preprocess:()=>VI,pipeline:()=>RI,ostring:()=>KI,optional:()=>HI,onumber:()=>FI,oboolean:()=>EI,objectUtil:()=>pY,object:()=>_I,number:()=>xH,nullable:()=>NI,null:()=>ok,never:()=>sk,nativeEnum:()=>LI,nan:()=>ck,map:()=>QI,makeIssue:()=>M9,literal:()=>DI,lazy:()=>jI,late:()=>dk,isValid:()=>X1,isDirty:()=>tY,isAsync:()=>JU,isAborted:()=>oY,intersection:()=>XI,instanceof:()=>nk,getParsedType:()=>k4,getErrorMap:()=>E9,function:()=>zI,enum:()=>OI,effect:()=>IH,discriminatedUnion:()=>UI,defaultErrorMap:()=>o2,datetimeRegex:()=>vH,date:()=>lk,custom:()=>hH,coerce:()=>MI,boolean:()=>uH,bigint:()=>ik,array:()=>$I,any:()=>tk,addIssueToContext:()=>n,ZodVoid:()=>UU,ZodUnknown:()=>j0,ZodUnion:()=>e2,ZodUndefined:()=>a2,ZodType:()=>f$,ZodTuple:()=>X4,ZodTransformer:()=>O6,ZodSymbol:()=>WU,ZodString:()=>k6,ZodSet:()=>Q1,ZodSchema:()=>f$,ZodRecord:()=>XU,ZodReadonly:()=>GJ,ZodPromise:()=>q1,ZodPipeline:()=>QU,ZodParsedType:()=>p,ZodOptional:()=>f6,ZodObject:()=>L_,ZodNumber:()=>D0,ZodNullable:()=>I4,ZodNull:()=>s2,ZodNever:()=>U4,ZodNativeEnum:()=>WJ,ZodNaN:()=>YU,ZodMap:()=>GU,ZodLiteral:()=>JJ,ZodLazy:()=>_J,ZodIssueCode:()=>T,ZodIntersection:()=>$J,ZodFunction:()=>p2,ZodFirstPartyTypeKind:()=>O$,ZodError:()=>_6,ZodEnum:()=>L0,ZodEffects:()=>O6,ZodDiscriminatedUnion:()=>A9,ZodDefault:()=>UJ,ZodDate:()=>G1,ZodCatch:()=>XJ,ZodBranded:()=>b9,ZodBoolean:()=>t2,ZodBigInt:()=>O0,ZodArray:()=>I6,ZodAny:()=>Y1,Schema:()=>f$,ParseStatus:()=>C_,OK:()=>u_,NEVER:()=>AI,INVALID:()=>q$,EMPTY_PATH:()=>Rk,DIRTY:()=>r2,BRAND:()=>uk});var h$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(h$||(h$={}));var pY;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(pY||(pY={}));var p=h$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),k4=($)=>{switch(typeof $){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN($)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":if(Array.isArray($))return p.array;if($===null)return p.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return p.promise;if(typeof Map<"u"&&$ instanceof Map)return p.map;if(typeof Set<"u"&&$ instanceof Set)return p.set;if(typeof Date<"u"&&$ instanceof Date)return p.date;return p.object;default:return p.unknown}},T=h$.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Hk=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class _6 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}_6.create=($)=>{return new _6($)};var Nk=($,_)=>{let J;switch($.code){case T.invalid_type:if($.received===p.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case T.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,h$.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:J=`Unrecognized key(s) in object: ${h$.joinValues($.keys,", ")}`;break;case T.invalid_union:J="Invalid input";break;case T.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${h$.joinValues($.options)}`;break;case T.invalid_enum_value:J=`Invalid enum value. Expected ${h$.joinValues($.options)}, received '${$.received}'`;break;case T.invalid_arguments:J="Invalid function arguments";break;case T.invalid_return_type:J="Invalid function return type";break;case T.invalid_date:J="Invalid date";break;case T.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else h$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case T.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case T.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case T.custom:J="Invalid input";break;case T.invalid_intersection_types:J="Intersection results could not be merged";break;case T.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case T.not_finite:J="Number must be finite";break;default:J=_.defaultError,h$.assertNever($)}return{message:J}},o2=Nk,TH=o2;function Vk($){TH=$}function E9(){return TH}var M9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},Rk=[];function n($,_){let J=E9(),U=M9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===o2?void 0:o2].filter((W)=>!!W)});$.common.issues.push(U)}class C_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return q$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return C_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return q$;if(X.status==="aborted")return q$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var q$=Object.freeze({status:"aborted"}),r2=($)=>({status:"dirty",value:$}),u_=($)=>({status:"valid",value:$}),oY=($)=>$.status==="aborted",tY=($)=>$.status==="dirty",X1=($)=>$.status==="valid",JU=($)=>typeof Promise<"u"&&$ instanceof Promise,W$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(W$||(W$={}));class C6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var gH=($,_)=>{if(X1(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new _6($.common.issues);return this._error=J,this._error}}}};function A$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class f${get description(){return this._def.description}_getType($){return k4($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:k4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new C_,ctx:{common:$.parent.common,data:$.data,parsedType:k4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(JU(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:k4($)},U=this._parseSync({data:$,path:J.path,parent:J});return gH(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:k4($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return X1(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>X1(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:k4($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(JU(U)?U:Promise.resolve(U));return gH(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:T.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new O6({schema:this,typeName:O$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(_)=>this["~validate"](_)}}optional(){return f6.create(this,this._def)}nullable(){return I4.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return I6.create(this)}promise(){return q1.create(this,this._def)}or($){return e2.create([this,$],this._def)}and($){return $J.create(this,$,this._def)}transform($){return new O6({...A$(this._def),schema:this,typeName:O$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new UJ({...A$(this._def),innerType:this,defaultValue:_,typeName:O$.ZodDefault})}brand(){return new b9({typeName:O$.ZodBranded,type:this,...A$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new XJ({...A$(this._def),innerType:this,catchValue:_,typeName:O$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return QU.create(this,$)}readonly(){return GJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Kk=/^c[^\s-]{8,}$/i,Fk=/^[0-9a-z]+$/,Ek=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Mk=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ak=/^[a-z0-9_-]{21}$/i,bk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wk=/^[-+]?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)?)??$/,gk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",iY,Ik=/^(?:(?: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])$/,fk=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Ck=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Pk=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Tk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,SH="((\\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])))",Zk=new RegExp(`^${SH}$`);function ZH($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function vk($){return new RegExp(`^${ZH($)}$`)}function vH($){let _=`${SH}T${ZH($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function yk($,_){if((_==="v4"||!_)&&Ik.test($))return!0;if((_==="v6"||!_)&&Ck.test($))return!0;return!1}function hk($,_){if(!bk.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function mk($,_){if((_==="v4"||!_)&&fk.test($))return!0;if((_==="v6"||!_)&&Pk.test($))return!0;return!1}class k6 extends f${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==p.string){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_type,expected:p.string,received:W.parsedType}),q$}let J=new C_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),n(U,{code:T.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:T.invalid_string,...W$.errToObj(J)})}_addCheck($){return new k6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...W$.errToObj($)})}url($){return this._addCheck({kind:"url",...W$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...W$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...W$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...W$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...W$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...W$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...W$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...W$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...W$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...W$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...W$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...W$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...W$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...W$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...W$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...W$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...W$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...W$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...W$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...W$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...W$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...W$.errToObj(_)})}nonempty($){return this.min(1,W$.errToObj($))}trim(){return new k6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new k6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new k6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}k6.create=($)=>{return new k6({checks:[],typeName:O$.ZodString,coerce:$?.coerce??!1,...A$($)})};function xk($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class D0 extends f${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==p.number){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_type,expected:p.number,received:W.parsedType}),q$}let J=void 0,U=new C_;for(let W of this._def.checks)if(W.kind==="int"){if(!h$.isInteger($.data))J=this._getOrReturnCtx($,J),n(J,{code:T.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),n(J,{code:T.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(xk($.data,W.value)!==0)J=this._getOrReturnCtx($,J),n(J,{code:T.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),n(J,{code:T.not_finite,message:W.message}),U.dirty()}else h$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,W$.toString(_))}gt($,_){return this.setLimit("min",$,!1,W$.toString(_))}lte($,_){return this.setLimit("max",$,!0,W$.toString(_))}lt($,_){return this.setLimit("max",$,!1,W$.toString(_))}setLimit($,_,J,U){return new D0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:W$.toString(U)}]})}_addCheck($){return new D0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:W$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:W$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:W$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&h$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}D0.create=($)=>{return new D0({checks:[],typeName:O$.ZodNumber,coerce:$?.coerce||!1,...A$($)})};class O0 extends f${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==p.bigint)return this._getInvalidInput($);let J=void 0,U=new C_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),n(J,{code:T.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),n(J,{code:T.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else h$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return n(_,{code:T.invalid_type,expected:p.bigint,received:_.parsedType}),q$}gte($,_){return this.setLimit("min",$,!0,W$.toString(_))}gt($,_){return this.setLimit("min",$,!1,W$.toString(_))}lte($,_){return this.setLimit("max",$,!0,W$.toString(_))}lt($,_){return this.setLimit("max",$,!1,W$.toString(_))}setLimit($,_,J,U){return new O0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:W$.toString(U)}]})}_addCheck($){return new O0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:W$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}O0.create=($)=>{return new O0({checks:[],typeName:O$.ZodBigInt,coerce:$?.coerce??!1,...A$($)})};class t2 extends f${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==p.boolean){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.boolean,received:J.parsedType}),q$}return u_($.data)}}t2.create=($)=>{return new t2({typeName:O$.ZodBoolean,coerce:$?.coerce||!1,...A$($)})};class G1 extends f${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==p.date){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_type,expected:p.date,received:W.parsedType}),q$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_date}),q$}let J=new C_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),n(U,{code:T.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else h$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new G1({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:W$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:W$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}G1.create=($)=>{return new G1({checks:[],coerce:$?.coerce||!1,typeName:O$.ZodDate,...A$($)})};class WU extends f${_parse($){if(this._getType($)!==p.symbol){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.symbol,received:J.parsedType}),q$}return u_($.data)}}WU.create=($)=>{return new WU({typeName:O$.ZodSymbol,...A$($)})};class a2 extends f${_parse($){if(this._getType($)!==p.undefined){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.undefined,received:J.parsedType}),q$}return u_($.data)}}a2.create=($)=>{return new a2({typeName:O$.ZodUndefined,...A$($)})};class s2 extends f${_parse($){if(this._getType($)!==p.null){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.null,received:J.parsedType}),q$}return u_($.data)}}s2.create=($)=>{return new s2({typeName:O$.ZodNull,...A$($)})};class Y1 extends f${constructor(){super(...arguments);this._any=!0}_parse($){return u_($.data)}}Y1.create=($)=>{return new Y1({typeName:O$.ZodAny,...A$($)})};class j0 extends f${constructor(){super(...arguments);this._unknown=!0}_parse($){return u_($.data)}}j0.create=($)=>{return new j0({typeName:O$.ZodUnknown,...A$($)})};class U4 extends f${_parse($){let _=this._getOrReturnCtx($);return n(_,{code:T.invalid_type,expected:p.never,received:_.parsedType}),q$}}U4.create=($)=>{return new U4({typeName:O$.ZodNever,...A$($)})};class UU extends f${_parse($){if(this._getType($)!==p.undefined){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.void,received:J.parsedType}),q$}return u_($.data)}}UU.create=($)=>{return new UU({typeName:O$.ZodVoid,...A$($)})};class I6 extends f${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==p.array)return n(_,{code:T.invalid_type,expected:p.array,received:_.parsedType}),q$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)n(_,{code:T.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new C6(_,X,_.path,G))})).then((X)=>{return C_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new C6(_,X,_.path,G))});return C_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new I6({...this._def,minLength:{value:$,message:W$.toString(_)}})}max($,_){return new I6({...this._def,maxLength:{value:$,message:W$.toString(_)}})}length($,_){return new I6({...this._def,exactLength:{value:$,message:W$.toString(_)}})}nonempty($){return this.min(1,$)}}I6.create=($,_)=>{return new I6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:O$.ZodArray,...A$(_)})};function l2($){if($ instanceof L_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=f6.create(l2(U))}return new L_({...$._def,shape:()=>_})}else if($ instanceof I6)return new I6({...$._def,type:l2($.element)});else if($ instanceof f6)return f6.create(l2($.unwrap()));else if($ instanceof I4)return I4.create(l2($.unwrap()));else if($ instanceof X4)return X4.create($.items.map((_)=>l2(_)));else return $}class L_ extends f${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=h$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==p.object){let Q=this._getOrReturnCtx($);return n(Q,{code:T.invalid_type,expected:p.object,received:Q.parsedType}),q$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof U4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new C6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof U4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)n(U,{code:T.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new C6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return C_.mergeObjectSync(J,Q)});else return C_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return W$.errToObj,new L_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:W$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new L_({...this._def,unknownKeys:"strip"})}passthrough(){return new L_({...this._def,unknownKeys:"passthrough"})}extend($){return new L_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new L_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:O$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new L_({...this._def,catchall:$})}pick($){let _={};for(let J of h$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new L_({...this._def,shape:()=>_})}omit($){let _={};for(let J of h$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new L_({...this._def,shape:()=>_})}deepPartial(){return l2(this)}partial($){let _={};for(let J of h$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new L_({...this._def,shape:()=>_})}required($){let _={};for(let J of h$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof f6)W=W._def.innerType;_[J]=W}return new L_({...this._def,shape:()=>_})}keyof(){return yH(h$.objectKeys(this.shape))}}L_.create=($,_)=>{return new L_({shape:()=>$,unknownKeys:"strip",catchall:U4.create(),typeName:O$.ZodObject,...A$(_)})};L_.strictCreate=($,_)=>{return new L_({shape:()=>$,unknownKeys:"strict",catchall:U4.create(),typeName:O$.ZodObject,...A$(_)})};L_.lazycreate=($,_)=>{return new L_({shape:$,unknownKeys:"strip",catchall:U4.create(),typeName:O$.ZodObject,...A$(_)})};class e2 extends f${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new _6(G.ctx.common.issues));return n(_,{code:T.invalid_union,unionErrors:X}),q$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new _6(Y));return n(_,{code:T.invalid_union,unionErrors:G}),q$}}get options(){return this._def.options}}e2.create=($,_)=>{return new e2({options:$,typeName:O$.ZodUnion,...A$(_)})};var g4=($)=>{if($ instanceof _J)return g4($.schema);else if($ instanceof O6)return g4($.innerType());else if($ instanceof JJ)return[$.value];else if($ instanceof L0)return $.options;else if($ instanceof WJ)return h$.objectValues($.enum);else if($ instanceof UJ)return g4($._def.innerType);else if($ instanceof a2)return[void 0];else if($ instanceof s2)return[null];else if($ instanceof f6)return[void 0,...g4($.unwrap())];else if($ instanceof I4)return[null,...g4($.unwrap())];else if($ instanceof b9)return g4($.unwrap());else if($ instanceof GJ)return g4($.unwrap());else if($ instanceof XJ)return g4($._def.innerType);else return[]};class A9 extends f${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.object)return n(_,{code:T.invalid_type,expected:p.object,received:_.parsedType}),q$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return n(_,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),q$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=g4(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new A9({typeName:O$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...A$(J)})}}function aY($,_){let J=k4($),U=k4(_);if($===_)return{valid:!0,data:$};else if(J===p.object&&U===p.object){let W=h$.objectKeys(_),X=h$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=aY($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===p.array&&U===p.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=aY(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===p.date&&U===p.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class $J extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(oY(W)||oY(X))return q$;let G=aY(W.value,X.value);if(!G.valid)return n(J,{code:T.invalid_intersection_types}),q$;if(tY(W)||tY(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}$J.create=($,_,J)=>{return new $J({left:$,right:_,typeName:O$.ZodIntersection,...A$(J)})};class X4 extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.array)return n(J,{code:T.invalid_type,expected:p.array,received:J.parsedType}),q$;if(J.data.lengththis._def.items.length)n(J,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new C6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return C_.mergeArray(_,X)});else return C_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new X4({...this._def,rest:$})}}X4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new X4({items:$,typeName:O$.ZodTuple,rest:null,...A$(_)})};class XU extends f${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.object)return n(J,{code:T.invalid_type,expected:p.object,received:J.parsedType}),q$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new C6(J,G,J.path,G)),value:X._parse(new C6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return C_.mergeObjectAsync(_,U);else return C_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof f$)return new XU({keyType:$,valueType:_,typeName:O$.ZodRecord,...A$(J)});return new XU({keyType:k6.create(),valueType:$,typeName:O$.ZodRecord,...A$(_)})}}class GU extends f${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.map)return n(J,{code:T.invalid_type,expected:p.map,received:J.parsedType}),q$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new C6(J,G,J.path,[Q,"key"])),value:W._parse(new C6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}GU.create=($,_,J)=>{return new GU({valueType:_,keyType:$,typeName:O$.ZodMap,...A$(J)})};class Q1 extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.set)return n(J,{code:T.invalid_type,expected:p.set,received:J.parsedType}),q$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)n(J,{code:T.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return q$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new C6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new Q1({...this._def,minSize:{value:$,message:W$.toString(_)}})}max($,_){return new Q1({...this._def,maxSize:{value:$,message:W$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}Q1.create=($,_)=>{return new Q1({valueType:$,minSize:null,maxSize:null,typeName:O$.ZodSet,...A$(_)})};class p2 extends f${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.function)return n(_,{code:T.invalid_type,expected:p.function,received:_.parsedType}),q$;function J(G,Y){return M9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,E9(),o2].filter((Q)=>!!Q),issueData:{code:T.invalid_arguments,argumentsError:Y}})}function U(G,Y){return M9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,E9(),o2].filter((Q)=>!!Q),issueData:{code:T.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof q1){let G=this;return u_(async function(...Y){let Q=new _6([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return u_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new _6([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new _6([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new p2({...this._def,args:X4.create($).rest(j0.create())})}returns($){return new p2({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new p2({args:$?$:X4.create([]).rest(j0.create()),returns:_||j0.create(),typeName:O$.ZodFunction,...A$(J)})}}class _J extends f${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}_J.create=($,_)=>{return new _J({getter:$,typeName:O$.ZodLazy,...A$(_)})};class JJ extends f${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return n(_,{received:_.data,code:T.invalid_literal,expected:this._def.value}),q$}return{status:"valid",value:$.data}}get value(){return this._def.value}}JJ.create=($,_)=>{return new JJ({value:$,typeName:O$.ZodLiteral,...A$(_)})};function yH($,_){return new L0({values:$,typeName:O$.ZodEnum,...A$(_)})}class L0 extends f${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return n(_,{expected:h$.joinValues(J),received:_.parsedType,code:T.invalid_type}),q$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return n(_,{received:_.data,code:T.invalid_enum_value,options:J}),q$}return u_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return L0.create($,{...this._def,..._})}exclude($,_=this._def){return L0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}L0.create=yH;class WJ extends f${_parse($){let _=h$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==p.string&&J.parsedType!==p.number){let U=h$.objectValues(_);return n(J,{expected:h$.joinValues(U),received:J.parsedType,code:T.invalid_type}),q$}if(!this._cache)this._cache=new Set(h$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=h$.objectValues(_);return n(J,{received:J.data,code:T.invalid_enum_value,options:U}),q$}return u_($.data)}get enum(){return this._def.values}}WJ.create=($,_)=>{return new WJ({values:$,typeName:O$.ZodNativeEnum,...A$(_)})};class q1 extends f${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.promise&&_.common.async===!1)return n(_,{code:T.invalid_type,expected:p.promise,received:_.parsedType}),q$;let J=_.parsedType===p.promise?_.data:Promise.resolve(_.data);return u_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}q1.create=($,_)=>{return new q1({type:$,typeName:O$.ZodPromise,...A$(_)})};class O6 extends f${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(n(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return q$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return q$;if(Y.status==="dirty")return r2(Y.value);if(_.value==="dirty")return r2(Y.value);return Y});else{if(_.value==="aborted")return q$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return q$;if(G.status==="dirty")return r2(G.value);if(_.value==="dirty")return r2(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return q$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return q$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!X1(X))return q$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!X1(X))return q$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});h$.assertNever(U)}}O6.create=($,_,J)=>{return new O6({schema:$,typeName:O$.ZodEffects,effect:_,...A$(J)})};O6.createWithPreprocess=($,_,J)=>{return new O6({schema:_,effect:{type:"preprocess",transform:$},typeName:O$.ZodEffects,...A$(J)})};class f6 extends f${_parse($){if(this._getType($)===p.undefined)return u_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}f6.create=($,_)=>{return new f6({innerType:$,typeName:O$.ZodOptional,...A$(_)})};class I4 extends f${_parse($){if(this._getType($)===p.null)return u_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}I4.create=($,_)=>{return new I4({innerType:$,typeName:O$.ZodNullable,...A$(_)})};class UJ extends f${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===p.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}UJ.create=($,_)=>{return new UJ({innerType:$,typeName:O$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...A$(_)})};class XJ extends f${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(JU(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new _6(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new _6(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}XJ.create=($,_)=>{return new XJ({innerType:$,typeName:O$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...A$(_)})};class YU extends f${_parse($){if(this._getType($)!==p.nan){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.nan,received:J.parsedType}),q$}return{status:"valid",value:$.data}}}YU.create=($)=>{return new YU({typeName:O$.ZodNaN,...A$($)})};var uk=Symbol("zod_brand");class b9 extends f${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class QU extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return q$;if(W.status==="dirty")return _.dirty(),r2(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return q$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new QU({in:$,out:_,typeName:O$.ZodPipeline})}}class GJ extends f${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(X1(U))U.value=Object.freeze(U.value);return U};return JU(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}GJ.create=($,_)=>{return new GJ({innerType:$,typeName:O$.ZodReadonly,...A$(_)})};function kH($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function hH($,_={},J){if($)return Y1.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=kH(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=kH(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return Y1.create()}var dk={object:L_.lazycreate},O$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(O$||(O$={}));var nk=($,_={message:`Input not instance of ${$.name}`})=>hH((J)=>J instanceof $,_),mH=k6.create,xH=D0.create,ck=YU.create,ik=O0.create,uH=t2.create,lk=G1.create,rk=WU.create,pk=a2.create,ok=s2.create,tk=Y1.create,ak=j0.create,sk=U4.create,ek=UU.create,$I=I6.create,_I=L_.create,JI=L_.strictCreate,WI=e2.create,UI=A9.create,XI=$J.create,GI=X4.create,YI=XU.create,QI=GU.create,qI=Q1.create,zI=p2.create,jI=_J.create,DI=JJ.create,OI=L0.create,LI=WJ.create,BI=q1.create,IH=O6.create,HI=f6.create,NI=I4.create,VI=O6.createWithPreprocess,RI=QU.create,KI=()=>mH().optional(),FI=()=>xH().optional(),EI=()=>uH().optional(),MI={string:($)=>k6.create({...$,coerce:!0}),number:($)=>D0.create({...$,coerce:!0}),boolean:($)=>t2.create({...$,coerce:!0}),bigint:($)=>O0.create({...$,coerce:!0}),date:($)=>G1.create({...$,coerce:!0})},AI=q$;var J$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},dH=j.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),J6=j.string().datetime(),N$=j.string().trim().min(1),f4=N$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),nH=j.string().regex(/^[a-fA-F0-9]{64}$/),cH=j.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),C4=j.record(j.unknown()),qJ=j.array(j.string().min(1)).default([]),z1=J6.nullable().optional(),bI=new Set(["succeeded","failed","cancelled","blocked","skipped"]),D1=j.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function o$($){return j.object({schema:j.literal($),id:j.string().min(1),createdAt:J6,updatedAt:z1,metadata:C4.optional()}).strict()}var Ot=j.object({schema:dH,id:j.string().min(1),createdAt:J6,updatedAt:z1,metadata:C4.optional()}).strict(),iH=j.enum(["agent","human","service","model","workflow","system"]),wI=o$(J$.actorRef).extend({kind:iH,name:j.string().min(1).optional(),provider:j.string().min(1).optional(),accountId:j.string().min(1).optional(),machineId:j.string().min(1).optional(),capabilities:j.array(j.string().min(1)).default([])}).strict(),G4=j.object({kind:iH,id:j.string().min(1),name:j.string().min(1).optional(),provider:j.string().min(1).optional(),accountId:j.string().min(1).optional(),machineId:j.string().min(1).optional()}).strict(),lH=j.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),gI=o$(J$.resourceRef).extend({kind:lH,name:j.string().min(1).optional(),uri:f4.optional(),externalId:N$.optional(),sourcePackage:N$.optional(),tags:qJ}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:j.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),I$=j.object({kind:lH,id:j.string().min(1),name:j.string().min(1).optional(),uri:f4.optional(),externalId:N$.optional(),sourcePackage:N$.optional(),tags:qJ}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:j.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),sY=j.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),kI=j.enum(["none","partial","full","unknown"]),II=o$(J$.evidenceRef).extend({kind:sY,uri:f4,sha256:nH.optional(),summary:j.string().min(1).optional(),contentType:j.string().min(1).optional(),sizeBytes:j.number().int().nonnegative().optional(),redaction:kI.default("unknown"),producer:G4.optional(),resourceRefs:j.array(I$).default([]),tags:qJ}).strict(),Y_=j.object({id:j.string().min(1),kind:sY.optional(),uri:f4.optional(),sha256:nH.optional(),summary:j.string().min(1).optional()}).strict(),qU=o$(J$.costEstimate).extend({currency:j.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:j.number().int().nonnegative(),provider:j.string().min(1).optional(),model:j.string().min(1).optional(),accountId:j.string().min(1).optional(),promptTokens:j.number().int().nonnegative().optional(),completionTokens:j.number().int().nonnegative().optional(),totalTokens:j.number().int().nonnegative().optional(),basis:j.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:j.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),fI=j.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),rH=o$(J$.decisionEnvelope).extend({decisionType:j.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:fI,actor:G4.optional(),traceId:j.string().min(1).optional(),inputHash:cH.optional(),policyBundleId:j.string().min(1).optional(),selected:j.array(I$).default([]),skipped:j.array(I$).default([]),reason:j.string().min(1),obligations:j.array(j.string().min(1)).default([]),redactions:j.array(j.string().min(1)).default([]),costEstimate:qU.optional(),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),CI=o$(J$.capabilityCard).extend({kind:j.enum(["model","tool","machine","agent","lane","connector","service"]),name:j.string().min(1),version:j.string().min(1).optional(),status:j.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:j.array(j.string().min(1)).default([]),limitations:j.array(j.string().min(1)).default([]),riskLevel:j.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:qU.optional(),evidenceRefs:j.array(Y_).default([])}).strict(),YJ=j.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),PI=j.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),TI=j.object({refName:N$,requiredForModes:j.array(YJ).min(1),allowedSecretInputs:j.array(j.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:N$,revocationCheck:j.boolean().default(!0)}).strict(),SI=j.object({operation:N$,supportedModes:j.array(YJ).min(1),sideEffectClass:PI,requiresApproval:j.boolean().default(!1),requiresIdempotencyKey:j.boolean().default(!1),requiresSandboxEvidence:j.boolean().default(!1),requiresRollbackOrRevocation:j.boolean().default(!1),rollbackOrRevocation:N$.optional(),noSideEffectSmoke:N$.optional(),reconciliation:N$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),ZI=j.object({providerId:N$,appId:N$,adapterId:N$,ownerPackage:N$,modes:j.array(YJ).min(1),defaultMode:YJ,credentialRequirements:j.array(TI).default([]),operations:j.array(SI).min(1),rateLimitPosture:N$,costPosture:N$.optional(),auditEvents:j.array(N$).default([]),redactionRules:j.array(N$).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:j.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),vI=j.object({appId:N$,repo:N$,priority:j.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:j.array(N$).min(1),firstOperations:j.array(N$).min(1),blockedUntil:j.array(N$).default([])}).strict(),yI=o$(J$.providerLiveModeStandard).extend({name:N$,version:N$,modes:j.array(YJ).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:j.array(N$).min(1),liveMutationGate:j.object({requiredMode:j.literal("live_mutating"),requiredChecks:j.array(N$).min(1),forbiddenBypassSignals:j.array(N$).min(1),disabledLiveSmoke:N$}).strict(),noSideEffectSmoke:j.object({requiredForModes:j.array(YJ).min(1),commandEvidence:j.array(N$).min(1),secretOutputScan:j.boolean().default(!0)}).strict(),credentialPolicy:j.object({acceptedInputs:j.array(j.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:j.literal(!1),missingCredentialBehavior:j.literal("fail_closed"),revocationCheckRequired:j.boolean().default(!0)}).strict(),operationCards:j.array(ZI).min(1),firstAdoptionTargets:j.array(vI).min(1),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:j.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),hI=j.object({id:j.string().min(1),title:j.string().min(1).optional(),summary:j.string().min(1),text:j.string().optional(),tokens:j.number().int().nonnegative().optional(),source:Y_,resourceRefs:j.array(I$).default([])}).strict(),pH=o$(J$.contextPack).extend({objective:j.string().min(1),budget:j.object({maxTokens:j.number().int().positive().optional(),maxBytes:j.number().int().positive().optional()}).strict().optional(),items:j.array(hI).default([]),citations:j.array(Y_).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),permissions:j.array(j.string().min(1)).default([]),redactions:j.array(j.string().min(1)).default([]),conflicts:j.array(j.string().min(1)).default([]),uncertainty:j.string().min(1).optional()}).strict(),g6=N$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),j1=j.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),mI=j.enum(["public","internal","private","sensitive"]),xI=j.enum(["draft","active","paused","archived"]),eY=j.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),oH=o$(J$.integrationRef).extend({kind:eY,name:j.string().min(1),projectId:j1.optional(),sourcePackage:N$.optional(),externalId:N$.optional(),uri:f4.optional(),enabled:j.boolean().default(!0),readOnly:j.boolean().default(!0),capabilities:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:I$.optional(),evidenceRefs:j.array(Y_).default([]),config:C4.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:j.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),uI=j.object({schemaRoot:g6.default(".hasna/project"),dashboardManifest:g6.default(".hasna/project/dashboard.render.json"),snapshotsDir:g6.default(".hasna/project/snapshots"),documentsDir:g6.default("documents"),reportsDir:g6.default("reports"),evidenceDir:g6.default(".hasna/project/evidence"),privateDir:g6.default(".hasna/project/private")}).strict(),dI=o$(J$.projectManifest).extend({projectId:j1,slug:j1,name:j.string().min(1),summary:j.string().min(1).optional(),status:xI.default("active"),classification:mI.default("private"),owner:G4.optional(),layout:uI.default({}),integrations:j.array(oH).default([]),renderManifests:j.array(I$).default([]),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),tags:qJ}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:j.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:j.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:j.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),nI=j.enum(["local","package","provider","url"]),$Q=j.object({id:j.string().min(1),kind:nI,specifier:j.string().min(1),path:g6.optional(),packageName:j.string().min(1).optional(),uri:f4.optional(),provider:eY.optional(),schemaId:dH.optional(),integrity:cH.optional(),resourceRef:I$.optional(),optional:j.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:j.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:j.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:j.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:j.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),cI=j.enum(["dashboard","canvas","panel","report","document","custom"]),iI=j.object({id:j.string().min(1),title:j.string().min(1),kind:cI,default:j.boolean().default(!1),entry:g6.optional(),imports:j.array($Q).default([]),panelRefs:j.array(I$).default([]),dataRefs:j.array(I$).default([]),layout:C4.optional()}).strict(),lI=o$(J$.renderManifest).extend({projectId:j1,name:j.string().min(1),version:j.string().min(1),manifestPath:g6.default(".hasna/project/dashboard.render.json"),renderer:j.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:j.array(iI).min(1),imports:j.array($Q).default([]),theme:C4.optional(),compatibility:j.object({minProjectsVersion:j.string().min(1).optional(),minContractsVersion:j.string().min(1).optional()}).strict().optional(),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:j.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),rI=j.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),pI=j.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),oI=j.object({id:j.string().min(1),label:j.string().min(1),value:j.union([j.string(),j.number(),j.boolean()]),unit:j.string().min(1).optional(),status:j.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:j.array(I$).default([])}).strict(),tI=j.object({id:j.string().min(1),title:j.string().min(1),summary:j.string().min(1).optional(),status:j.string().min(1).optional(),priority:j.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:J6.optional(),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),metadata:C4.optional()}).strict(),aI=j.object({renderer:j.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:j.string().min(1).optional(),entry:g6.optional(),imports:j.array($Q).default([]),spec:C4.default({})}).strict(),tH=o$(J$.projectPanel).extend({projectId:j1,provider:j.object({kind:eY,id:j.string().min(1),name:j.string().min(1).optional(),sourcePackage:N$.optional(),externalId:N$.optional()}).strict(),kind:pI,title:j.string().min(1),summary:j.string().min(1).optional(),state:rI.default("ready"),stateReason:j.string().min(1).optional(),generatedAt:J6,freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),metrics:j.array(oI).default([]),items:j.array(tI).default([]),actions:j.array(I$).default([]),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),renderFragment:aI.optional(),warnings:j.array(j.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:j.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:j.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),sI=o$(J$.projectSnapshot).extend({projectId:j1,generatedAt:J6,status:D1.default("unknown"),manifestRef:I$,renderManifestRef:I$.optional(),panels:j.array(tH).default([]),contextPacks:j.array(pH).default([]),proofBundleRefs:j.array(I$).default([]),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),warnings:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:j.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),aH=j.object({id:j.string().min(1),kind:j.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:j.boolean().default(!0),command:j.string().min(1).optional(),expected:j.string().min(1).optional(),timeoutMs:j.number().int().positive().optional(),resourceRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:j.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),eI=o$(J$.validationPlan).extend({objective:j.string().min(1),subject:I$.optional(),checks:j.array(aH).min(1),verifier:G4.optional(),requiredEvidenceKinds:j.array(sY).default([])}).strict(),$f=j.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),_f=j.enum(["draft","active","deprecated","archived"]),Jf=j.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Wf=j.object({key:j.string().regex(/^[A-Z][A-Z0-9_]*$/),description:j.string().min(1),required:j.boolean().default(!1),["secret"]:j.boolean().default(!1),group:j.string().min(1).optional(),default:j.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Uf=j.object({name:j.string().min(1),command:j.string().min(1),description:j.string().min(1).optional(),required:j.boolean().default(!1)}).strict(),Xf=j.object({packageManager:j.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:j.array(j.string().min(1)).default([]),requiredFiles:j.array(j.string().min(1)).default([]),requiredDirectories:j.array(j.string().min(1)).default([]),optionalDirectories:j.array(j.string().min(1)).default([])}).strict(),Gf=o$(J$.scaffoldManifest).extend({name:j.string().min(1),version:j.string().min(1),summary:j.string().min(1),type:$f,status:_f.default("draft"),capabilities:j.array(Jf).default([]),techStack:j.array(j.string().min(1)).default([]),tags:qJ,source:I$.optional(),output:Xf,env:j.array(Wf).default([]),scripts:j.array(Uf).default([]),validationChecks:j.array(aH).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:j.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),Yf=j.enum(["installed","failed","cancelled","partial","unknown"]),Qf=o$(J$.scaffoldInstallRecord).extend({scaffoldId:j.string().min(1),scaffoldVersion:j.string().min(1).optional(),manifestRef:I$.optional(),target:I$,status:Yf,installedAt:J6.optional(),installer:G4.optional(),packageManager:j.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:C4.optional(),generatedFiles:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),proofBundleRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:j.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),QJ=j.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),_Q=j.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),sH=j.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),qf=j.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),zf=N$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),jf=j.enum(["active","stub","deprecated","archived"]),Df=j.enum(["stable","beta","canary","internal"]),Of=j.object({transport:j.enum(["http","stdio"]).default("http"),bin:j.string().min(1).optional(),url:f4.optional()}).strict(),Lf=j.object({healthPath:j.string().min(1).default("/health"),port:j.number().int().positive().optional(),baseUrl:f4.optional()}).strict(),Bf=j.object({bins:j.array(j.string().min(1)).default([]),mcp:Of.optional(),http:Lf.optional()}).strict(),Hf=o$(J$.app).extend({appId:QJ,npmName:_Q,repoFolder:QJ,githubUrl:zf,projectSlug:j1,surfaces:Bf.default({}),lifecycle:jf,releaseChannel:Df.default("stable"),summary:j.string().min(1).optional(),tags:qJ}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:j.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),Nf=j.enum(["skill","ci","backfilled"]),Vf=o$(J$.release).extend({appId:QJ,package:_Q,version:sH,gitSha:qf,publishedAt:J6,publishPath:Nf,changelogRef:I$.optional(),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Rf=j.enum(["install","update","rollback","freeze-blocked"]),Kf=j.object({cliVersion:j.string().min(1).optional(),mcpHealth:j.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),Ff=o$(J$.rolloutRecord).extend({appId:QJ,package:_Q,version:sH,machine:N$,action:Rf,result:D1,verifiedBy:Kf.optional(),at:J6,evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:j.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),Ef=j.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),Mf=j.enum(["pending","queued","sent","failed","skipped","suppressed"]),Af=j.object({channel:Ef,status:Mf,deliveredAt:J6.optional(),detail:j.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:j.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),bf=o$(J$.announcement).extend({campaignId:N$,appId:QJ.optional(),releaseRef:I$.optional(),channels:j.array(Af).min(1),audienceRef:I$,sentAt:J6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:j.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:j.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),wf=j.enum(["tag","attribute","group"]),gf=j.enum(["eq","neq","in","not_in","exists","not_exists"]),fH=j.union([j.string(),j.number(),j.boolean()]),kf=j.object({kind:wf,key:j.string().min(1).optional(),op:gf.default("eq"),value:fH.optional(),values:j.array(fH).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:j.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),If=j.object({match:j.enum(["all","any"]).default("all"),predicates:j.array(kf).min(1)}).strict(),ff=j.enum(["opt_in","opt_out","transactional","none"]),Cf=o$(J$.audience).extend({audienceId:QJ,name:N$,definition:If,consentPolicy:ff,suppressionSyncedAt:z1}).strict(),lY=["@hasna/cloud","open-cloud"],Pf=j.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),Tf=j.object({id:j.string().min(1),provider:Pf,kind:j.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:j.string().min(1),region:j.string().min(1).optional(),accountId:j.string().min(1).optional(),uri:f4.optional(),machineScoped:j.boolean().default(!1)}).strict(),eH=o$(J$.appCloudManifest).extend({packageName:j.string().min(1),packageVersion:j.string().min(1).optional(),appId:j.string().min(1),repository:I$.optional(),storageMode:j.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:j.enum(["none","app_owned","external_service","local_cache"]),cloudResources:j.array(Tf).default([]),localCache:j.object({path:j.string().min(1).optional(),pullMode:j.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:j.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:j.array(j.string().min(1)).default([...lY]),dependencies:j.array(j.string().min(1)).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...lY,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:j.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of lY)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:j.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:j.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:j.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:j.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:j.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:j.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),$N=j.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),Sf=j.enum(["low","medium","high","critical"]),_N=j.object({id:j.string().min(1),kind:$N,severity:Sf,path:j.string().min(1).optional(),packageName:j.string().min(1).optional(),pattern:j.string().min(1),message:j.string().min(1),evidenceRefs:j.array(Y_).default([])}).strict(),Zf=j.object({id:j.string().min(1),kind:$N,status:D1,target:j.string().min(1),command:j.string().min(1).optional(),evidenceRefs:j.array(Y_).default([]),findings:j.array(_N).default([])}).strict(),vf=o$(J$.noCloudEvidencePack).extend({subject:I$,packageName:j.string().min(1).optional(),packageVersion:j.string().min(1).optional(),generatedBy:G4.optional(),scanMode:j.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:D1,verdict:j.enum(["passed","failed","warning","not_run"]),appCloudManifest:eH.optional(),checks:j.array(Zf).min(1),findings:j.array(_N).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),yf=j.object({checkId:j.string().min(1),status:D1,summary:j.string().min(1).optional(),startedAt:z1,finishedAt:z1,evidenceRefs:j.array(Y_).default([])}).strict(),hf=o$(J$.proofBundle).extend({subject:I$,validationPlanRef:I$.optional(),status:D1,verdict:j.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:j.array(yf).default([]),verifier:G4.optional(),evidenceRefs:j.array(Y_).default([]),residualRisks:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),mf=o$(J$.workRun).extend({objective:j.string().min(1),status:D1,actor:G4,traceId:j.string().min(1).optional(),startedAt:z1,finishedAt:z1,constraints:j.array(j.string().min(1)).default([]),resourceRefs:j.array(I$).default([]),decisions:j.array(rH).default([]),costEstimates:j.array(qU).default([]),evidenceRefs:j.array(Y_).default([]),validationPlanRefs:j.array(I$).default([]),proofBundleRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),xf=j.object({id:j.string().min(1),at:J6,kind:j.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:j.string().min(1),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),costEstimate:qU.optional()}).strict(),uf=o$(J$.agentTrajectory).extend({actor:G4,workRunRef:I$.optional(),events:j.array(xf).default([]),outcome:j.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:I$.optional()}).strict(),df="v1",nf=j.enum(["library","cli-with-store","service","saas"]),cf=["local","self-hosted","cloud"],JN=j.enum(cf),lf=j.enum(["supported","deferred","unsupported"]),rf=j.enum(["none","local-only","api-key","session","service-token","custom"]),rY=j.object({method:j.enum(["GET","POST","PUT","PATCH","DELETE"]),path:j.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:j.boolean().default(!1),description:j.string().min(1).optional()}).strict(),pf=j.object({id:j.string().min(1),kind:j.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:j.boolean().default(!0),command:j.string().min(1).optional(),evidenceRef:Y_.optional(),status:j.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:j.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:j.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),of=j.object({name:j.string().min(1),status:lf,bin:j.string().min(1).optional(),mcpBin:j.string().min(1).optional(),authMode:rf,deploymentModes:j.array(JN).min(1),health:rY.optional(),readiness:rY.optional(),version:rY.optional(),apiBasePath:j.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:j.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:j.string().min(1).optional(),readinessGates:j.array(pf).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:j.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:j.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:j.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:j.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),tf=["local","cloud"],WN=j.enum(tf);var af=j.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),sf=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function ef($){return sf.map((_)=>`${$}${_}`)}function CH($){return`hasna/oss/${$}/database-url`}var $C=j.object({mode:WN,envPrefix:j.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:j.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:j.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:j.string().min(1).optional()}).strict(),_C=j.object({$schema:j.string().min(1).optional(),schema:j.literal(J$.serviceContract),name:af,class:nf,contractVersion:j.literal(df),kitVersion:j.string().min(1),description:j.string().min(1).optional(),bins:j.array(j.string().min(1)).default([]),storage:$C.optional(),deploymentModes:j.array(JN).default(["local"]),serviceSurfaces:j.array(of).default([]),metadata:C4.optional()}).strict().superRefine(($,_)=>{let J=new Set(ef($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:j.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:j.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:j.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==CH($.name))_.addIssue({code:j.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${CH($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:j.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:j.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:j.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:j.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:j.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:j.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),Lt=j.object({status:j.enum(["ok","degraded","unavailable"]),version:j.string().min(1),mode:WN}).strict(),Bt=j.object({ready:j.boolean(),reason:j.string().min(1).optional()}).strict(),Ht=j.object({version:j.string().min(1)}).strict(),JC=j.enum(["info","notice","breaking","critical"]),WC=j.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),UC=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],XC=j.enum(UC);var GC=j.enum(["fleet","package","machine"]),UN=o$(J$.commsEventEnvelope).extend({type:WC,severity:JC,scope:GC,summary:j.string().min(1).optional(),source:G4.optional(),affected_packages:j.array(N$).default([]),affected_machines:j.array(N$).default([]),action_required:j.boolean().default(!1),ack_by:J6.optional(),dedupe_key:N$,resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:j.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),YC=j.enum(["fleet","package","product","loop-lane","initiative","personal"]),QC=j.enum(["quiet","work","firehose"]),qC=N$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),zC=o$(J$.commsChannelMetadata).extend({class:YC,noise:QC.optional(),owner:N$.optional(),until:qC.optional(),successor:N$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:j.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:j.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),PH={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},jC=o$(J$.commsMessageMetadata).extend({tag:XC,envelope:UN}).strict().superRefine(($,_)=>{let J=PH[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:j.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:j.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(PH))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:j.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var Nt={[J$.actorRef]:wI,[J$.resourceRef]:gI,[J$.evidenceRef]:II,[J$.workRun]:mf,[J$.decisionEnvelope]:rH,[J$.costEstimate]:qU,[J$.capabilityCard]:CI,[J$.providerLiveModeStandard]:yI,[J$.contextPack]:pH,[J$.integrationRef]:oH,[J$.projectManifest]:dI,[J$.projectPanel]:tH,[J$.projectSnapshot]:sI,[J$.renderManifest]:lI,[J$.agentTrajectory]:uf,[J$.validationPlan]:eI,[J$.proofBundle]:hf,[J$.scaffoldManifest]:Gf,[J$.scaffoldInstallRecord]:Qf,[J$.appCloudManifest]:eH,[J$.noCloudEvidencePack]:vf,[J$.serviceContract]:_C,[J$.commsEventEnvelope]:UN,[J$.commsChannelMetadata]:zC,[J$.commsMessageMetadata]:jC,[J$.app]:Hf,[J$.release]:Vf,[J$.rolloutRecord]:Ff,[J$.announcement]:bf,[J$.audience]:Cf};function DC($){return $.toUpperCase().replace(/-/g,"_")}function XN($){let _=DC($);return{modeKeys:[`HASNA_${_}_STORAGE_MODE`,`HASNA_${_}_MODE`,`${_}_STORAGE_MODE`,`${_}_MODE`],apiUrlKeys:[`HASNA_${_}_API_URL`,`${_}_API_URL`],apiKeyKeys:[`HASNA_${_}_API_KEY`,`${_}_API_KEY`]}}var OC=Object.defineProperty,LC=($)=>$;function BC($,_){this[$]=LC.bind(null,_)}var HC=($,_)=>{for(var J in _)OC($,J,{get:_[J],enumerable:!0,configurable:!0,set:BC.bind(_,J)})},D={};HC(D,{void:()=>$P,util:()=>m$,unknown:()=>sC,union:()=>UP,undefined:()=>oC,tuple:()=>YP,transformer:()=>QN,symbol:()=>pC,string:()=>VN,strictObject:()=>WP,setErrorMap:()=>RC,set:()=>zP,record:()=>QP,quotelessJson:()=>NC,promise:()=>HP,preprocess:()=>RP,pipeline:()=>KP,ostring:()=>FP,optional:()=>NP,onumber:()=>EP,oboolean:()=>MP,objectUtil:()=>XQ,object:()=>JP,number:()=>RN,nullable:()=>VP,null:()=>tC,never:()=>eC,nativeEnum:()=>BP,nan:()=>iC,map:()=>qP,makeIssue:()=>g9,literal:()=>OP,lazy:()=>DP,late:()=>nC,isValid:()=>O1,isDirty:()=>YQ,isAsync:()=>zU,isAborted:()=>GQ,intersection:()=>GP,instanceof:()=>cC,getParsedType:()=>T4,getErrorMap:()=>w9,function:()=>jP,enum:()=>LP,effect:()=>QN,discriminatedUnion:()=>XP,defaultErrorMap:()=>OJ,datetimeRegex:()=>BN,date:()=>rC,custom:()=>NN,coerce:()=>AP,boolean:()=>KN,bigint:()=>lC,array:()=>_P,any:()=>aC,addIssueToContext:()=>c,ZodVoid:()=>DU,ZodUnknown:()=>B0,ZodUnion:()=>NJ,ZodUndefined:()=>BJ,ZodType:()=>P$,ZodTuple:()=>Q4,ZodTransformer:()=>L6,ZodSymbol:()=>jU,ZodString:()=>T6,ZodSet:()=>H1,ZodSchema:()=>P$,ZodRecord:()=>OU,ZodReadonly:()=>AJ,ZodPromise:()=>N1,ZodPipeline:()=>HU,ZodParsedType:()=>o,ZodOptional:()=>Z6,ZodObject:()=>B_,ZodNumber:()=>H0,ZodNullable:()=>S4,ZodNull:()=>HJ,ZodNever:()=>Y4,ZodNativeEnum:()=>FJ,ZodNaN:()=>BU,ZodMap:()=>LU,ZodLiteral:()=>KJ,ZodLazy:()=>RJ,ZodIssueCode:()=>S,ZodIntersection:()=>VJ,ZodFunction:()=>DJ,ZodFirstPartyTypeKind:()=>L$,ZodError:()=>W6,ZodEnum:()=>V0,ZodEffects:()=>L6,ZodDiscriminatedUnion:()=>k9,ZodDefault:()=>EJ,ZodDate:()=>L1,ZodCatch:()=>MJ,ZodBranded:()=>I9,ZodBoolean:()=>LJ,ZodBigInt:()=>N0,ZodArray:()=>S6,ZodAny:()=>B1,Schema:()=>P$,ParseStatus:()=>P_,OK:()=>d_,NEVER:()=>bP,INVALID:()=>z$,EMPTY_PATH:()=>KC,DIRTY:()=>jJ,BRAND:()=>dC});var m$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(m$||(m$={}));var XQ;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(XQ||(XQ={}));var o=m$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T4=($)=>{switch(typeof $){case"undefined":return o.undefined;case"string":return o.string;case"number":return Number.isNaN($)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":if(Array.isArray($))return o.array;if($===null)return o.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return o.promise;if(typeof Map<"u"&&$ instanceof Map)return o.map;if(typeof Set<"u"&&$ instanceof Set)return o.set;if(typeof Date<"u"&&$ instanceof Date)return o.date;return o.object;default:return o.unknown}},S=m$.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),NC=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class W6 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}W6.create=($)=>{return new W6($)};var VC=($,_)=>{let J;switch($.code){case S.invalid_type:if($.received===o.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case S.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,m$.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:J=`Unrecognized key(s) in object: ${m$.joinValues($.keys,", ")}`;break;case S.invalid_union:J="Invalid input";break;case S.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${m$.joinValues($.options)}`;break;case S.invalid_enum_value:J=`Invalid enum value. Expected ${m$.joinValues($.options)}, received '${$.received}'`;break;case S.invalid_arguments:J="Invalid function arguments";break;case S.invalid_return_type:J="Invalid function return type";break;case S.invalid_date:J="Invalid date";break;case S.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else m$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case S.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case S.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case S.custom:J="Invalid input";break;case S.invalid_intersection_types:J="Intersection results could not be merged";break;case S.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case S.not_finite:J="Number must be finite";break;default:J=_.defaultError,m$.assertNever($)}return{message:J}},OJ=VC,DN=OJ;function RC($){DN=$}function w9(){return DN}var g9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},KC=[];function c($,_){let J=w9(),U=g9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===OJ?void 0:OJ].filter((W)=>!!W)});$.common.issues.push(U)}class P_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return z$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return P_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return z$;if(X.status==="aborted")return z$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var z$=Object.freeze({status:"aborted"}),jJ=($)=>({status:"dirty",value:$}),d_=($)=>({status:"valid",value:$}),GQ=($)=>$.status==="aborted",YQ=($)=>$.status==="dirty",O1=($)=>$.status==="valid",zU=($)=>typeof Promise<"u"&&$ instanceof Promise,X$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(X$||(X$={}));class v6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var GN=($,_)=>{if(O1(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new W6($.common.issues);return this._error=J,this._error}}}};function b$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class P${get description(){return this._def.description}_getType($){return T4($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:T4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new P_,ctx:{common:$.parent.common,data:$.data,parsedType:T4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(zU(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T4($)},U=this._parseSync({data:$,path:J.path,parent:J});return GN(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T4($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return O1(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>O1(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T4($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(zU(U)?U:Promise.resolve(U));return GN(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:S.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new L6({schema:this,typeName:L$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(_)=>this["~validate"](_)}}optional(){return Z6.create(this,this._def)}nullable(){return S4.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return S6.create(this)}promise(){return N1.create(this,this._def)}or($){return NJ.create([this,$],this._def)}and($){return VJ.create(this,$,this._def)}transform($){return new L6({...b$(this._def),schema:this,typeName:L$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new EJ({...b$(this._def),innerType:this,defaultValue:_,typeName:L$.ZodDefault})}brand(){return new I9({typeName:L$.ZodBranded,type:this,...b$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new MJ({...b$(this._def),innerType:this,catchValue:_,typeName:L$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return HU.create(this,$)}readonly(){return AJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var FC=/^c[^\s-]{8,}$/i,EC=/^[0-9a-z]+$/,MC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,AC=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,bC=/^[a-z0-9_-]{21}$/i,wC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,gC=/^[-+]?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)?)??$/,kC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,IC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",JQ,fC=/^(?:(?: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])$/,CC=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,PC=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,TC=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,SC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ZC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ON="((\\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])))",vC=new RegExp(`^${ON}$`);function LN($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function yC($){return new RegExp(`^${LN($)}$`)}function BN($){let _=`${ON}T${LN($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function hC($,_){if((_==="v4"||!_)&&fC.test($))return!0;if((_==="v6"||!_)&&PC.test($))return!0;return!1}function mC($,_){if(!wC.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function xC($,_){if((_==="v4"||!_)&&CC.test($))return!0;if((_==="v6"||!_)&&TC.test($))return!0;return!1}class T6 extends P${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==o.string){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.string,received:W.parsedType}),z$}let J=new P_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),c(U,{code:S.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:S.invalid_string,...X$.errToObj(J)})}_addCheck($){return new T6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...X$.errToObj($)})}url($){return this._addCheck({kind:"url",...X$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...X$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...X$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...X$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...X$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...X$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...X$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...X$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...X$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...X$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...X$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...X$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...X$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...X$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...X$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...X$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...X$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...X$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...X$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...X$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...X$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...X$.errToObj(_)})}nonempty($){return this.min(1,X$.errToObj($))}trim(){return new T6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}T6.create=($)=>{return new T6({checks:[],typeName:L$.ZodString,coerce:$?.coerce??!1,...b$($)})};function uC($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class H0 extends P${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==o.number){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.number,received:W.parsedType}),z$}let J=void 0,U=new P_;for(let W of this._def.checks)if(W.kind==="int"){if(!m$.isInteger($.data))J=this._getOrReturnCtx($,J),c(J,{code:S.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),c(J,{code:S.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(uC($.data,W.value)!==0)J=this._getOrReturnCtx($,J),c(J,{code:S.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),c(J,{code:S.not_finite,message:W.message}),U.dirty()}else m$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,X$.toString(_))}gt($,_){return this.setLimit("min",$,!1,X$.toString(_))}lte($,_){return this.setLimit("max",$,!0,X$.toString(_))}lt($,_){return this.setLimit("max",$,!1,X$.toString(_))}setLimit($,_,J,U){return new H0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:X$.toString(U)}]})}_addCheck($){return new H0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:X$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:X$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:X$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&m$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}H0.create=($)=>{return new H0({checks:[],typeName:L$.ZodNumber,coerce:$?.coerce||!1,...b$($)})};class N0 extends P${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==o.bigint)return this._getInvalidInput($);let J=void 0,U=new P_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),c(J,{code:S.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),c(J,{code:S.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else m$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return c(_,{code:S.invalid_type,expected:o.bigint,received:_.parsedType}),z$}gte($,_){return this.setLimit("min",$,!0,X$.toString(_))}gt($,_){return this.setLimit("min",$,!1,X$.toString(_))}lte($,_){return this.setLimit("max",$,!0,X$.toString(_))}lt($,_){return this.setLimit("max",$,!1,X$.toString(_))}setLimit($,_,J,U){return new N0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:X$.toString(U)}]})}_addCheck($){return new N0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:X$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}N0.create=($)=>{return new N0({checks:[],typeName:L$.ZodBigInt,coerce:$?.coerce??!1,...b$($)})};class LJ extends P${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==o.boolean){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.boolean,received:J.parsedType}),z$}return d_($.data)}}LJ.create=($)=>{return new LJ({typeName:L$.ZodBoolean,coerce:$?.coerce||!1,...b$($)})};class L1 extends P${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==o.date){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.date,received:W.parsedType}),z$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_date}),z$}let J=new P_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),c(U,{code:S.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else m$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new L1({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:X$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:X$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}L1.create=($)=>{return new L1({checks:[],coerce:$?.coerce||!1,typeName:L$.ZodDate,...b$($)})};class jU extends P${_parse($){if(this._getType($)!==o.symbol){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.symbol,received:J.parsedType}),z$}return d_($.data)}}jU.create=($)=>{return new jU({typeName:L$.ZodSymbol,...b$($)})};class BJ extends P${_parse($){if(this._getType($)!==o.undefined){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.undefined,received:J.parsedType}),z$}return d_($.data)}}BJ.create=($)=>{return new BJ({typeName:L$.ZodUndefined,...b$($)})};class HJ extends P${_parse($){if(this._getType($)!==o.null){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.null,received:J.parsedType}),z$}return d_($.data)}}HJ.create=($)=>{return new HJ({typeName:L$.ZodNull,...b$($)})};class B1 extends P${constructor(){super(...arguments);this._any=!0}_parse($){return d_($.data)}}B1.create=($)=>{return new B1({typeName:L$.ZodAny,...b$($)})};class B0 extends P${constructor(){super(...arguments);this._unknown=!0}_parse($){return d_($.data)}}B0.create=($)=>{return new B0({typeName:L$.ZodUnknown,...b$($)})};class Y4 extends P${_parse($){let _=this._getOrReturnCtx($);return c(_,{code:S.invalid_type,expected:o.never,received:_.parsedType}),z$}}Y4.create=($)=>{return new Y4({typeName:L$.ZodNever,...b$($)})};class DU extends P${_parse($){if(this._getType($)!==o.undefined){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.void,received:J.parsedType}),z$}return d_($.data)}}DU.create=($)=>{return new DU({typeName:L$.ZodVoid,...b$($)})};class S6 extends P${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==o.array)return c(_,{code:S.invalid_type,expected:o.array,received:_.parsedType}),z$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)c(_,{code:S.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new v6(_,X,_.path,G))})).then((X)=>{return P_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new v6(_,X,_.path,G))});return P_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new S6({...this._def,minLength:{value:$,message:X$.toString(_)}})}max($,_){return new S6({...this._def,maxLength:{value:$,message:X$.toString(_)}})}length($,_){return new S6({...this._def,exactLength:{value:$,message:X$.toString(_)}})}nonempty($){return this.min(1,$)}}S6.create=($,_)=>{return new S6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:L$.ZodArray,...b$(_)})};function zJ($){if($ instanceof B_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=Z6.create(zJ(U))}return new B_({...$._def,shape:()=>_})}else if($ instanceof S6)return new S6({...$._def,type:zJ($.element)});else if($ instanceof Z6)return Z6.create(zJ($.unwrap()));else if($ instanceof S4)return S4.create(zJ($.unwrap()));else if($ instanceof Q4)return Q4.create($.items.map((_)=>zJ(_)));else return $}class B_ extends P${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=m$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==o.object){let Q=this._getOrReturnCtx($);return c(Q,{code:S.invalid_type,expected:o.object,received:Q.parsedType}),z$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof Y4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new v6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof Y4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)c(U,{code:S.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new v6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return P_.mergeObjectSync(J,Q)});else return P_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return X$.errToObj,new B_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:X$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new B_({...this._def,unknownKeys:"strip"})}passthrough(){return new B_({...this._def,unknownKeys:"passthrough"})}extend($){return new B_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new B_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:L$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new B_({...this._def,catchall:$})}pick($){let _={};for(let J of m$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new B_({...this._def,shape:()=>_})}omit($){let _={};for(let J of m$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new B_({...this._def,shape:()=>_})}deepPartial(){return zJ(this)}partial($){let _={};for(let J of m$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new B_({...this._def,shape:()=>_})}required($){let _={};for(let J of m$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof Z6)W=W._def.innerType;_[J]=W}return new B_({...this._def,shape:()=>_})}keyof(){return HN(m$.objectKeys(this.shape))}}B_.create=($,_)=>{return new B_({shape:()=>$,unknownKeys:"strip",catchall:Y4.create(),typeName:L$.ZodObject,...b$(_)})};B_.strictCreate=($,_)=>{return new B_({shape:()=>$,unknownKeys:"strict",catchall:Y4.create(),typeName:L$.ZodObject,...b$(_)})};B_.lazycreate=($,_)=>{return new B_({shape:$,unknownKeys:"strip",catchall:Y4.create(),typeName:L$.ZodObject,...b$(_)})};class NJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new W6(G.ctx.common.issues));return c(_,{code:S.invalid_union,unionErrors:X}),z$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new W6(Y));return c(_,{code:S.invalid_union,unionErrors:G}),z$}}get options(){return this._def.options}}NJ.create=($,_)=>{return new NJ({options:$,typeName:L$.ZodUnion,...b$(_)})};var P4=($)=>{if($ instanceof RJ)return P4($.schema);else if($ instanceof L6)return P4($.innerType());else if($ instanceof KJ)return[$.value];else if($ instanceof V0)return $.options;else if($ instanceof FJ)return m$.objectValues($.enum);else if($ instanceof EJ)return P4($._def.innerType);else if($ instanceof BJ)return[void 0];else if($ instanceof HJ)return[null];else if($ instanceof Z6)return[void 0,...P4($.unwrap())];else if($ instanceof S4)return[null,...P4($.unwrap())];else if($ instanceof I9)return P4($.unwrap());else if($ instanceof AJ)return P4($.unwrap());else if($ instanceof MJ)return P4($._def.innerType);else return[]};class k9 extends P${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.object)return c(_,{code:S.invalid_type,expected:o.object,received:_.parsedType}),z$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return c(_,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),z$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=P4(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new k9({typeName:L$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...b$(J)})}}function QQ($,_){let J=T4($),U=T4(_);if($===_)return{valid:!0,data:$};else if(J===o.object&&U===o.object){let W=m$.objectKeys(_),X=m$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=QQ($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===o.array&&U===o.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=QQ(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===o.date&&U===o.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class VJ extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(GQ(W)||GQ(X))return z$;let G=QQ(W.value,X.value);if(!G.valid)return c(J,{code:S.invalid_intersection_types}),z$;if(YQ(W)||YQ(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}VJ.create=($,_,J)=>{return new VJ({left:$,right:_,typeName:L$.ZodIntersection,...b$(J)})};class Q4 extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.array)return c(J,{code:S.invalid_type,expected:o.array,received:J.parsedType}),z$;if(J.data.lengththis._def.items.length)c(J,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new v6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return P_.mergeArray(_,X)});else return P_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new Q4({...this._def,rest:$})}}Q4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Q4({items:$,typeName:L$.ZodTuple,rest:null,...b$(_)})};class OU extends P${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.object)return c(J,{code:S.invalid_type,expected:o.object,received:J.parsedType}),z$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new v6(J,G,J.path,G)),value:X._parse(new v6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return P_.mergeObjectAsync(_,U);else return P_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof P$)return new OU({keyType:$,valueType:_,typeName:L$.ZodRecord,...b$(J)});return new OU({keyType:T6.create(),valueType:$,typeName:L$.ZodRecord,...b$(_)})}}class LU extends P${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.map)return c(J,{code:S.invalid_type,expected:o.map,received:J.parsedType}),z$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new v6(J,G,J.path,[Q,"key"])),value:W._parse(new v6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return z$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return z$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}LU.create=($,_,J)=>{return new LU({valueType:_,keyType:$,typeName:L$.ZodMap,...b$(J)})};class H1 extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.set)return c(J,{code:S.invalid_type,expected:o.set,received:J.parsedType}),z$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)c(J,{code:S.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return z$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new v6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new H1({...this._def,minSize:{value:$,message:X$.toString(_)}})}max($,_){return new H1({...this._def,maxSize:{value:$,message:X$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}H1.create=($,_)=>{return new H1({valueType:$,minSize:null,maxSize:null,typeName:L$.ZodSet,...b$(_)})};class DJ extends P${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.function)return c(_,{code:S.invalid_type,expected:o.function,received:_.parsedType}),z$;function J(G,Y){return g9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,w9(),OJ].filter((Q)=>!!Q),issueData:{code:S.invalid_arguments,argumentsError:Y}})}function U(G,Y){return g9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,w9(),OJ].filter((Q)=>!!Q),issueData:{code:S.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof N1){let G=this;return d_(async function(...Y){let Q=new W6([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return d_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new W6([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new W6([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new DJ({...this._def,args:Q4.create($).rest(B0.create())})}returns($){return new DJ({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new DJ({args:$?$:Q4.create([]).rest(B0.create()),returns:_||B0.create(),typeName:L$.ZodFunction,...b$(J)})}}class RJ extends P${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}RJ.create=($,_)=>{return new RJ({getter:$,typeName:L$.ZodLazy,...b$(_)})};class KJ extends P${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return c(_,{received:_.data,code:S.invalid_literal,expected:this._def.value}),z$}return{status:"valid",value:$.data}}get value(){return this._def.value}}KJ.create=($,_)=>{return new KJ({value:$,typeName:L$.ZodLiteral,...b$(_)})};function HN($,_){return new V0({values:$,typeName:L$.ZodEnum,...b$(_)})}class V0 extends P${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return c(_,{expected:m$.joinValues(J),received:_.parsedType,code:S.invalid_type}),z$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return c(_,{received:_.data,code:S.invalid_enum_value,options:J}),z$}return d_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return V0.create($,{...this._def,..._})}exclude($,_=this._def){return V0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}V0.create=HN;class FJ extends P${_parse($){let _=m$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==o.string&&J.parsedType!==o.number){let U=m$.objectValues(_);return c(J,{expected:m$.joinValues(U),received:J.parsedType,code:S.invalid_type}),z$}if(!this._cache)this._cache=new Set(m$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=m$.objectValues(_);return c(J,{received:J.data,code:S.invalid_enum_value,options:U}),z$}return d_($.data)}get enum(){return this._def.values}}FJ.create=($,_)=>{return new FJ({values:$,typeName:L$.ZodNativeEnum,...b$(_)})};class N1 extends P${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.promise&&_.common.async===!1)return c(_,{code:S.invalid_type,expected:o.promise,received:_.parsedType}),z$;let J=_.parsedType===o.promise?_.data:Promise.resolve(_.data);return d_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}N1.create=($,_)=>{return new N1({type:$,typeName:L$.ZodPromise,...b$(_)})};class L6 extends P${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(c(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return z$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return z$;if(Y.status==="dirty")return jJ(Y.value);if(_.value==="dirty")return jJ(Y.value);return Y});else{if(_.value==="aborted")return z$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return z$;if(G.status==="dirty")return jJ(G.value);if(_.value==="dirty")return jJ(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return z$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return z$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!O1(X))return z$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!O1(X))return z$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});m$.assertNever(U)}}L6.create=($,_,J)=>{return new L6({schema:$,typeName:L$.ZodEffects,effect:_,...b$(J)})};L6.createWithPreprocess=($,_,J)=>{return new L6({schema:_,effect:{type:"preprocess",transform:$},typeName:L$.ZodEffects,...b$(J)})};class Z6 extends P${_parse($){if(this._getType($)===o.undefined)return d_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}Z6.create=($,_)=>{return new Z6({innerType:$,typeName:L$.ZodOptional,...b$(_)})};class S4 extends P${_parse($){if(this._getType($)===o.null)return d_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}S4.create=($,_)=>{return new S4({innerType:$,typeName:L$.ZodNullable,...b$(_)})};class EJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===o.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}EJ.create=($,_)=>{return new EJ({innerType:$,typeName:L$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...b$(_)})};class MJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(zU(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new W6(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new W6(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}MJ.create=($,_)=>{return new MJ({innerType:$,typeName:L$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...b$(_)})};class BU extends P${_parse($){if(this._getType($)!==o.nan){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.nan,received:J.parsedType}),z$}return{status:"valid",value:$.data}}}BU.create=($)=>{return new BU({typeName:L$.ZodNaN,...b$($)})};var dC=Symbol("zod_brand");class I9 extends P${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class HU extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return z$;if(W.status==="dirty")return _.dirty(),jJ(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return z$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new HU({in:$,out:_,typeName:L$.ZodPipeline})}}class AJ extends P${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(O1(U))U.value=Object.freeze(U.value);return U};return zU(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}AJ.create=($,_)=>{return new AJ({innerType:$,typeName:L$.ZodReadonly,...b$(_)})};function YN($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function NN($,_={},J){if($)return B1.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=YN(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=YN(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return B1.create()}var nC={object:B_.lazycreate},L$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(L$||(L$={}));var cC=($,_={message:`Input not instance of ${$.name}`})=>NN((J)=>J instanceof $,_),VN=T6.create,RN=H0.create,iC=BU.create,lC=N0.create,KN=LJ.create,rC=L1.create,pC=jU.create,oC=BJ.create,tC=HJ.create,aC=B1.create,sC=B0.create,eC=Y4.create,$P=DU.create,_P=S6.create,JP=B_.create,WP=B_.strictCreate,UP=NJ.create,XP=k9.create,GP=VJ.create,YP=Q4.create,QP=OU.create,qP=LU.create,zP=H1.create,jP=DJ.create,DP=RJ.create,OP=KJ.create,LP=V0.create,BP=FJ.create,HP=N1.create,QN=L6.create,NP=Z6.create,VP=S4.create,RP=L6.createWithPreprocess,KP=HU.create,FP=()=>VN().optional(),EP=()=>RN().optional(),MP=()=>KN().optional(),AP={string:($)=>T6.create({...$,coerce:!0}),number:($)=>H0.create({...$,coerce:!0}),boolean:($)=>LJ.create({...$,coerce:!0}),bigint:($)=>N0.create({...$,coerce:!0}),date:($)=>L1.create({...$,coerce:!0})},bP=z$;var U$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},FN=D.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),U6=D.string().datetime(),V$=D.string().trim().min(1),Z4=V$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),EN=D.string().regex(/^[a-fA-F0-9]{64}$/),MN=D.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),v4=D.record(D.unknown()),gJ=D.array(D.string().min(1)).default([]),V1=U6.nullable().optional(),wP=new Set(["succeeded","failed","cancelled","blocked","skipped"]),K1=D.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function t$($){return D.object({schema:D.literal($),id:D.string().min(1),createdAt:U6,updatedAt:V1,metadata:v4.optional()}).strict()}var Rt=D.object({schema:FN,id:D.string().min(1),createdAt:U6,updatedAt:V1,metadata:v4.optional()}).strict(),AN=D.enum(["agent","human","service","model","workflow","system"]),gP=t$(U$.actorRef).extend({kind:AN,name:D.string().min(1).optional(),provider:D.string().min(1).optional(),accountId:D.string().min(1).optional(),machineId:D.string().min(1).optional(),capabilities:D.array(D.string().min(1)).default([])}).strict(),q4=D.object({kind:AN,id:D.string().min(1),name:D.string().min(1).optional(),provider:D.string().min(1).optional(),accountId:D.string().min(1).optional(),machineId:D.string().min(1).optional()}).strict(),bN=D.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),kP=t$(U$.resourceRef).extend({kind:bN,name:D.string().min(1).optional(),uri:Z4.optional(),externalId:V$.optional(),sourcePackage:V$.optional(),tags:gJ}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:D.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),C$=D.object({kind:bN,id:D.string().min(1),name:D.string().min(1).optional(),uri:Z4.optional(),externalId:V$.optional(),sourcePackage:V$.optional(),tags:gJ}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:D.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),qQ=D.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),IP=D.enum(["none","partial","full","unknown"]),fP=t$(U$.evidenceRef).extend({kind:qQ,uri:Z4,sha256:EN.optional(),summary:D.string().min(1).optional(),contentType:D.string().min(1).optional(),sizeBytes:D.number().int().nonnegative().optional(),redaction:IP.default("unknown"),producer:q4.optional(),resourceRefs:D.array(C$).default([]),tags:gJ}).strict(),Q_=D.object({id:D.string().min(1),kind:qQ.optional(),uri:Z4.optional(),sha256:EN.optional(),summary:D.string().min(1).optional()}).strict(),NU=t$(U$.costEstimate).extend({currency:D.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:D.number().int().nonnegative(),provider:D.string().min(1).optional(),model:D.string().min(1).optional(),accountId:D.string().min(1).optional(),promptTokens:D.number().int().nonnegative().optional(),completionTokens:D.number().int().nonnegative().optional(),totalTokens:D.number().int().nonnegative().optional(),basis:D.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:D.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),CP=D.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),wN=t$(U$.decisionEnvelope).extend({decisionType:D.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:CP,actor:q4.optional(),traceId:D.string().min(1).optional(),inputHash:MN.optional(),policyBundleId:D.string().min(1).optional(),selected:D.array(C$).default([]),skipped:D.array(C$).default([]),reason:D.string().min(1),obligations:D.array(D.string().min(1)).default([]),redactions:D.array(D.string().min(1)).default([]),costEstimate:NU.optional(),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),PP=t$(U$.capabilityCard).extend({kind:D.enum(["model","tool","machine","agent","lane","connector","service"]),name:D.string().min(1),version:D.string().min(1).optional(),status:D.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:D.array(D.string().min(1)).default([]),limitations:D.array(D.string().min(1)).default([]),riskLevel:D.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:NU.optional(),evidenceRefs:D.array(Q_).default([])}).strict(),bJ=D.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),TP=D.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),SP=D.object({refName:V$,requiredForModes:D.array(bJ).min(1),allowedSecretInputs:D.array(D.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:V$,revocationCheck:D.boolean().default(!0)}).strict(),ZP=D.object({operation:V$,supportedModes:D.array(bJ).min(1),sideEffectClass:TP,requiresApproval:D.boolean().default(!1),requiresIdempotencyKey:D.boolean().default(!1),requiresSandboxEvidence:D.boolean().default(!1),requiresRollbackOrRevocation:D.boolean().default(!1),rollbackOrRevocation:V$.optional(),noSideEffectSmoke:V$.optional(),reconciliation:V$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),vP=D.object({providerId:V$,appId:V$,adapterId:V$,ownerPackage:V$,modes:D.array(bJ).min(1),defaultMode:bJ,credentialRequirements:D.array(SP).default([]),operations:D.array(ZP).min(1),rateLimitPosture:V$,costPosture:V$.optional(),auditEvents:D.array(V$).default([]),redactionRules:D.array(V$).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:D.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),yP=D.object({appId:V$,repo:V$,priority:D.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:D.array(V$).min(1),firstOperations:D.array(V$).min(1),blockedUntil:D.array(V$).default([])}).strict(),hP=t$(U$.providerLiveModeStandard).extend({name:V$,version:V$,modes:D.array(bJ).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:D.array(V$).min(1),liveMutationGate:D.object({requiredMode:D.literal("live_mutating"),requiredChecks:D.array(V$).min(1),forbiddenBypassSignals:D.array(V$).min(1),disabledLiveSmoke:V$}).strict(),noSideEffectSmoke:D.object({requiredForModes:D.array(bJ).min(1),commandEvidence:D.array(V$).min(1),secretOutputScan:D.boolean().default(!0)}).strict(),credentialPolicy:D.object({acceptedInputs:D.array(D.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:D.literal(!1),missingCredentialBehavior:D.literal("fail_closed"),revocationCheckRequired:D.boolean().default(!0)}).strict(),operationCards:D.array(vP).min(1),firstAdoptionTargets:D.array(yP).min(1),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:D.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),mP=D.object({id:D.string().min(1),title:D.string().min(1).optional(),summary:D.string().min(1),text:D.string().optional(),tokens:D.number().int().nonnegative().optional(),source:Q_,resourceRefs:D.array(C$).default([])}).strict(),gN=t$(U$.contextPack).extend({objective:D.string().min(1),budget:D.object({maxTokens:D.number().int().positive().optional(),maxBytes:D.number().int().positive().optional()}).strict().optional(),items:D.array(mP).default([]),citations:D.array(Q_).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),permissions:D.array(D.string().min(1)).default([]),redactions:D.array(D.string().min(1)).default([]),conflicts:D.array(D.string().min(1)).default([]),uncertainty:D.string().min(1).optional()}).strict(),P6=V$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),R1=D.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),xP=D.enum(["public","internal","private","sensitive"]),uP=D.enum(["draft","active","paused","archived"]),zQ=D.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),kN=t$(U$.integrationRef).extend({kind:zQ,name:D.string().min(1),projectId:R1.optional(),sourcePackage:V$.optional(),externalId:V$.optional(),uri:Z4.optional(),enabled:D.boolean().default(!0),readOnly:D.boolean().default(!0),capabilities:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:C$.optional(),evidenceRefs:D.array(Q_).default([]),config:v4.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:D.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),dP=D.object({schemaRoot:P6.default(".hasna/project"),dashboardManifest:P6.default(".hasna/project/dashboard.render.json"),snapshotsDir:P6.default(".hasna/project/snapshots"),documentsDir:P6.default("documents"),reportsDir:P6.default("reports"),evidenceDir:P6.default(".hasna/project/evidence"),privateDir:P6.default(".hasna/project/private")}).strict(),nP=t$(U$.projectManifest).extend({projectId:R1,slug:R1,name:D.string().min(1),summary:D.string().min(1).optional(),status:uP.default("active"),classification:xP.default("private"),owner:q4.optional(),layout:dP.default({}),integrations:D.array(kN).default([]),renderManifests:D.array(C$).default([]),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),tags:gJ}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:D.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:D.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:D.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),cP=D.enum(["local","package","provider","url"]),jQ=D.object({id:D.string().min(1),kind:cP,specifier:D.string().min(1),path:P6.optional(),packageName:D.string().min(1).optional(),uri:Z4.optional(),provider:zQ.optional(),schemaId:FN.optional(),integrity:MN.optional(),resourceRef:C$.optional(),optional:D.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:D.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:D.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:D.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:D.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),iP=D.enum(["dashboard","canvas","panel","report","document","custom"]),lP=D.object({id:D.string().min(1),title:D.string().min(1),kind:iP,default:D.boolean().default(!1),entry:P6.optional(),imports:D.array(jQ).default([]),panelRefs:D.array(C$).default([]),dataRefs:D.array(C$).default([]),layout:v4.optional()}).strict(),rP=t$(U$.renderManifest).extend({projectId:R1,name:D.string().min(1),version:D.string().min(1),manifestPath:P6.default(".hasna/project/dashboard.render.json"),renderer:D.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:D.array(lP).min(1),imports:D.array(jQ).default([]),theme:v4.optional(),compatibility:D.object({minProjectsVersion:D.string().min(1).optional(),minContractsVersion:D.string().min(1).optional()}).strict().optional(),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:D.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),pP=D.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),oP=D.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),tP=D.object({id:D.string().min(1),label:D.string().min(1),value:D.union([D.string(),D.number(),D.boolean()]),unit:D.string().min(1).optional(),status:D.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:D.array(C$).default([])}).strict(),aP=D.object({id:D.string().min(1),title:D.string().min(1),summary:D.string().min(1).optional(),status:D.string().min(1).optional(),priority:D.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:U6.optional(),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),metadata:v4.optional()}).strict(),sP=D.object({renderer:D.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:D.string().min(1).optional(),entry:P6.optional(),imports:D.array(jQ).default([]),spec:v4.default({})}).strict(),IN=t$(U$.projectPanel).extend({projectId:R1,provider:D.object({kind:zQ,id:D.string().min(1),name:D.string().min(1).optional(),sourcePackage:V$.optional(),externalId:V$.optional()}).strict(),kind:oP,title:D.string().min(1),summary:D.string().min(1).optional(),state:pP.default("ready"),stateReason:D.string().min(1).optional(),generatedAt:U6,freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),metrics:D.array(tP).default([]),items:D.array(aP).default([]),actions:D.array(C$).default([]),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),renderFragment:sP.optional(),warnings:D.array(D.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:D.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:D.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),eP=t$(U$.projectSnapshot).extend({projectId:R1,generatedAt:U6,status:K1.default("unknown"),manifestRef:C$,renderManifestRef:C$.optional(),panels:D.array(IN).default([]),contextPacks:D.array(gN).default([]),proofBundleRefs:D.array(C$).default([]),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),warnings:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:D.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),fN=D.object({id:D.string().min(1),kind:D.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:D.boolean().default(!0),command:D.string().min(1).optional(),expected:D.string().min(1).optional(),timeoutMs:D.number().int().positive().optional(),resourceRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:D.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),$T=t$(U$.validationPlan).extend({objective:D.string().min(1),subject:C$.optional(),checks:D.array(fN).min(1),verifier:q4.optional(),requiredEvidenceKinds:D.array(qQ).default([])}).strict(),_T=D.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),JT=D.enum(["draft","active","deprecated","archived"]),WT=D.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),UT=D.object({key:D.string().regex(/^[A-Z][A-Z0-9_]*$/),description:D.string().min(1),required:D.boolean().default(!1),["secret"]:D.boolean().default(!1),group:D.string().min(1).optional(),default:D.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),XT=D.object({name:D.string().min(1),command:D.string().min(1),description:D.string().min(1).optional(),required:D.boolean().default(!1)}).strict(),GT=D.object({packageManager:D.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:D.array(D.string().min(1)).default([]),requiredFiles:D.array(D.string().min(1)).default([]),requiredDirectories:D.array(D.string().min(1)).default([]),optionalDirectories:D.array(D.string().min(1)).default([])}).strict(),YT=t$(U$.scaffoldManifest).extend({name:D.string().min(1),version:D.string().min(1),summary:D.string().min(1),type:_T,status:JT.default("draft"),capabilities:D.array(WT).default([]),techStack:D.array(D.string().min(1)).default([]),tags:gJ,source:C$.optional(),output:GT,env:D.array(UT).default([]),scripts:D.array(XT).default([]),validationChecks:D.array(fN).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:D.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),QT=D.enum(["installed","failed","cancelled","partial","unknown"]),qT=t$(U$.scaffoldInstallRecord).extend({scaffoldId:D.string().min(1),scaffoldVersion:D.string().min(1).optional(),manifestRef:C$.optional(),target:C$,status:QT,installedAt:U6.optional(),installer:q4.optional(),packageManager:D.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:v4.optional(),generatedFiles:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),proofBundleRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:D.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),wJ=D.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),DQ=D.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),CN=D.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),zT=D.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),jT=V$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),DT=D.enum(["active","stub","deprecated","archived"]),OT=D.enum(["stable","beta","canary","internal"]),LT=D.object({transport:D.enum(["http","stdio"]).default("http"),bin:D.string().min(1).optional(),url:Z4.optional()}).strict(),BT=D.object({healthPath:D.string().min(1).default("/health"),port:D.number().int().positive().optional(),baseUrl:Z4.optional()}).strict(),HT=D.object({bins:D.array(D.string().min(1)).default([]),mcp:LT.optional(),http:BT.optional()}).strict(),NT=t$(U$.app).extend({appId:wJ,npmName:DQ,repoFolder:wJ,githubUrl:jT,projectSlug:R1,surfaces:HT.default({}),lifecycle:DT,releaseChannel:OT.default("stable"),summary:D.string().min(1).optional(),tags:gJ}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:D.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),VT=D.enum(["skill","ci","backfilled"]),RT=t$(U$.release).extend({appId:wJ,package:DQ,version:CN,gitSha:zT,publishedAt:U6,publishPath:VT,changelogRef:C$.optional(),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),KT=D.enum(["install","update","rollback","freeze-blocked"]),FT=D.object({cliVersion:D.string().min(1).optional(),mcpHealth:D.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),ET=t$(U$.rolloutRecord).extend({appId:wJ,package:DQ,version:CN,machine:V$,action:KT,result:K1,verifiedBy:FT.optional(),at:U6,evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:D.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),MT=D.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),AT=D.enum(["pending","queued","sent","failed","skipped","suppressed"]),bT=D.object({channel:MT,status:AT,deliveredAt:U6.optional(),detail:D.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:D.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),wT=t$(U$.announcement).extend({campaignId:V$,appId:wJ.optional(),releaseRef:C$.optional(),channels:D.array(bT).min(1),audienceRef:C$,sentAt:U6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:D.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:D.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),gT=D.enum(["tag","attribute","group"]),kT=D.enum(["eq","neq","in","not_in","exists","not_exists"]),qN=D.union([D.string(),D.number(),D.boolean()]),IT=D.object({kind:gT,key:D.string().min(1).optional(),op:kT.default("eq"),value:qN.optional(),values:D.array(qN).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:D.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),fT=D.object({match:D.enum(["all","any"]).default("all"),predicates:D.array(IT).min(1)}).strict(),CT=D.enum(["opt_in","opt_out","transactional","none"]),PT=t$(U$.audience).extend({audienceId:wJ,name:V$,definition:fT,consentPolicy:CT,suppressionSyncedAt:V1}).strict(),WQ=["@hasna/cloud","open-cloud"],TT=D.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),ST=D.object({id:D.string().min(1),provider:TT,kind:D.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:D.string().min(1),region:D.string().min(1).optional(),accountId:D.string().min(1).optional(),uri:Z4.optional(),machineScoped:D.boolean().default(!1)}).strict(),PN=t$(U$.appCloudManifest).extend({packageName:D.string().min(1),packageVersion:D.string().min(1).optional(),appId:D.string().min(1),repository:C$.optional(),storageMode:D.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:D.enum(["none","app_owned","external_service","local_cache"]),cloudResources:D.array(ST).default([]),localCache:D.object({path:D.string().min(1).optional(),pullMode:D.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:D.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:D.array(D.string().min(1)).default([...WQ]),dependencies:D.array(D.string().min(1)).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...WQ,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:D.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of WQ)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:D.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:D.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:D.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:D.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:D.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:D.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),TN=D.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),ZT=D.enum(["low","medium","high","critical"]),SN=D.object({id:D.string().min(1),kind:TN,severity:ZT,path:D.string().min(1).optional(),packageName:D.string().min(1).optional(),pattern:D.string().min(1),message:D.string().min(1),evidenceRefs:D.array(Q_).default([])}).strict(),vT=D.object({id:D.string().min(1),kind:TN,status:K1,target:D.string().min(1),command:D.string().min(1).optional(),evidenceRefs:D.array(Q_).default([]),findings:D.array(SN).default([])}).strict(),yT=t$(U$.noCloudEvidencePack).extend({subject:C$,packageName:D.string().min(1).optional(),packageVersion:D.string().min(1).optional(),generatedBy:q4.optional(),scanMode:D.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:K1,verdict:D.enum(["passed","failed","warning","not_run"]),appCloudManifest:PN.optional(),checks:D.array(vT).min(1),findings:D.array(SN).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),hT=D.object({checkId:D.string().min(1),status:K1,summary:D.string().min(1).optional(),startedAt:V1,finishedAt:V1,evidenceRefs:D.array(Q_).default([])}).strict(),mT=t$(U$.proofBundle).extend({subject:C$,validationPlanRef:C$.optional(),status:K1,verdict:D.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:D.array(hT).default([]),verifier:q4.optional(),evidenceRefs:D.array(Q_).default([]),residualRisks:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),xT=t$(U$.workRun).extend({objective:D.string().min(1),status:K1,actor:q4,traceId:D.string().min(1).optional(),startedAt:V1,finishedAt:V1,constraints:D.array(D.string().min(1)).default([]),resourceRefs:D.array(C$).default([]),decisions:D.array(wN).default([]),costEstimates:D.array(NU).default([]),evidenceRefs:D.array(Q_).default([]),validationPlanRefs:D.array(C$).default([]),proofBundleRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),uT=D.object({id:D.string().min(1),at:U6,kind:D.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:D.string().min(1),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),costEstimate:NU.optional()}).strict(),dT=t$(U$.agentTrajectory).extend({actor:q4,workRunRef:C$.optional(),events:D.array(uT).default([]),outcome:D.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:C$.optional()}).strict(),nT="v1",cT=D.enum(["library","cli-with-store","service","saas"]),iT=["local","self-hosted","cloud"],ZN=D.enum(iT),lT=D.enum(["supported","deferred","unsupported"]),rT=D.enum(["none","local-only","api-key","session","service-token","custom"]),UQ=D.object({method:D.enum(["GET","POST","PUT","PATCH","DELETE"]),path:D.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:D.boolean().default(!1),description:D.string().min(1).optional()}).strict(),pT=D.object({id:D.string().min(1),kind:D.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:D.boolean().default(!0),command:D.string().min(1).optional(),evidenceRef:Q_.optional(),status:D.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:D.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:D.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),oT=D.object({name:D.string().min(1),status:lT,bin:D.string().min(1).optional(),mcpBin:D.string().min(1).optional(),authMode:rT,deploymentModes:D.array(ZN).min(1),health:UQ.optional(),readiness:UQ.optional(),version:UQ.optional(),apiBasePath:D.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:D.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:D.string().min(1).optional(),readinessGates:D.array(pT).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:D.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:D.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:D.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:D.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),tT=["local","cloud"],vN=D.enum(tT),aT=["remote","hybrid","self_hosted"],sT=D.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),eT=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function $S($){return eT.map((_)=>`${$}${_}`)}function zN($){return`hasna/oss/${$}/database-url`}var _S=D.object({mode:vN,envPrefix:D.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:D.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:D.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:D.string().min(1).optional()}).strict(),JS=D.object({$schema:D.string().min(1).optional(),schema:D.literal(U$.serviceContract),name:sT,class:cT,contractVersion:D.literal(nT),kitVersion:D.string().min(1),description:D.string().min(1).optional(),bins:D.array(D.string().min(1)).default([]),storage:_S.optional(),deploymentModes:D.array(ZN).default(["local"]),serviceSurfaces:D.array(oT).default([]),metadata:v4.optional()}).strict().superRefine(($,_)=>{let J=new Set($S($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:D.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:D.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:D.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==zN($.name))_.addIssue({code:D.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${zN($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:D.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:D.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:D.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:D.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:D.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:D.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),Kt=D.object({status:D.enum(["ok","degraded","unavailable"]),version:D.string().min(1),mode:vN}).strict(),Ft=D.object({ready:D.boolean(),reason:D.string().min(1).optional()}).strict(),Et=D.object({version:D.string().min(1)}).strict(),WS=D.enum(["info","notice","breaking","critical"]),US=D.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),XS=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],GS=D.enum(XS);var YS=D.enum(["fleet","package","machine"]),yN=t$(U$.commsEventEnvelope).extend({type:US,severity:WS,scope:YS,summary:D.string().min(1).optional(),source:q4.optional(),affected_packages:D.array(V$).default([]),affected_machines:D.array(V$).default([]),action_required:D.boolean().default(!1),ack_by:U6.optional(),dedupe_key:V$,resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:D.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),QS=D.enum(["fleet","package","product","loop-lane","initiative","personal"]),qS=D.enum(["quiet","work","firehose"]),zS=V$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),jS=t$(U$.commsChannelMetadata).extend({class:QS,noise:qS.optional(),owner:V$.optional(),until:zS.optional(),successor:V$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:D.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:D.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),jN={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},DS=t$(U$.commsMessageMetadata).extend({tag:GS,envelope:yN}).strict().superRefine(($,_)=>{let J=jN[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:D.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:D.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(jN))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:D.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var Mt={[U$.actorRef]:gP,[U$.resourceRef]:kP,[U$.evidenceRef]:fP,[U$.workRun]:xT,[U$.decisionEnvelope]:wN,[U$.costEstimate]:NU,[U$.capabilityCard]:PP,[U$.providerLiveModeStandard]:hP,[U$.contextPack]:gN,[U$.integrationRef]:kN,[U$.projectManifest]:nP,[U$.projectPanel]:IN,[U$.projectSnapshot]:eP,[U$.renderManifest]:rP,[U$.agentTrajectory]:dT,[U$.validationPlan]:$T,[U$.proofBundle]:mT,[U$.scaffoldManifest]:YT,[U$.scaffoldInstallRecord]:qT,[U$.appCloudManifest]:PN,[U$.noCloudEvidencePack]:yT,[U$.serviceContract]:JS,[U$.commsEventEnvelope]:yN,[U$.commsChannelMetadata]:jS,[U$.commsMessageMetadata]:DS,[U$.app]:NT,[U$.release]:RT,[U$.rolloutRecord]:ET,[U$.announcement]:wT,[U$.audience]:PT};function VU($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(aT.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}var OS=["remote","hybrid","self_hosted"];function OQ($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(OS.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}import ft from"pg";class f9 extends Error{scheme;port;constructor($,_){super($);this.name="KnowledgeNetworkGuardError",this.scheme=_.scheme,this.port=_.port}}function kJ($=process.env){return($.NODE_ENV??"").trim().toLowerCase()==="test"}function hN($){let _=$.split(".");if(_.length!==4)return!1;if(!_.every((J)=>/^\d{1,3}$/.test(J)&&Number(J)<=255))return!1;return _[0]==="127"}function VS($){let _=$.trim().toLowerCase();if(_.length===0)return!1;if(_==="localhost"||_.endsWith(".localhost"))return!0;if(hN(_))return!0;if(!_.startsWith("[")||!_.endsWith("]"))return!1;let J=_.slice(1,-1);if(J==="::1"||/^(0:){7}1$/.test(J))return!0;let U=J.split(":").pop()??"";if(/^(::ffff:|::)/.test(J)&&hN(U))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(J)}function uN($){if(typeof $==="string")return $;if($ instanceof URL)return $.href;return $.url}function mN($,_=process.env){if(!kJ(_))return;let J=uN($),U;try{U=new URL(J)}catch{throw new f9("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(VS(U.hostname))return;throw new f9(`knowledge: refused a non-loopback ${U.protocol.replace(":","")} request while NODE_ENV=test (target host withheld on purpose). This process resolved to the cloud backend under test, which means a read or write was about to leave the machine and reach the live store. Select the mode explicitly (HASNA_KNOWLEDGE_STORAGE_MODE=local) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:U.protocol.replace(":",""),port:U.port})}var RS=new Set([301,302,303,307,308]),xN=5;function KS($,_){if(_?.method)return _.method.toUpperCase();if(typeof $!=="string"&&!($ instanceof URL))return $.method.toUpperCase();return"GET"}async function C9($,_){if(mN($),!kJ()||_?.redirect!==void 0)return fetch($,_);let J=uN($),U=KS($,_),W=_?.body,X=await fetch($,{..._??{},redirect:"manual"});for(let G=0;RS.has(X.status);G++){let Y=X.headers.get("location");if(!Y)return X;let Q=new URL(Y,J).href;if(mN(Q),G>=xN){let L=new URL(Q);throw new f9(`knowledge: refused to follow more than ${xN} redirects while NODE_ENV=test (target host withheld on purpose). Under test the guard follows redirects itself so every hop is checked, and a chain this long is a loop, not a route.`,{scheme:L.protocol.replace(":",""),port:L.port})}if(X.status===303||(X.status===301||X.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",W=void 0;let q={..._??{},method:U,redirect:"manual"};if(W===void 0)delete q.body;else q.body=W;X=await fetch(Q,q),J=Q}return X}var T9="knowledge",LQ=XN(T9),y4=LQ.modeKeys,S9=LQ.apiUrlKeys,Z9=LQ.apiKeyKeys;function P9($,_){return _.filter((J)=>($[J]??"").trim().length>0)}function RU($=process.env){let _=[...P9($,S9),...P9($,Z9)],J=y4[0];for(let U of y4){let W=$[U]?.trim();if(!W)continue;let X;try{X=OQ(W)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);throw Error(`knowledge: ${U}=${W} is not a valid mode. ${Q}`)}let G=[];if(X.deprecatedAlias)G.push(`Deprecated mode '${X.deprecatedAlias}' from ${U} is treated as 'cloud'. Prefer ${J}=cloud.`);if(U!==J)G.push(`Using alias env ${U}; the canonical key is ${J}.`);if(X.mode==="local"&&_.length>0)G.push(`${U}=local pins the on-box store; ${_.join(", ")} are set but ignored.`);return{mode:X.mode,source:{kind:"env",name:U,value:W},pointer_env_present:_,pointer_ignored:X.mode==="local"&&_.length>0,warning:G.length>0?G.join(" "):null}}return{mode:"local",source:{kind:"default",name:null,value:null},pointer_env_present:_,pointer_ignored:_.length>0,warning:_.length>0?`${_.join(", ")} are set but do NOT select a backend: mode is local by default. Set ${J}=cloud to route reads and writes to the API, or unset those vars to silence this note.`:null}}var FS=["postgres","cloud","self_hosted"],ES=["sqlite","local"],dN=new Map;function nN($,_,J){let U=_===VU;if(U){let W=dN.get($);if(W!==void 0)return W}for(let W of $)try{if(_(W),U)dN.set($,W);return W}catch{}throw Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts (tried ${$.join(", ")}). The storage-mode enum has changed; add the new token to ${J} in src/knowledge-mode.ts.`)}function MS($=VU){return nN(FS,$,"SERVER_MODE_CANDIDATES")}function AS($=VU){return nN(ES,$,"LOCAL_MODE_CANDIDATES")}function bS($,_=VU){return $==="cloud"?MS(_):AS(_)}function BQ($,_){return{...$,[y4[0]]:bS(_)}}class cN extends Error{code="knowledge_mode_unset_with_api_url";constructor($){let _=y4[0];super(`knowledge: ${$.join(", ")} names an API store, but no mode variable says to use it, so this command would silently read and write the on-box store instead. Set ${_}=cloud to use the API, or ${_}=local to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function iN($=process.env,_={}){let J=RU($);if(_.storePathOverridden)return J;if(J.source.kind!=="default")return J;let U=P9($,S9);if(U.length===0)return J;throw new cN(U)}function lN($=process.env){let _=RU($);return{..._,store_transport:_.mode==="cloud"?"api":"local",api_key_present:P9($,Z9).length>0,network_guard_active:kJ($)}}function rN($){return{fetchImpl:C9,...kJ($)?{retry:!1}:{}}}var R0="notes";class pN extends Error{expected;current;code="version_conflict";constructor($,_){super(`version_conflict: this edit was written against version ${$} but the stored entry is now at version ${_}. Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions.`);this.expected=$;this.current=_;this.name="KnowledgeVersionConflictError"}}function wS($){let _={};if($.search)_.search=$.search;if($.limit!==void 0)_.limit=$.limit;if($.offset!==void 0)_.offset=$.offset;if($.includeArchived||$.archivedOnly)_.includeArchived=!0;return _}function gS($){return{baseUrl:$.baseUrl,async list(_={}){let J=_.limit??200,U=wS({..._,limit:Math.min(Math.max(J,1),200)}),W=await $.list(R0,{query:U}),X=W.items;if(_.archivedOnly)X=X.filter((G)=>G.archived===!0);if(_.tag){let G=_.tag.toLowerCase();X=X.filter((Y)=>(Y.tags??[]).some((Q)=>Q.toLowerCase()===G))}return{items:X,total:W.total}},async get(_){return $.get(R0,_)},async create(_){return $.create(R0,{..._.id?{id:_.id}:{},title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],..._.metadata?{metadata:_.metadata}:{}})},async update(_,J,U={}){try{return await $.update(R0,_,J,{...U.expectedVersion!==void 0?{headers:{"if-match":String(U.expectedVersion)}}:{}})}catch(W){if(HQ(W))return null;let X=kS(W);if(X)throw X;throw W}},async delete(_){let J=await $.get(R0,_);if(!J)return!1;return await $.delete(R0,J.id),!0},async listVersions(_,J={}){try{return await $.transport.get(`/${R0}/${encodeURIComponent(_)}/versions`,{query:{limit:J.limit,offset:J.offset}})}catch(U){if(HQ(U))return null;throw U}},async getVersion(_,J){try{return await $.transport.get(`/${R0}/${encodeURIComponent(_)}/versions/${J}`)}catch(U){if(HQ(U))return null;throw U}}}}function kS($){if(!$||typeof $!=="object")return null;if($.status!==409)return null;let _=$.body,U=(typeof _==="string"?IS(_):_)??{};if(U.error!=="version_conflict")return null;return new pN(Number(U.expected??0),Number(U.current??0))}function IS($){try{return JSON.parse($)}catch{return null}}function HQ($){return Boolean($&&typeof $==="object"&&$.status===404)}function KU($=process.env){if(RU($).mode!=="cloud")return null;let _=cY(T9,BQ($,"cloud"),rN($));if(_.transport!=="cloud-http")return null;return gS(_.client)}function K0($=process.env){if(RU($).mode!=="cloud")return!1;return cY(T9,BQ($,"cloud"),rN($)).transport==="cloud-http"}async function v9($){let J=[];for(let U=0;;U+=200){let{items:W}=await $.list({includeArchived:!0,limit:200,offset:U});if(J.push(...W),W.length<200)break;if(U>1e5)break}return J}class VQ extends Error{location;code="version_history_unsupported";constructor($){super(`Version history is not kept by the local JSON knowledge store (${$}). It has no version line, so an empty history here would be a claim, not a measurement. Entry versioning lives in the Postgres-backed store: point this CLI at it (HASNA_KNOWLEDGE_STORAGE_MODE=cloud plus the API url/key) and re-run.`);this.location=$;this.name="VersionHistoryUnsupportedError"}}function NQ($,_){return $.id===_||$.short_id===_}class oN{storePath;kind="local";supportsVersions=!1;constructor($){this.storePath=$}async listVersions(){throw new VQ(this.storePath)}async getVersion(){throw new VQ(this.storePath)}get location(){return this.storePath}get exists(){return fS(this.storePath)}async listAll(){let $=g2(this.storePath);return{items:$.items,exists:$.exists}}async get($){return g2(this.storePath).items.find((J)=>NQ(J,$))??null}async create($){return $4(this.storePath,()=>{let _=rW(this.storePath),J=new Date().toISOString(),U=$.id??lB(),W={id:U,short_id:rB(U),title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],metadata:$.metadata??{},archived:!1,created_at:J,updated_at:J};return _.items.push(W),F4(this.storePath,_),W},{createParent:!0})}async update($,_){return $4(this.storePath,()=>{let J=rW(this.storePath),U=J.items.findIndex((X)=>NQ(X,$));if(U===-1)return null;let W=J.items[U];if(_.title!==void 0)W.title=_.title;if(_.content!==void 0)W.content=_.content;if(_.url!==void 0)W.url=_.url;if(_.tags!==void 0)W.tags=_.tags;if(_.metadata!==void 0)W.metadata=_.metadata;if(_.archived!==void 0)W.archived=_.archived;return W.updated_at=new Date().toISOString(),J.items[U]=W,F4(this.storePath,J),W},{createParent:!0})}async delete($){return $4(this.storePath,()=>{let _=rW(this.storePath),J=_.items.length;_.items=_.items.filter((W)=>!NQ(W,$));let U=J!==_.items.length;if(U)F4(this.storePath,_);return U},{createParent:!0})}async deleteMany($){if($.length===0)return 0;let _=new Set($);return $4(this.storePath,()=>{let J=rW(this.storePath),U=J.items.length;J.items=J.items.filter((X)=>!_.has(X.id)&&!(X.short_id!=null&&_.has(X.short_id)));let W=U-J.items.length;if(W>0)F4(this.storePath,J);return W},{createParent:!0})}}class tN{cloud;kind="api";exists=!0;supportsVersions=!0;constructor($){this.cloud=$}async listVersions($,_={}){return this.cloud.listVersions($,_)}async getVersion($,_){return this.cloud.getVersion($,_)}get location(){return this.cloud.baseUrl}async listAll(){return{items:await v9(this.cloud),exists:!0}}async get($){return this.cloud.get($)}async create($){return this.cloud.create({...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})}async update($,_,J={}){return this.cloud.update($,_,{expectedVersion:J.expectedVersion})}async delete($){return this.cloud.delete($)}async deleteMany($){let _=0;for(let J of $)if(await this.cloud.delete(J))_+=1;return _}}function y9($){let _=$.storePathOverridden?null:KU($.env??process.env);if(_)return new tN(_);return new oN($.storePath)}function aN($){let _=$??"";if(_==="")return[];return _.replace(/\n$/,"").split(` -`)}var RQ=5000;function CS($,_){let J=aN($),U=aN(_);if(J.length>RQ||U.length>RQ)throw Error(`Refusing to line-diff ${Math.max(J.length,U.length)} lines (limit ${RQ}). Fetch the two versions and diff them with a dedicated tool.`);let W=Array.from({length:J.length+1},()=>Array(U.length+1).fill(0));for(let Q=J.length-1;Q>=0;Q-=1)for(let q=U.length-1;q>=0;q-=1)W[Q][q]=J[Q]===U[q]?W[Q+1][q+1]+1:Math.max(W[Q+1][q],W[Q][q+1]);let X=[],G=0,Y=0;while(G=W[G][Y+1])X.push({op:"remove",from_line:G+1,to_line:null,text:J[G]}),G+=1;else X.push({op:"add",from_line:null,to_line:Y+1,text:U[Y]}),Y+=1;while(G{if(!PS($[Y],_[Y]))J.push({field:Y,from:$[Y]??null,to:_[Y]??null})};U("title"),U("url"),U("tags"),U("metadata"),U("archived");let W=CS($.content,_.content),X=W.filter((Y)=>Y.op==="add").length,G=W.filter((Y)=>Y.op==="remove").length;return{identical:J.length===0&&X===0&&G===0,fields:J,content:W,added:X,removed:G}}function eN($,_,J){let U=[`--- ${_}`,`+++ ${J}`];if($.identical)return U.push("(no changes)"),U.join(` -`);for(let W of $.fields)U.push(`~ ${W.field}: ${JSON.stringify(W.from)} -> ${JSON.stringify(W.to)}`);if($.added===0&&$.removed===0){if($.fields.length>0)U.push("(content unchanged)")}else{U.push(`@@ content +${$.added} -${$.removed} @@`);for(let W of $.content){let X=W.op==="add"?"+":W.op==="remove"?"-":" ";U.push(`${X}${W.text}`)}}return U.join(` -`)}import{Database as $3}from"bun:sqlite";function h9($="catalog"){if(K0()){let _=y4[0];throw Error(`knowledge: ${$} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${_}=local `+"(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see "+"which variable selected the current backend.")}}var TS="porter unicode61 remove_diacritics 2",_3=` +`),this.outputHelp({error:!0});let g=$||{},U=g.exitCode||1,D=g.code||"commander.error";this._exit(U,D,_)}_parseOptionsEnv(){this.options.forEach((_)=>{if(_.envVar&&_.envVar in E_.env){let $=_.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(_.required||_.optional)this.emit(`optionEnv:${_.name()}`,E_.env[_.envVar]);else this.emit(`optionEnv:${_.name()}`)}})}_parseOptionsImplied(){let _=new lr(this.options),$=(g)=>{return this.getOptionValue(g)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(g))};this.options.filter((g)=>g.implied!==void 0&&$(g.attributeName())&&_.valueFromOption(this.getOptionValue(g.attributeName()),g)).forEach((g)=>{Object.keys(g.implied).filter((U)=>!$(U)).forEach((U)=>{this.setOptionValueWithSource(U,g.implied[U],"implied")})})}missingArgument(_){let $=`error: missing required argument '${_}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(_){let $=`error: option '${_.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(_){let $=`error: required option '${_.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(_,$){let g=(I)=>{let j=I.attributeName(),N=this.getOptionValue(j),O=this.options.find((L)=>L.negate&&j===L.attributeName()),A=this.options.find((L)=>!L.negate&&j===L.attributeName());if(O&&(O.presetArg===void 0&&N===!1||O.presetArg!==void 0&&N===O.presetArg))return O;return A||I},U=(I)=>{let j=g(I),N=j.attributeName();if(this.getOptionValueSource(N)==="env")return`environment variable '${j.envVar}'`;return`option '${j.flags}'`},D=`error: ${U(_)} cannot be used with ${U($)}`;this.error(D,{code:"commander.conflictingOption"})}unknownOption(_){if(this._allowUnknownOption)return;let $="";if(_.startsWith("--")&&this._showSuggestionAfterError){let U=[],D=this;do{let I=D.createHelp().visibleOptions(D).filter((j)=>j.long).map((j)=>j.long);U=U.concat(I),D=D.parent}while(D&&!D._enablePositionalOptions);$=O8(_,U)}let g=`error: unknown option '${_}'${$}`;this.error(g,{code:"commander.unknownOption"})}_excessArguments(_){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,g=$===1?"":"s",D=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${g} but got ${_.length}.`;this.error(D,{code:"commander.excessArguments"})}unknownCommand(){let _=this.args[0],$="";if(this._showSuggestionAfterError){let U=[];this.createHelp().visibleCommands(this).forEach((D)=>{if(U.push(D.name()),D.alias())U.push(D.alias())}),$=O8(_,U)}let g=`error: unknown command '${_}'${$}`;this.error(g,{code:"commander.unknownCommand"})}version(_,$,g){if(_===void 0)return this._version;this._version=_,$=$||"-V, --version",g=g||"output the version number";let U=this.createOption($,g);return this._versionOptionName=U.attributeName(),this._registerOption(U),this.on("option:"+U.name(),()=>{this._outputConfiguration.writeOut(`${_} +`),this._exit(0,"commander.version",_)}),this}description(_,$){if(_===void 0&&$===void 0)return this._description;if(this._description=_,$)this._argsDescription=$;return this}summary(_){if(_===void 0)return this._summary;return this._summary=_,this}alias(_){if(_===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(_===$._name)throw Error("Command alias can't be the same as its name");let g=this.parent?._findCommand(_);if(g){let U=[g.name()].concat(g.aliases()).join("|");throw Error(`cannot add alias '${_}' to command '${this.name()}' as already have command '${U}'`)}return $._aliases.push(_),this}aliases(_){if(_===void 0)return this._aliases;return _.forEach(($)=>this.alias($)),this}usage(_){if(_===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((g)=>{return dr(g)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=_,this}name(_){if(_===void 0)return this._name;return this._name=_,this}nameFromFilename(_){return this._name=S6.basename(_,S6.extname(_)),this}executableDir(_){if(_===void 0)return this._executableDir;return this._executableDir=_,this}helpInformation(_){let $=this.createHelp(),g=this._getOutputContext(_);$.prepareContext({error:g.error,helpWidth:g.helpWidth,outputHasColors:g.hasColors});let U=$.formatHelp(this,$);if(g.hasColors)return U;return this._outputConfiguration.stripColor(U)}_getOutputContext(_){_=_||{};let $=!!_.error,g,U,D;if($)g=(j)=>this._outputConfiguration.writeErr(j),U=this._outputConfiguration.getErrHasColors(),D=this._outputConfiguration.getErrHelpWidth();else g=(j)=>this._outputConfiguration.writeOut(j),U=this._outputConfiguration.getOutHasColors(),D=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(j)=>{if(!U)j=this._outputConfiguration.stripColor(j);return g(j)},hasColors:U,helpWidth:D}}outputHelp(_){let $;if(typeof _==="function")$=_,_=void 0;let g=this._getOutputContext(_),U={error:g.error,write:g.write,command:this};this._getCommandAndAncestors().reverse().forEach((I)=>I.emit("beforeAllHelp",U)),this.emit("beforeHelp",U);let D=this.helpInformation({error:g.error});if($){if(D=$(D),typeof D!=="string"&&!Buffer.isBuffer(D))throw Error("outputHelp callback must return a string or a Buffer")}if(g.write(D),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",U),this._getCommandAndAncestors().forEach((I)=>I.emit("afterAllHelp",U))}helpOption(_,$){if(typeof _==="boolean"){if(_)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return _=_??"-h, --help",$=$??"display help for command",this._helpOption=this.createOption(_,$),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(_){return this._helpOption=_,this}help(_){this.outputHelp(_);let $=Number(E_.exitCode??0);if($===0&&_&&typeof _!=="function"&&_.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(_,$){let g=["beforeAll","before","after","afterAll"];if(!g.includes(_))throw Error(`Unexpected value for position to addHelpText. +Expecting one of '${g.join("', '")}'`);let U=`${_}Help`;return this.on(U,(D)=>{let I;if(typeof $==="function")I=$({error:D.error,command:D.command});else I=$;if(I)D.write(`${I} +`)}),this}_outputHelpIfRequested(_){let $=this._getHelpOption();if($&&_.find((U)=>$.is(U)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function A8(_){return _.map(($)=>{if(!$.startsWith("--inspect"))return $;let g,U="127.0.0.1",D="9229",I;if((I=$.match(/^(--inspect(-brk)?)$/))!==null)g=I[1];else if((I=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(g=I[1],/^\d+$/.test(I[3]))D=I[3];else U=I[3];else if((I=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)g=I[1],U=I[3],D=I[4];if(g&&D!=="0")return`${g}=${U}:${parseInt(D)+1}`;return $})}function _z(){if(E_.env.NO_COLOR||E_.env.FORCE_COLOR==="0"||E_.env.FORCE_COLOR==="false")return!1;if(E_.env.FORCE_COLOR||E_.env.CLICOLOR_FORCE!==void 0)return!0;return}tr.Command=$z;tr.useColor=_z});var S8=e6((sr)=>{var{Argument:J8}=zN(),{Command:gz}=L8(),{CommanderError:er,InvalidArgumentError:P8}=qU(),{Help:ar}=p3(),{Option:z8}=e3();sr.program=new gz;sr.createCommand=(_)=>new gz(_);sr.createOption=(_,$)=>new z8(_,$);sr.createArgument=(_,$)=>new J8(_,$);sr.Command=gz;sr.Option=z8;sr.Argument=J8;sr.Help=ar;sr.CommanderError=er;sr.InvalidArgumentError=P8;sr.InvalidOptionArgumentError=P8});import{chmodSync as Qz,closeSync as Mg,existsSync as U0,fsyncSync as kN,lstatSync as EY,openSync as CN,readFileSync as Zg,renameSync as Tz,unlinkSync as rN,writeFileSync as vN}from"fs";import{randomUUID as bg}from"crypto";import{basename as OY,dirname as qz,join as HN}from"path";import{chmodSync as Jz,existsSync as DY,mkdirSync as BN,readFileSync as UY,writeFileSync as Pz}from"fs";import{homedir as KN}from"os";import{dirname as IY,join as x_,resolve as zz}from"path";var l$=x_(".hasna","knowledge"),Sz=x_(".hasna","apps","knowledge"),P_={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:l$,s3:{bucket:"example-knowledge-prod",region:"us-east-1",profile:"example-infra",prefix:".hasna/knowledge",server_side_encryption:"AES256"},secrets:{env:"example/knowledge/prod/env",aws:"example/knowledge/prod/aws",s3:"example/knowledge/prod/s3",rds:null,future_rds:"example/knowledge/prod/rds"},source_owner:"open-files",evidence_doc:"docs/canonical-secrets-bootstrap-2026-06-08.md"};function Wz(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:P_.s3.bucket,prefix:P_.s3.prefix,region:P_.s3.region,profile:P_.s3.profile,server_side_encryption:P_.s3.server_side_encryption}}}function Vg(){return x_(KN(),".open-knowledge","db.json")}function MU(){return x_(KN(),".hasna","knowledge")}function VN(_=process.cwd()){return zz(_,l$)}function jY(){return x_(KN(),Sz)}function NY(_=process.cwd()){return zz(_,Sz)}function FN(_,$=process.cwd()){if(_==="project"||_==="local")return D$(NY($));return D$(jY())}function D$(_){return{home:_,configPath:x_(_,"config.json"),jsonStorePath:x_(_,"db.json"),knowledgeDbPath:x_(_,"knowledge.db"),artifactsDir:x_(_,"artifacts"),cacheDir:x_(_,"cache"),exportsDir:x_(_,"exports"),indexesDir:x_(_,"indexes"),logsDir:x_(_,"logs"),runsDir:x_(_,"runs"),schemasDir:x_(_,"schemas"),wikiDir:x_(_,"wiki")}}function Fg(){return{version:1,mode:"local",hosted:{api_url:"https://knowledge.md"},storage:{type:"local",artifacts_root:"artifacts"},sources:{preferred_ref:"open-files",allowed_schemes:["open-files","s3","file","https","http"]},providers:{default_model:"openai:gpt-5.2",aliases:{fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"},openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},embeddings:{default_model:"openai:text-embedding-3-small",dimensions:1536,batch_size:64,max_parallel_calls:4},safety:{network:{web_search_enabled:!1,s3_reads_enabled:!1,allowed_s3_buckets:[]},redaction:{enabled:!0},approvals:{generated_writes_require_approval:!0}}}}function D0(_){let $=D$(_);BN($.home,{recursive:!0,mode:448});for(let g of[$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir])BN(g,{recursive:!0,mode:448});if(!DY($.configPath))Pz($.configPath,`${JSON.stringify(Fg(),null,2)} +`,{mode:384}),Jz($.configPath,384);return $}function ZU(_,$=process.cwd()){if(_==="project"||_==="local")return D$(VN($));return D$(MU())}function X6(_){BN(IY(_),{recursive:!0})}function MN(_){let $=UY(_,"utf8");return JSON.parse($)}function Xz(_,$){X6(_),Pz(_,`${JSON.stringify($,null,2)} +`,{mode:384}),Jz(_,384)}function HU(){return D$(MU()).jsonStorePath}function Hg(_){if(_===HU()&&U0(Vg()))wN();if(!U0(_))X6(_),Vz(_,`${JSON.stringify({items:[]},null,2)} +`)}function AY(_){return _.toISOString().replace(/[:.]/g,"-")}function fN(_){let $=[`id:${_.id}`];if(typeof _.short_id==="string"&&_.short_id.length>0)$.push(`short_id:${_.short_id}`);return $}function LY(_){let $=new Set;for(let g of _)for(let U of fN(g))$.add(U);return $}function JY(_,$){return fN($).some((g)=>_.has(g))}function ZN(_,$){X6(_),vN(_,`${JSON.stringify($,null,2)} +`,{mode:384}),Qz(_,384)}function Rz(_){let $=JSON.parse(Zg(_,"utf8"));if(!$||typeof $!=="object"||!Array.isArray($.items))return{store:{items:[]},skippedInvalid:0};let g={items:[]},U=0;for(let D of $.items)if(D&&typeof D==="object"&&typeof D.id==="string"&&D.id.length>0)g.items.push(D);else U+=1;return{store:g,skippedInvalid:U}}function wN(_={}){if(_.dryRun===!0)return Gz(_);return v$(HU(),()=>Gz(_),{createParent:!0})}function Gz(_={}){let $=_.dryRun===!0,g=_.now??new Date,U=D$(MU()),D=Vg(),I=U.jsonStorePath,j=U0(D),N=U0(I),O={ok:!0,dry_run:$,legacy_path:D,canonical_path:I,legacy_exists:j,canonical_existed:N,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:j?"Legacy global store already imported":"No legacy global store found"};if(!j)return O;let A;try{let P=Rz(D);A=P.store,O.skipped_invalid=P.skippedInvalid}catch(P){return O.ok=!1,O.errors.push(`Could not read legacy store: ${P instanceof Error?P.message:String(P)}`),O.message="Legacy global store import failed",O}let L={items:[]};if(N)try{L=Rz(I).store}catch(P){return O.ok=!1,O.errors.push(`Could not read canonical store: ${P instanceof Error?P.message:String(P)}`),O.message="Legacy global store import failed",O}let z=LY(L.items),W={items:[...L.items]};for(let P of A.items){if(!P?.id){O.skipped_invalid+=1;continue}if(JY(z,P)){O.skipped_existing+=1;continue}W.items.push(P);for(let S of fN(P))z.add(S);O.imported+=1}if(O.would_create_canonical=!N&&O.imported>0,O.canonical_created=!$&&O.would_create_canonical,O.message=O.imported>0?`Imported ${O.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",$||O.imported===0)return O;let J=`${AY(g)}-${bg().slice(0,8)}`;if(N)O.backup_path=HN(U.exportsDir,`legacy-open-knowledge-db-before-import-${J}.json`),ZN(O.backup_path,L);return ZN(I,W),O.report_path=HN(U.runsDir,`legacy-open-knowledge-import-${J}.json`),ZN(O.report_path,O),O}function I0(_){if(!U0(_))return{exists:!1,items:[]};let $=Zg(_,"utf8"),g=JSON.parse($);if(!g||!Array.isArray(g.items))return{exists:!0,items:[]};return{exists:!0,items:g.items}}function PY(_){return`${_}.lock`}var bU=1e4,Bz=25,Yz=120000,zY=new Int32Array(new SharedArrayBuffer(4));function uN(_){return typeof _==="object"&&_!==null&&"code"in _?String(_.code):void 0}function Kz(_){let $=null;try{$=CN(qz(_),"r"),kN($)}catch{}finally{if($!==null)try{Mg($)}catch{}}}var bN=new Set;function Vz(_,$){X6(_);let g=HN(qz(_),`.${OY(_)}.tmp.${bg()}`),U=null;try{U=CN(g,"wx",384),vN(U,$),kN(U),Mg(U),U=null,Tz(g,_);try{Qz(_,384)}catch{}Kz(_)}catch(D){if(U!==null)try{Mg(U)}catch{}try{rN(g)}catch{}throw D}}function Fz(_){Atomics.wait(zY,0,0,_)}function SY(_){if(typeof _!=="number"||!Number.isInteger(_)||_<=0)return!1;try{return process.kill(_,0),!0}catch($){return uN($)!=="ESRCH"}}function Mz(_,$){try{let g=Zg(_,"utf8"),U=JSON.parse(g);if(typeof U.ts==="number")return $-U.ts>Yz&&!SY(U.pid)}catch{}try{return $-EY(_).mtimeMs>Yz}catch{return!1}}function WY(_){let $=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),g=`${_}.stale.${$}.${bg()}`;try{Tz(_,g)}catch(U){if(uN(U)!=="ENOENT")throw U;return}}function XY(_){let $=bg(),g=`${_}.breaker`,U=Date.now();while(Date.now()-UFY)return null;g=QY(_,"utf8")}catch{return null}let U=kY(g);for(let D of $){let I=U.get(D)?.trim();if(I)return I}return null}function j0(_,$,g){if(!bY.test(g))return;throw new Cg(_,`The credential from ${$} contains characters that cannot be sent in an HTTP header (a control character or non-ASCII byte). A file written with CR-only line endings is the usual cause. Rewrite that credential file with one LF-terminated KEY=value line. The value is not shown here, and is deliberately never logged.`,[$])}var CY=Symbol.for("nodejs.util.inspect.custom");function N0(_){let{apiKey:$,...g}=_,U={...g};return Object.defineProperty(U,"apiKey",{value:$,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(U,CY,{value:()=>({...g,apiKey:"[redacted]"}),enumerable:!1,writable:!1,configurable:!1}),U}function rY(_,$){return j0(_,"explicit apiKey option",$),N0({apiKey:$,tier:"argument",source:"explicit apiKey option",deliberate:!0,deprecated:!1,diskCandidates:[],warning:null})}function fz(_,$){for(let g of $){let U=_[g]?.trim();if(U)return{key:g,value:U}}return null}var wz=Symbol.for("hasna:contracts:credentialDeprecationNotices");function vY(){let _=globalThis,$=_[wz];if($ instanceof Set)return $;let g=new Set;return _[wz]=g,g}function fY(_){if(typeof process<"u"&&process.stderr)process.stderr.write(`${_} +`)}function cN(_,$,g={}){let{apiKeyKeys:U}=hz(_),D=cz(_,$),I=g.apiKey?.trim();if(I)return j0(_,"the explicit apiKey argument",I),N0({apiKey:I,tier:"argument",source:"explicit apiKey argument",deliberate:!0,deprecated:!1,diskCandidates:D,warning:null});let j=YY(_),N=$[j];if(N!==void 0){let z=N.trim();if(!z)throw new Cg(_,`${j} is set but empty. It is a deliberate override, so it is not resolved around: either give it a real key or unset it to fall back to the credential on disk.`,[j]);return j0(_,j,z),N0({apiKey:z,tier:"override",source:j,deliberate:!0,deprecated:!1,diskCandidates:D,warning:null})}let O=g.profile?.trim()||$[xN]?.trim();if(O){let z=g.profile?.trim()?"explicit profile argument":xN;if(!ZY.test(O))throw new Cg(_,`Profile name from ${z} is not usable in a path. Use letters, digits, dot, dash, or underscore.`,[z]);let W=nz(_,$,O);for(let J of W){let P=vz(J,U);if(P)return j0(_,J,P),N0({apiKey:P,tier:"profile",source:J,deliberate:!0,deprecated:!1,diskCandidates:W,warning:null})}throw new Cg(_,`Profile '${O}' (from ${z}) has no ${U[0]} for '${_}'. Looked in: ${W.join(", ")||""}. `+"A profile names WHICH identity to use, so it is never resolved around \u2014 "+`create the profile's credential file or unset ${xN}.`,W)}let A=D.map((z)=>({path:z,value:vz(z,U)})).filter((z)=>z.value!==null);if(A.length>0){let z=A[0];j0(_,z.path,z.value);let W=[...A.slice(1).filter((P)=>P.value!==z.value).map((P)=>P.path),...(()=>{let P=fz($,U);return P&&P.value!==z.value?[P.key]:[]})()],J=W.length>0?`Credential sources disagree for '${_}': ${z.path} and ${W.join(", ")} hold different keys. ${z.path} wins, because a file on `+"disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 "+"a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.":null;return N0({apiKey:z.value,tier:"disk",source:z.path,deliberate:!1,deprecated:!1,diskCandidates:D,warning:J})}let L=fz($,U);if(L){j0(_,L.key,L.value);let z=D.length>0?`Put the current key in ${D[0]} \u2014 it is re-read on every call, so rotations take effect immediately.`:"This environment has no HOME, so no credential file could be consulted at all; the disk tier is unavailable here and this process will keep using the environment snapshot.",W=`[${_}] DEPRECATED: the API key came from ${L.key} in this process's environment. Environment variables are a snapshot taken when this process started, so a shell that started before a key rotation keeps using the old key until it exits. ${z}`,J=g.onDeprecation??fY,P=vY();if(!P.has(_))P.add(_),J(W);return N0({apiKey:L.value,tier:"legacy-env",source:L.key,deliberate:!1,deprecated:!0,diskCandidates:D,warning:W})}return null}var R6="HASNA_FLEET_API_DOMAIN",E0="your-deployment.example",dN=/[\u0000-\u001f\u007f]/,dz=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function kU(_){if(_.length===0||_.length>253||dN.test(_)||/[^\x00-\x7f]/.test(_))return!1;return _.split(".").every(($)=>$.length<=63&&!$.startsWith("xn--")&&dz.test($))}function wY(_){let $=_[R6];if($===void 0)return{domain:E0,source:"default",misconfigured:!0,warning:`${R6} is not set; using the non-resolving ${E0} fallback.`};let g=$.trim().toLowerCase();if(dN.test($)||!kU(g))return{domain:E0,source:R6,misconfigured:!0,warning:`${R6} is blank or invalid; using the non-resolving ${E0} fallback.`};return{domain:g,source:R6,misconfigured:!1,warning:null}}function mz(_){if(_.length>63||!dz.test(_))throw Error("App name must be one lowercase DNS label.");return _}function uY(_,$){let g=`${mz(_)}.${$}`;if(!kU(g))throw Error("Composed cloud hostname must be a valid DNS domain");return g}function xY(_,$){let g=mz(_),U=wY($),D=`${g}.${U.domain}`;if(kU(D))return{baseUrl:`https://${D}`,source:U.source,misconfigured:U.misconfigured,warning:U.warning};return{baseUrl:`https://${uY(g,E0)}`,source:U.source,misconfigured:!0,warning:`${R6} cannot form a valid composed cloud hostname for app '${g}'; using the non-resolving ${E0} fallback.`}}function yN(_,$,g={}){for(let U of $){let D=_[U],I=D?.trim();if(I)return{key:U,value:g.preserveRaw?D:I}}return null}function yY(_){let $=/^[a-z][a-z0-9+.-]*:\/\//i.exec(_);if(!$)throw Error("API URL must be absolute.");let g=_.slice($[0].length),U=g.search(/[/?#]/),D=U===-1?g:g.slice(0,U);if(!D)throw Error("API URL must include a hostname.");return D}function uz(_){if(!/^[0-9]+$/.test(_)||_.length>1&&_.startsWith("0"))throw Error("API URL authority must contain a canonical port between 1 and 65535.");let $=Number(_);if(!Number.isSafeInteger($)||$<1||$>65535)throw Error("API URL authority must contain a canonical port between 1 and 65535.")}function hY(_){let $;if(_.startsWith("[")){let g=_.indexOf("]");if(g===-1)throw Error("API URL authority must contain a canonical hostname.");$=_.slice(0,g+1);let U=_.slice(g+1);if(U){if(!U.startsWith(":"))throw Error("API URL authority must contain a canonical hostname and port.");uz(U.slice(1))}if(Cz($.slice(1,-1))!==6)throw Error("API URL authority must contain a canonical IPv6 literal.")}else{let g=_.indexOf(":"),U=_.lastIndexOf(":");if(g!==U)throw Error("IPv6 API URL authorities must use brackets.");if(U!==-1){let N=_.slice(U+1);uz(N),$=_.slice(0,U)}else $=_;let D=Cz($),j=$.split(".").every((N)=>/^(?:0x[0-9a-f]+|[0-9]+)$/i.test(N));if(D!==4&&j||D!==4&&!kU($.toLowerCase()))throw Error("API URL authority must contain a canonical ASCII hostname.")}return $.toLowerCase()}function cY(_){return/^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(_)}function iz(_){if(dN.test(_))throw Error("API URL must not contain ASCII control characters.");let $=_.trim(),g=yY($);if(g.includes("@")||g.includes("\\")||g.includes("%")||/[^\x00-\x7f]/.test(g))throw Error("API URL authority must be canonical ASCII without credentials.");let U=hY(g),D=new URL($);if(D.protocol!=="http:"&&D.protocol!=="https:")throw Error("API URL must use http or https.");if(D.username||D.password)throw Error("API URL must not include credentials.");if(!D.hostname||D.hostname.endsWith("."))throw Error("API URL must include a canonical hostname.");if(D.hostname.toLowerCase()!==U)throw Error("API URL authority must not rely on parser hostname normalization.");if(D.hostname.split(".").some((j)=>j.toLowerCase().startsWith("xn--")))throw Error("API URL must not use IDN or punycode hostnames.");if(D.protocol==="http:"&&!cY(g))throw Error("API URL may use http only for an exact loopback authority.");if(D.search||D.hash)throw Error("API URL must not include a query string or fragment.");let I=D.pathname.replace(/\/+$/,"");if(I.endsWith("/v1"))I=I.slice(0,-3);return D.pathname=`${I}/v1`,D.toString().replace(/\/+$/,"")}function nY(_,$=process.env,g={}){let U=hz(_),D=yN($,U.modeKeys),I=yN($,U.apiUrlKeys,{preserveRaw:!0}),j=yN($,U.apiKeyKeys),N="sqlite",O="default",A=[],L;if(D)N=GY(D.value).mode,O=D.key;else if(I){if(L=cN(_,$,g.credentials),L)N="postgres",O=`${I.key}+${L.source}`}if(N==="sqlite")return{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(j),apiKeySource:j?j.key:null,apiKeyTier:null,misconfigured:!1,warning:A.length>0?A.join(" "):null};if(L===void 0)L=cN(_,$,g.credentials);if(!L){let P=lz(_,$);return A.push(`${O}=postgres but no API key could be resolved for '${_}'. A client reaches server data over HTTP only; refusing to route. Using the local sqlite store. Looked for a credential file at ${P}, then for ${U.apiKeyKeys[0]} in the environment.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,apiKeyTier:null,misconfigured:!0,warning:A.join(" ")}}if(L.warning)A.push(L.warning);let z=null,W=I?.key??($[R6]===void 0?"default":R6),J;try{if(!I)z=xY(_,$),W=z.source;let P=I?.value??z.baseUrl;J=iz(P)}catch(P){let S=P instanceof Error?P.message:String(P);return A.push(`Invalid API URL from ${W}: ${S}. Using local store.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:!0,warning:A.join(" ")}}if(z?.warning)A.push(z.warning);return{transport:"http",mode:N,modeSource:O,baseUrl:J,apiUrlSource:W,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:z?.misconfigured??!1,warning:A.length>0?A.join(" "):null}}function lz(_,$){let g=cz(_,$);return g.length>0?g.join(" or "):""}class O0 extends Error{status;method;path;body;credentialSource;credentialTier;constructor(_,$,g,U,D){let I=D?`. ${D.guidance}`:"";super(`Hasna cloud request failed: ${_} ${$} -> ${g}${I}`);this.name="HasnaHttpError",this.status=g,this.method=_,this.path=$,this.body=U,this.credentialSource=D?.source??null,this.credentialTier=D?.tier??null}}function dY(_,$){if(typeof $==="function")return $();return rY(_,$)}function mY(_){let $=`The API key for this request came from ${_.source}`;if(_.deliberate)return`${$} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: `+"falling back here would authenticate as a different principal than the one you named, which is exactly the failure an override exists to prevent. Rotate that key, or unset the override to use the credential on disk.";if(_.deprecated){let g=_.diskCandidates[0],U=g?`Write the CURRENT key to ${g} \u2014 that file is re-read on every call, so rotations take `+`effect immediately and in every shell. Do not simply unset ${_.source}: nothing was found on disk, so that would leave this client with no credential at all.`:"This environment has no HOME, so no credential file could be consulted; the disk tier is unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.";return`${$}, a variable in this process's environment \u2014 which is a snapshot taken when the process `+`started. A STALE SHELL is the most common cause of this error: this shell exported the key before it was rotated, and will keep sending the old one until it exits. ${U}`}return`${$}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. `+"The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution so this machine gets the current key."}var iY=[408,425,429,500,502,503,504],lY=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),tY=new Set(["host",":authority","forwarded","x-forwarded-host","x-original-host"]);function xz(_,$){if(!_)return;let g=Object.keys(_).find((U)=>tY.has(U.trim().toLowerCase()));if(g)throw Error(`Authenticated ${$} headers must not set authority header '${g}'.`)}function oY(_,$){if(!$)return _;let g=$ instanceof URLSearchParams?$:new URLSearchParams;if(!($ instanceof URLSearchParams))for(let[D,I]of Object.entries($)){if(I===null||I===void 0)continue;if(Array.isArray(I))for(let j of I)g.append(D,String(j));else g.append(D,String(I))}let U=g.toString();if(!U)return _;return`${_}${_.includes("?")?"&":"?"}${U}`}var pY=(_)=>new Promise(($)=>setTimeout($,_));function eY(_){let $=_.fetchImpl??((A,L)=>fetch(A,L)),g=iz(_.baseUrl),U=_.timeoutMs??30000,D=_.sleepImpl??pY,I=_.retry;function j(A){let L=A!==void 0?A:I;if(L===!1)return null;let z=L??{};return{retries:z.retries??2,baseDelayMs:z.baseDelayMs??200,maxDelayMs:z.maxDelayMs??2000,retryStatuses:z.retryStatuses??[...iY]}}async function N(A,L,z,W,J,P){xz(_.headers,"transport"),xz(J.headers,"request");let S={"x-api-key":P.apiKey,Authorization:`Bearer ${P.apiKey}`,Accept:"application/json",..._.headers??{},...J.headers??{}};if(J.idempotencyKey)S["Idempotency-Key"]=J.idempotencyKey;let X={method:A,headers:S,redirect:"manual"};if(W!==void 0)S["Content-Type"]="application/json",X.body=JSON.stringify(W);let G=new AbortController,R=()=>G.abort();if(J.signal)if(J.signal.aborted)G.abort();else J.signal.addEventListener("abort",R,{once:!0});let K=setTimeout(()=>G.abort(),J.timeoutMs??U);X.signal=G.signal;let Q;try{Q=await $(z,X)}catch(V){let Z=V instanceof Error?V:Error(String(V));if(J.signal?.aborted)return{ok:!1,retryable:!1,error:Z};return{ok:!1,retryable:!0,error:Z}}finally{if(clearTimeout(K),J.signal)J.signal.removeEventListener("abort",R)}let T=await Q.text(),q=void 0;if(T.length>0)try{q=JSON.parse(T)}catch{q=T}if(!Q.ok){if(Q.status>=300&&Q.status<400)return{ok:!1,retryable:!1,error:new O0(A,L,Q.status,q)};if(Q.status===401||Q.status===403)return{ok:!1,retryable:!1,error:new O0(A,L,Q.status,q,{source:P.source,tier:P.tier,guidance:mY(P)})};let V=j(J.retry);return{ok:!1,retryable:V?V.retryStatuses.includes(Q.status):!1,error:new O0(A,L,Q.status,q)}}return{ok:!0,value:q}}async function O(A,L,z,W={}){let J=A.toUpperCase(),P=oY(L.startsWith("/")?L:`/${L}`,W.query),S=`${g}${P}`,X=j(W.retry),G=lY.has(J)||Boolean(W.idempotencyKey),R=X&&G?X.retries+1:1,K=dY(_.name,_.apiKey),Q=null;for(let T=1;T<=R;T++){let q=await N(J,P,S,z,W,K);if(q.ok)return q.value;if(Q=q,!(X!==null&&G&&q.retryable&&TO("GET",A,void 0,L),post:(A,L,z)=>O("POST",A,L,z),put:(A,L,z)=>O("PUT",A,L,z),patch:(A,L,z)=>O("PATCH",A,L,z),del:(A,L,z)=>O("DELETE",A,L,z)}}function aY(_,$=process.env,g){let U=g?.credentials,D=nY(_,$,{...U?{credentials:U}:{}});if(D.misconfigured)throw Error(D.warning??`Client for '${_}' is misconfigured for the API client.`);if(D.transport==="sqlite"||!D.baseUrl)return{transport:"sqlite",client:null,resolution:D};let I=()=>{let j=cN(_,$,U);if(!j)throw Error(`Client for '${_}' resolved to the http transport but no API key is available any more. Looked at ${lz(_,$)}, then the environment. A credential file that was removed after this client was built is the usual cause.`);return j};return{transport:"http",client:eY({name:_,baseUrl:D.baseUrl,apiKey:I,...g?.fetchImpl?{fetchImpl:g.fetchImpl}:{},...g?.headers?{headers:g.headers}:{},...g?.timeoutMs?{timeoutMs:g.timeoutMs}:{},...g?.retry!==void 0?{retry:g.retry}:{},...g?.sleepImpl?{sleepImpl:g.sleepImpl}:{}}),resolution:D}}function nN(_){let $=_.replace(/^\/+|\/+$/g,"");if(!$)throw Error("resource must be a non-empty path segment");return`/${$}`}function hN(_,$){if($===void 0||$===null||`${$}`.length===0)throw Error("id must be a non-empty string");return`${nN(_)}/${encodeURIComponent(String($))}`}function sY(){let _=globalThis;if(_.crypto?.randomUUID)return _.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function _Q(_){if(Array.isArray(_))return _;if(_&&typeof _==="object"){let $=_;for(let g of["items","data","results","rows","records"])if(Array.isArray($[g]))return $[g]}return[]}function $Q(_){if(_&&typeof _==="object"){let $=_;for(let g of["total","count","totalCount","total_count"])if(typeof $[g]==="number")return $[g]}return null}function gQ(_){if(_&&typeof _==="object"){let $=_;for(let g of["cursor","nextCursor","next_cursor","next"])if(typeof $[g]==="string")return $[g]}return null}function DQ(_,$){return{name:_,baseUrl:$.baseUrl,transport:$,async list(g,U={}){let D=await $.get(nN(g),U);return{items:_Q(D),total:$Q(D),cursor:gQ(D),raw:D}},async get(g,U,D={}){try{return await $.get(hN(g,U),D)}catch(I){if(I instanceof O0&&I.status===404)return null;throw I}},async create(g,U,D={}){let{idempotencyKey:I,...j}=D;return $.post(nN(g),U,{...j,idempotencyKey:I??sY()})},async update(g,U,D,I={}){let{method:j="PATCH",idempotencyKey:N,...O}=I;return(j==="PUT"?$.put:$.patch)(hN(g,U),D,{...O,...N?{idempotencyKey:N}:{}})},async delete(g,U,D={}){try{await $.del(hN(g,U),void 0,D)}catch(I){if(I instanceof O0&&I.status===404)return;throw I}}}}function mN(_,$=process.env,g){let U=aY(_,$,g);if(U.transport==="http")return{transport:"http",client:DQ(_,U.client)};return{transport:"sqlite",client:null}}function UQ(_){return _.toUpperCase().replace(/-/g,"_")}function tz(_){let $=UQ(_);return{modeKeys:[`HASNA_${$}_STORAGE_MODE`,`HASNA_${$}_MODE`,`${$}_STORAGE_MODE`,`${$}_MODE`],apiUrlKeys:[`HASNA_${$}_API_URL`,`${$}_API_URL`],apiKeyKeys:[`HASNA_${$}_API_KEY`,`${$}_API_KEY`]}}function rg(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}function CU(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}import $w from"pg";class rU extends Error{scheme;port;constructor(_,$){super(_);this.name="KnowledgeNetworkGuardError",this.scheme=$.scheme,this.port=$.port}}function A0(_=process.env){return(_.NODE_ENV??"").trim().toLowerCase()==="test"}function oz(_){let $=_.split(".");if($.length!==4)return!1;if(!$.every((g)=>/^\d{1,3}$/.test(g)&&Number(g)<=255))return!1;return $[0]==="127"}function OQ(_){let $=_.trim().toLowerCase();if($.length===0)return!1;if($==="localhost"||$.endsWith(".localhost"))return!0;if(oz($))return!0;if(!$.startsWith("[")||!$.endsWith("]"))return!1;let g=$.slice(1,-1);if(g==="::1"||/^(0:){7}1$/.test(g))return!0;let U=g.split(":").pop()??"";if(/^(::ffff:|::)/.test(g)&&oz(U))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(g)}function az(_){if(typeof _==="string")return _;if(_ instanceof URL)return _.href;return _.url}function pz(_,$=process.env){if(!A0($))return;let g=az(_),U;try{U=new URL(g)}catch{throw new rU("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(OQ(U.hostname))return;throw new rU(`knowledge: refused a non-loopback ${U.protocol.replace(":","")} request while NODE_ENV=test (target host withheld on purpose). This process resolved to the cloud backend under test, which means a read or write was about to leave the machine and reach the live store. Select the mode explicitly (HASNA_KNOWLEDGE_STORAGE_MODE=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:U.protocol.replace(":",""),port:U.port})}var AQ=new Set([301,302,303,307,308]),ez=5;function LQ(_,$){if($?.method)return $.method.toUpperCase();if(typeof _!=="string"&&!(_ instanceof URL))return _.method.toUpperCase();return"GET"}async function vU(_,$){if(pz(_),!A0()||$?.redirect!==void 0)return fetch(_,$);let g=az(_),U=LQ(_,$),D=$?.body,I=await fetch(_,{...$??{},redirect:"manual"});for(let j=0;AQ.has(I.status);j++){let N=I.headers.get("location");if(!N)return I;let O=new URL(N,g).href;if(pz(O),j>=ez){let L=new URL(O);throw new rU(`knowledge: refused to follow more than ${ez} redirects while NODE_ENV=test (target host withheld on purpose). Under test the guard follows redirects itself so every hop is checked, and a chain this long is a loop, not a route.`,{scheme:L.protocol.replace(":",""),port:L.port})}if(I.status===303||(I.status===301||I.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",D=void 0;let A={...$??{},method:U,redirect:"manual"};if(D===void 0)delete A.body;else A.body=D;I=await fetch(O,A),g=O}return I}var wU="knowledge",iN=tz(wU),o$=iN.modeKeys,uU=iN.apiUrlKeys,xU=iN.apiKeyKeys;function fU(_,$){return $.filter((g)=>(_[g]??"").trim().length>0)}function vg(_=process.env){let $=[...fU(_,uU),...fU(_,xU)],g=o$[0];for(let U of o$){let D=_[U]?.trim();if(!D)continue;let I;try{I=CU(D)}catch(N){let O=N instanceof Error?N.message:String(N);throw Error(`knowledge: ${U}=${D} is not a valid mode. ${O}`)}let j=[];if(U!==g)j.push(`Using alias env ${U}; the canonical key is ${g}.`);if(I.mode==="sqlite"&&$.length>0)j.push(`${U}=sqlite pins the on-box store; ${$.join(", ")} are set but ignored.`);return{mode:I.mode,source:{kind:"env",name:U,value:D},pointer_env_present:$,pointer_ignored:I.mode==="sqlite"&&$.length>0,warning:j.length>0?j.join(" "):null}}return{mode:"sqlite",source:{kind:"default",name:null,value:null},pointer_env_present:$,pointer_ignored:$.length>0,warning:$.length>0?`${$.join(", ")} are set but do NOT select a backend: mode is sqlite by default. Set ${g}=postgres to route reads and writes to the API, or unset those vars to silence this note.`:null}}var JQ=["postgres"],PQ=["sqlite"],sz=new Map;function _S(_,$,g){let U=$===rg;if(U){let D=sz.get(_);if(D!==void 0)return D}for(let D of _)try{if($(D),U)sz.set(_,D);return D}catch{}throw Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts (tried ${_.join(", ")}). The storage-mode enum has changed; add the new token to ${g} in src/knowledge-mode.ts.`)}function zQ(_=rg){return _S(JQ,_,"SERVER_MODE_CANDIDATES")}function SQ(_=rg){return _S(PQ,_,"LOCAL_MODE_CANDIDATES")}function WQ(_,$=rg){return _==="postgres"?zQ($):SQ($)}function lN(_,$){return{..._,[o$[0]]:WQ($)}}class $S extends Error{code="knowledge_mode_unset_with_api_url";constructor(_){let $=o$[0];super(`knowledge: ${_.join(", ")} names an API store, but no mode variable says to use it, so this command would silently read and write the on-box store instead. Set ${$}=postgres to use the API, or ${$}=sqlite to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function gS(_=process.env,$={}){let g=vg(_);if($.storePathOverridden)return g;if(g.source.kind!=="default")return g;let U=fU(_,uU);if(U.length===0)return g;throw new $S(U)}function DS(_=process.env){let $=vg(_);return{...$,store_transport:$.mode==="postgres"?"api":"local",api_key_present:fU(_,xU).length>0,network_guard_active:A0(_)}}function US(_){return{fetchImpl:vU,...A0(_)?{retry:!1}:{}}}var G6="notes";class IS extends Error{expected;current;code="version_conflict";constructor(_,$){super(`version_conflict: this edit was written against version ${_} but the stored entry is now at version ${$}. Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions.`);this.expected=_;this.current=$;this.name="KnowledgeVersionConflictError"}}function XQ(_){let $={};if(_.search)$.search=_.search;if(_.limit!==void 0)$.limit=_.limit;if(_.offset!==void 0)$.offset=_.offset;if(_.includeArchived||_.archivedOnly)$.includeArchived=!0;return $}function RQ(_){return{baseUrl:_.baseUrl,async list($={}){let g=$.limit??200,U=XQ({...$,limit:Math.min(Math.max(g,1),200)}),D=await _.list(G6,{query:U}),I=D.items;if($.archivedOnly)I=I.filter((j)=>j.archived===!0);if($.tag){let j=$.tag.toLowerCase();I=I.filter((N)=>(N.tags??[]).some((O)=>O.toLowerCase()===j))}return{items:I,total:D.total}},async get($){return _.get(G6,$)},async create($){return _.create(G6,{...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})},async update($,g,U={}){try{return await _.update(G6,$,g,{...U.expectedVersion!==void 0?{headers:{"if-match":String(U.expectedVersion)}}:{}})}catch(D){if(tN(D))return null;let I=GQ(D);if(I)throw I;throw D}},async delete($){let g=await _.get(G6,$);if(!g)return!1;return await _.delete(G6,g.id),!0},async listVersions($,g={}){try{return await _.transport.get(`/${G6}/${encodeURIComponent($)}/versions`,{query:{limit:g.limit,offset:g.offset}})}catch(U){if(tN(U))return null;throw U}},async getVersion($,g){try{return await _.transport.get(`/${G6}/${encodeURIComponent($)}/versions/${g}`)}catch(U){if(tN(U))return null;throw U}}}}function GQ(_){if(!_||typeof _!=="object")return null;if(_.status!==409)return null;let $=_.body,U=(typeof $==="string"?YQ($):$)??{};if(U.error!=="version_conflict")return null;return new IS(Number(U.expected??0),Number(U.current??0))}function YQ(_){try{return JSON.parse(_)}catch{return null}}function tN(_){return Boolean(_&&typeof _==="object"&&_.status===404)}function fg(_=process.env){if(vg(_).mode!=="postgres")return null;let $=mN(wU,lN(_,"postgres"),US(_));if($.transport!=="http")return null;return RQ($.client)}function Y6(_=process.env){if(vg(_).mode!=="postgres")return!1;return mN(wU,lN(_,"postgres"),US(_)).transport==="http"}async function yU(_){let g=[];for(let U=0;;U+=200){let{items:D}=await _.list({includeArchived:!0,limit:200,offset:U});if(g.push(...D),D.length<200)break;if(U>1e5)break}return g}class pN extends Error{location;code="version_history_unsupported";constructor(_){super(`Version history is not kept by the local JSON knowledge store (${_}). It has no version line, so an empty history here would be a claim, not a measurement. Entry versioning lives in the Postgres-backed store: point this CLI at it (HASNA_KNOWLEDGE_STORAGE_MODE=postgres plus the API url/key) and re-run.`);this.location=_;this.name="VersionHistoryUnsupportedError"}}function oN(_,$){return _.id===$||_.short_id===$}class jS{storePath;kind="local";supportsVersions=!1;constructor(_){this.storePath=_}async listVersions(){throw new pN(this.storePath)}async getVersion(){throw new pN(this.storePath)}get location(){return this.storePath}get exists(){return QQ(this.storePath)}async listAll(){let _=I0(this.storePath);return{items:_.items,exists:_.exists}}async get(_){return I0(this.storePath).items.find((g)=>oN(g,_))??null}async create(_){return v$(this.storePath,()=>{let $=kg(this.storePath),g=new Date().toISOString(),U=_.id??Hz(),D={id:U,short_id:kz(U),title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:!1,created_at:g,updated_at:g};return $.items.push(D),t$(this.storePath,$),D},{createParent:!0})}async update(_,$){return v$(this.storePath,()=>{let g=kg(this.storePath),U=g.items.findIndex((I)=>oN(I,_));if(U===-1)return null;let D=g.items[U];if($.title!==void 0)D.title=$.title;if($.content!==void 0)D.content=$.content;if($.url!==void 0)D.url=$.url;if($.tags!==void 0)D.tags=$.tags;if($.metadata!==void 0)D.metadata=$.metadata;if($.archived!==void 0)D.archived=$.archived;return D.updated_at=new Date().toISOString(),g.items[U]=D,t$(this.storePath,g),D},{createParent:!0})}async delete(_){return v$(this.storePath,()=>{let $=kg(this.storePath),g=$.items.length;$.items=$.items.filter((D)=>!oN(D,_));let U=g!==$.items.length;if(U)t$(this.storePath,$);return U},{createParent:!0})}async deleteMany(_){if(_.length===0)return 0;let $=new Set(_);return v$(this.storePath,()=>{let g=kg(this.storePath),U=g.items.length;g.items=g.items.filter((I)=>!$.has(I.id)&&!(I.short_id!=null&&$.has(I.short_id)));let D=U-g.items.length;if(D>0)t$(this.storePath,g);return D},{createParent:!0})}}class NS{cloud;kind="api";exists=!0;supportsVersions=!0;constructor(_){this.cloud=_}async listVersions(_,$={}){return this.cloud.listVersions(_,$)}async getVersion(_,$){return this.cloud.getVersion(_,$)}get location(){return this.cloud.baseUrl}async listAll(){return{items:await yU(this.cloud),exists:!0}}async get(_){return this.cloud.get(_)}async create(_){return this.cloud.create({..._.id?{id:_.id}:{},title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],..._.metadata?{metadata:_.metadata}:{}})}async update(_,$,g={}){return this.cloud.update(_,$,{expectedVersion:g.expectedVersion})}async delete(_){return this.cloud.delete(_)}async deleteMany(_){let $=0;for(let g of _)if(await this.cloud.delete(g))$+=1;return $}}function hU(_){let $=_.storePathOverridden?null:fg(_.env??process.env);if($)return new NS($);return new jS(_.storePath)}function ES(_){let $=_??"";if($==="")return[];return $.replace(/\n$/,"").split(` +`)}var eN=5000;function TQ(_,$){let g=ES(_),U=ES($);if(g.length>eN||U.length>eN)throw Error(`Refusing to line-diff ${Math.max(g.length,U.length)} lines (limit ${eN}). Fetch the two versions and diff them with a dedicated tool.`);let D=Array.from({length:g.length+1},()=>Array(U.length+1).fill(0));for(let O=g.length-1;O>=0;O-=1)for(let A=U.length-1;A>=0;A-=1)D[O][A]=g[O]===U[A]?D[O+1][A+1]+1:Math.max(D[O+1][A],D[O][A+1]);let I=[],j=0,N=0;while(j=D[j][N+1])I.push({op:"remove",from_line:j+1,to_line:null,text:g[j]}),j+=1;else I.push({op:"add",from_line:null,to_line:N+1,text:U[N]}),N+=1;while(j{if(!qQ(_[N],$[N]))g.push({field:N,from:_[N]??null,to:$[N]??null})};U("title"),U("url"),U("tags"),U("metadata"),U("archived");let D=TQ(_.content,$.content),I=D.filter((N)=>N.op==="add").length,j=D.filter((N)=>N.op==="remove").length;return{identical:g.length===0&&I===0&&j===0,fields:g,content:D,added:I,removed:j}}function AS(_,$,g){let U=[`--- ${$}`,`+++ ${g}`];if(_.identical)return U.push("(no changes)"),U.join(` +`);for(let D of _.fields)U.push(`~ ${D.field}: ${JSON.stringify(D.from)} -> ${JSON.stringify(D.to)}`);if(_.added===0&&_.removed===0){if(_.fields.length>0)U.push("(content unchanged)")}else{U.push(`@@ content +${_.added} -${_.removed} @@`);for(let D of _.content){let I=D.op==="add"?"+":D.op==="remove"?"-":" ";U.push(`${I}${D.text}`)}}return U.join(` +`)}import{Database as LS}from"bun:sqlite";function cU(_="catalog"){if(Y6()){let $=o$[0];throw Error(`knowledge: ${_} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${$}=local `+"(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see "+"which variable selected the current backend.")}}var BQ="porter unicode61 remove_diacritics 2",JS=` PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; @@ -265,7 +266,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (1, datetime('now')); -`,SS=` +`,KQ=` DROP TABLE IF EXISTS chunks_fts; CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( @@ -278,7 +279,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (2, datetime('now')); -`,ZS=` +`,VQ=` CREATE TABLE IF NOT EXISTS audit_events ( id TEXT PRIMARY KEY, event_type TEXT NOT NULL, @@ -309,7 +310,7 @@ CREATE INDEX IF NOT EXISTS idx_approval_gates_status ON approval_gates(status); INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (3, datetime('now')); -`,vS=` +`,FQ=` CREATE TABLE IF NOT EXISTS vector_index_entries ( id TEXT PRIMARY KEY, chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, @@ -340,7 +341,7 @@ CREATE INDEX IF NOT EXISTS idx_vector_index_status ON vector_index_entries(statu INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (4, datetime('now')); -`,yS=` +`,MQ=` CREATE TABLE IF NOT EXISTS reindex_queue ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, @@ -361,7 +362,7 @@ CREATE INDEX IF NOT EXISTS idx_reindex_queue_source_uri ON reindex_queue(source_ INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (5, datetime('now')); -`,J3=` +`,PS=` CREATE TABLE IF NOT EXISTS knowledge_machines ( machine_id TEXT PRIMARY KEY, hostname TEXT, @@ -436,7 +437,7 @@ CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON knowledge_sync_conflicts INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (6, datetime('now')); -`,hS=` +`,ZQ=` CREATE TABLE IF NOT EXISTS knowledge_sync_table_clocks ( table_name TEXT NOT NULL, machine_id TEXT NOT NULL, @@ -476,7 +477,7 @@ CREATE INDEX IF NOT EXISTS idx_sync_imports_status ON knowledge_sync_imports(sta INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (7, datetime('now')); -`,mS=` +`,bQ=` CREATE INDEX IF NOT EXISTS idx_wiki_pages_lifecycle_status ON wiki_pages(status, valid_to); CREATE INDEX IF NOT EXISTS idx_wiki_pages_last_verified ON wiki_pages(last_verified_at); CREATE INDEX IF NOT EXISTS idx_wiki_pages_supersedes ON wiki_pages(supersedes); @@ -484,7 +485,7 @@ CREATE INDEX IF NOT EXISTS idx_wiki_pages_superseded_by ON wiki_pages(superseded INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (8, datetime('now')); -`,xS=` +`,HQ=` BEGIN; CREATE TEMP TABLE _chunks_fts_backup AS @@ -497,7 +498,7 @@ CREATE VIRTUAL TABLE chunks_fts USING fts5( text, title, source_uri, - tokenize='${TS}' + tokenize='${BQ}' ); INSERT INTO chunks_fts (chunk_id, text, title, source_uri) @@ -509,7 +510,7 @@ INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now')); COMMIT; -`,uS=` +`,kQ=` CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( id TEXT PRIMARY KEY, record_kind TEXT NOT NULL, @@ -570,14 +571,14 @@ CREATE INDEX IF NOT EXISTS idx_durable_records_validity INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (10, datetime('now')); -`;function m($){h9("opening the local knowledge.db catalog"),G0($);let _=new $3($);return _.exec("PRAGMA foreign_keys = ON;"),_.exec("PRAGMA busy_timeout = 5000;"),_}function W3($){return h9("reading the local knowledge.db catalog"),new $3($,{readonly:!0})}function a($){let _=m($);try{if(_.exec(_3),b_(_)<2)_.exec(SS);if(b_(_)<3)_.exec(ZS);if(b_(_)<4)_.exec(vS);if(b_(_)<5)_.exec(yS);if(b_(_)<6)_.exec(J3);if(dS(_))nS(_);if(cS(_))iS(_);if(lS(_))rS(_);if(pS(_))oS(_);return{path:$,schema_version:b_(_)}}finally{_.close()}}function b_($){return $.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function H_($,_){return $.query(`SELECT COUNT(*) AS n FROM ${_}`).get()?.n??0}function KQ($){return`"${$.replaceAll('"','""')}"`}function m4($,_){let J=$.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get(_);return Boolean(J)}function h4($,_,J){if(!m4($,_))return!1;return $.query(`PRAGMA table_info(${KQ(_)})`).all().some((W)=>W.name===J)}function F0($,_,J,U){if(!h4($,_,J))$.exec(`ALTER TABLE ${KQ(_)} ADD COLUMN ${KQ(J)} ${U};`)}function dS($){return b_($)<7||!h4($,"knowledge_sync_changes","logical_clock")||!h4($,"knowledge_sync_changes","bundle_id")||!m4($,"knowledge_sync_table_clocks")||!m4($,"knowledge_sync_imports")}function nS($){if(!m4($,"knowledge_sync_changes"))$.exec(J3);F0($,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),F0($,"knowledge_sync_changes","bundle_id","TEXT"),$.exec(hS)}function cS($){return b_($)<8||!h4($,"wiki_pages","valid_from")||!h4($,"wiki_pages","valid_to")||!h4($,"wiki_pages","supersedes")||!h4($,"wiki_pages","superseded_by")||!h4($,"wiki_pages","confidence")||!h4($,"wiki_pages","last_verified_at")}function iS($){if(!m4($,"wiki_pages"))$.exec(_3);F0($,"wiki_pages","valid_from","TEXT"),F0($,"wiki_pages","valid_to","TEXT"),F0($,"wiki_pages","supersedes","TEXT"),F0($,"wiki_pages","superseded_by","TEXT"),F0($,"wiki_pages","confidence","REAL"),F0($,"wiki_pages","last_verified_at","TEXT"),$.exec(` +`;function v(_){cU("opening the local knowledge.db catalog"),X6(_);let $=new LS(_);return $.exec("PRAGMA foreign_keys = ON;"),$.exec("PRAGMA busy_timeout = 5000;"),$}function zS(_){return cU("reading the local knowledge.db catalog"),new LS(_,{readonly:!0})}function h(_){let $=v(_);try{if($.exec(JS),v_($)<2)$.exec(KQ);if(v_($)<3)$.exec(VQ);if(v_($)<4)$.exec(FQ);if(v_($)<5)$.exec(MQ);if(v_($)<6)$.exec(PS);if(CQ($))rQ($);if(vQ($))fQ($);if(wQ($))uQ($);if(xQ($))yQ($);return{path:_,schema_version:v_($)}}finally{$.close()}}function v_(_){return _.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function F_(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function aN(_){return`"${_.replaceAll('"','""')}"`}function e$(_,$){let g=_.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get($);return Boolean(g)}function p$(_,$,g){if(!e$(_,$))return!1;return _.query(`PRAGMA table_info(${aN($)})`).all().some((D)=>D.name===g)}function Q6(_,$,g,U){if(!p$(_,$,g))_.exec(`ALTER TABLE ${aN($)} ADD COLUMN ${aN(g)} ${U};`)}function CQ(_){return v_(_)<7||!p$(_,"knowledge_sync_changes","logical_clock")||!p$(_,"knowledge_sync_changes","bundle_id")||!e$(_,"knowledge_sync_table_clocks")||!e$(_,"knowledge_sync_imports")}function rQ(_){if(!e$(_,"knowledge_sync_changes"))_.exec(PS);Q6(_,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),Q6(_,"knowledge_sync_changes","bundle_id","TEXT"),_.exec(ZQ)}function vQ(_){return v_(_)<8||!p$(_,"wiki_pages","valid_from")||!p$(_,"wiki_pages","valid_to")||!p$(_,"wiki_pages","supersedes")||!p$(_,"wiki_pages","superseded_by")||!p$(_,"wiki_pages","confidence")||!p$(_,"wiki_pages","last_verified_at")}function fQ(_){if(!e$(_,"wiki_pages"))_.exec(JS);Q6(_,"wiki_pages","valid_from","TEXT"),Q6(_,"wiki_pages","valid_to","TEXT"),Q6(_,"wiki_pages","supersedes","TEXT"),Q6(_,"wiki_pages","superseded_by","TEXT"),Q6(_,"wiki_pages","confidence","REAL"),Q6(_,"wiki_pages","last_verified_at","TEXT"),_.exec(` UPDATE wiki_pages SET valid_from = COALESCE(valid_from, created_at), last_verified_at = COALESCE(last_verified_at, updated_at), confidence = COALESCE(confidence, 0.8) WHERE valid_from IS NULL OR last_verified_at IS NULL OR confidence IS NULL; - `),$.exec(mS)}function U3($){let _=$.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean(_?.sql&&_.sql.includes("remove_diacritics"))}function lS($){if(!m4($,"chunks_fts"))return!1;return b_($)<9||!U3($)}function rS($){if(!m4($,"chunks_fts"))return;if(U3($)){$.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}$.exec(xS)}function pS($){return b_($)<10||!m4($,"knowledge_promotion_candidates")||!m4($,"durable_knowledge_records")}function oS($){$.exec(uS)}function FQ($){let _=m($);try{return{schema_version:b_(_),sources:H_(_,"sources"),source_revisions:H_(_,"source_revisions"),chunks:H_(_,"chunks"),wiki_pages:H_(_,"wiki_pages"),citations:H_(_,"citations"),indexes:H_(_,"knowledge_indexes"),runs:H_(_,"runs"),run_events:H_(_,"run_events"),redaction_findings:H_(_,"redaction_findings"),audit_events:H_(_,"audit_events"),approval_gates:H_(_,"approval_gates"),storage_objects:H_(_,"storage_objects"),embeddings:H_(_,"chunk_embeddings"),vector_entries:H_(_,"vector_index_entries"),reindex_queue:H_(_,"reindex_queue"),knowledge_machines:H_(_,"knowledge_machines"),sync_snapshots:H_(_,"knowledge_sync_snapshots"),sync_changes:H_(_,"knowledge_sync_changes"),sync_conflicts:H_(_,"knowledge_sync_conflicts"),sync_table_clocks:H_(_,"knowledge_sync_table_clocks"),sync_imports:H_(_,"knowledge_sync_imports"),promotion_candidates:H_(_,"knowledge_promotion_candidates"),durable_records:H_(_,"durable_knowledge_records")}}finally{_.close()}}import{chmodSync as tS,existsSync as aS,mkdirSync as X3,readFileSync as sS,statSync as eS,writeFileSync as $Z}from"fs";import{dirname as _Z,join as EQ,relative as JZ,sep as WZ}from"path";import{pathToFileURL as UZ}from"url";function z4($){let _=$.replace(/\\/g,"/").trim();if(!_||_.startsWith("/"))throw Error(`Invalid artifact key: ${$}`);let J=_.split("/").filter(Boolean);if(J.length===0||J.some((U)=>U==="."||U===".."))throw Error(`Invalid artifact key: ${$}`);return J.join("/")}function MQ($,_){let J=JZ($,_);if(J.startsWith("..")||J===".."||J.startsWith(`..${WZ}`))throw Error(`Artifact path escapes root: ${_}`)}function XZ($){if(!$)return;let _={};for(let[J,U]of Object.entries($))if(typeof U==="string")_[J]=U;else if(typeof U==="number"||typeof U==="boolean")_[J]=String(U);return Object.keys(_).length>0?_:void 0}class G3{root;type="local";canRead=!0;canWrite=!0;constructor($){this.root=$;X3($,{recursive:!0,mode:448})}async put($){let _=z4($.key),J=EQ(this.root,_);return MQ(this.root,J),X3(_Z(J),{recursive:!0,mode:448}),$Z(J,$.body,{mode:384}),tS(J,384),{key:_,uri:UZ(J).href,modified_at:eS(J).mtime.toISOString()}}async getText($){let _=z4($),J=EQ(this.root,_);return MQ(this.root,J),sS(J,"utf8")}async exists($){let _=z4($),J=EQ(this.root,_);return MQ(this.root,J),aS(J)}}class Y3{options;type="s3";canRead=!0;canWrite=!0;client;constructor($){this.options=$;this.client=$.client}async getClient(){if(this.client)return this.client;let[{S3Client:$},{fromIni:_}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]);return this.client=new $({region:this.options.region,credentials:this.options.profile?_({profile:this.options.profile}):void 0,maxAttempts:this.options.max_attempts}),this.client}objectKey($){let _=z4($),J=this.options.prefix?z4(this.options.prefix):"";return J?`${J}/${_}`:_}async put($){let[{PutObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=z4($.key),W=this.objectKey(U);return await J.send(new _({Bucket:this.options.bucket,Key:W,Body:$.body,ContentType:$.content_type,Metadata:XZ($.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:U,uri:`s3://${this.options.bucket}/${W}`,modified_at:new Date().toISOString()}}async getText($){let[{GetObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey($),W=await J.send(new _({Bucket:this.options.bucket,Key:U}));if(!W.Body)return"";return await W.Body.transformToString()}async exists($){let[{HeadObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey($);try{return await J.send(new _({Bucket:this.options.bucket,Key:U})),!0}catch(W){let X=W instanceof Error?W.name:"";if(X==="NotFound"||X==="NoSuchKey"||X==="NotFoundError")return!1;throw W}}}function AQ($,_){if($.storage.type==="s3"){if(!$.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new Y3({bucket:$.storage.s3.bucket,prefix:$.storage.s3.prefix,region:$.storage.s3.region,profile:$.storage.s3.profile,max_attempts:$.storage.s3.max_attempts,server_side_encryption:$.storage.s3.server_side_encryption,kms_key_id:$.storage.s3.kms_key_id})}return new G3(_.artifactsDir)}import{createHash as pX}from"crypto";import{spawnSync as en}from"child_process";import{existsSync as e$,readFileSync as $c}from"fs";import{hostname as _c}from"os";import{join as FE,resolve as ZE}from"path";import{createHash as Cv,randomUUID as Pv}from"crypto";import{createHash as LZ,randomUUID as BZ}from"crypto";import{existsSync as wQ,readdirSync as HZ}from"fs";import{join as B3}from"path";import{pathToFileURL as NZ}from"url";import{existsSync as GZ,mkdirSync as YZ,readFileSync as QZ,unlinkSync as qZ,writeFileSync as zZ}from"fs";import{homedir as jZ}from"os";import{dirname as DZ,join as Q3}from"path";var bQ="https://knowledge.md";function x4($){let _=new URL($);if(_.protocol!=="http:"&&_.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let J=_.pathname.replace(/\/+$/,"");if(J==="/api"||J==="/api/v1")_.pathname="/";else if(J.endsWith("/api/v1"))_.pathname=J.slice(0,-7)||"/";else if(J.endsWith("/api"))_.pathname=J.slice(0,-4)||"/";return _.toString().replace(/\/+$/,"")}function m9($=process.env){if($.HASNA_KNOWLEDGE_AUTH_PATH)return $.HASNA_KNOWLEDGE_AUTH_PATH;let _=$.HASNA_KNOWLEDGE_AUTH_DIR??Q3(jZ(),".hasna","knowledge");return Q3(_,"auth.json")}function q3($,_=process.env){return x4(_.KNOWLEDGE_API_URL??$?.hosted?.api_url??bQ)}function z3($=process.env){try{let _=m9($);if(!GZ(_))return null;let J=JSON.parse(QZ(_,"utf8"));return typeof J.api_key==="string"&&J.api_key.length>0?J:null}catch{return null}}function j3($,_=process.env){let J=m9(_),U={...$,api_url:$.api_url?x4($.api_url):void 0,created_at:$.created_at??new Date().toISOString()};return YZ(DZ(J),{recursive:!0,mode:448}),zZ(J,`${JSON.stringify(U,null,2)} -`,{mode:384}),U}function D3($=process.env){try{return qZ(m9($)),!0}catch{return!1}}function OZ($=process.env){if($.KNOWLEDGE_API_KEY)return{apiKey:$.KNOWLEDGE_API_KEY,source:"env"};if($.HASNA_KNOWLEDGE_API_KEY)return{apiKey:$.HASNA_KNOWLEDGE_API_KEY,source:"env"};let _=z3($);return _?.api_key?{apiKey:_.api_key,source:"file"}:{apiKey:null,source:"none"}}function O3($,_=process.env){let J=z3(_),U=OZ(_),W=_.KNOWLEDGE_API_URL?q3($,_):J?.api_url?x4(J.api_url):q3($,_);return{authenticated:Boolean(U.apiKey),source:U.source,api_url:W,auth_path:m9(_),email:U.source==="file"?J?.email??null:null,org_id:U.source==="file"?J?.org_id??null:null,org_slug:U.source==="file"?J?.org_slug??null:null,user_id:U.source==="file"?J?.user_id??null:null,api_key_present:Boolean(U.apiKey)}}var L3=2;var H3=[{kind:"schema",prefix:"schemas/",description:"Machine-readable agent schemas and source rules."},{kind:"index",prefix:"indexes/",description:"Small orientation indexes and future shard manifests."},{kind:"log",prefix:"logs/",description:"Append-only JSONL run and wiki-maintenance log partitions."},{kind:"run",prefix:"runs/",description:"Prompt/tool/cost ledgers and generated output records."},{kind:"wiki_page",prefix:"wiki/",description:"Generated cited Markdown pages, not raw source files."},{kind:"export",prefix:"exports/",description:"Portable exports and snapshots of derived knowledge state."}],VZ=["cloud.env","knowledge.db.pre-cloud-*.bak","db.json.pre-cloud-*.bak","migration-exports"];function N3($){let _=[];if(wQ(B3($.home,"cloud.env")))_.push("cloud.env");if(wQ(B3($.home,"migration-exports")))_.push("migration-exports");if(wQ($.home)){for(let J of HZ($.home))if(/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(J))_.push(J)}return _}function IJ($){let _=typeof $==="string"?Buffer.from($):Buffer.from($);return{hash:`sha256:${LZ("sha256").update(_).digest("hex")}`,size_bytes:_.byteLength}}function V3($){return H3.find((J)=>$.startsWith(J.prefix))?.kind??"artifact"}function x9($,_,J="global"){let U=gQ($,_),W=$.storage.s3??null,X=W?.prefix?.replace(/^\/+|\/+$/g,"")??"",G=W?`s3://${W.bucket}/${X?`${X}/`:""}`:"",Y=r$.s3.prefix.replace(/^\/+|\/+$/g,""),Q=`s3://${r$.s3.bucket}/${Y}/`,q=$.storage.type==="s3"&&W?.bucket===r$.s3.bucket&&(W.region??null)===r$.s3.region;return{scope:J,mode:$.mode,storage_type:$.storage.type,workspace_home:_.home,local_layout:{app_path:K4,config_path:_.configPath,json_store_path:_.jsonStorePath,knowledge_db_path:_.knowledgeDbPath,directories:{artifacts:_.artifactsDir,cache:_.cacheDir,exports:_.exportsDir,indexes:_.indexesDir,logs:_.logsDir,runs:_.runsDir,schemas:_.schemasDir,wiki:_.wikiDir}},artifact_store:{type:$.storage.type,artifacts_root:$.storage.artifacts_root,uri_prefix:$.storage.type==="s3"?G:NZ(`${_.artifactsDir}/`).href,s3:W?{bucket:W.bucket,prefix:X,region:W.region??null,profile:W.profile??null,server_side_encryption:W.server_side_encryption??null,kms_key_configured:Boolean(W.kms_key_id)}:null},canonical_example:{division:r$.division,app_type:r$.app_type,app:r$.app,env:r$.env,active:q,local_path:r$.local_path,s3:{bucket:r$.s3.bucket,region:r$.s3.region,profile:r$.s3.profile,prefix:Y,uri_prefix:Q,server_side_encryption:r$.s3.server_side_encryption},secrets:{env:r$.secrets.env,aws:r$.secrets.aws,s3:r$.secrets.s3,rds:r$.secrets.rds,future_rds:r$.secrets.future_rds},evidence_doc:r$.evidence_doc},hosted:{enabled:$.mode==="hosted",api_url:x4($.hosted?.api_url??bQ),api_url_env:"KNOWLEDGE_API_URL",api_key_env:"KNOWLEDGE_API_KEY",auth_storage:"~/.hasna/knowledge/auth.json",registry_contract_version:L3,requires_hosted_account_for_local_use:!1},secret_handling:{workspace_env_files_supported:!1,forbidden_workspace_files:VZ,forbidden_workspace_files_present:N3(_),runtime_env_keys:["HASNA_KNOWLEDGE_STORAGE_MODE","KNOWLEDGE_STORAGE_MODE","HASNA_KNOWLEDGE_DATABASE_URL","KNOWLEDGE_DATABASE_URL"],secret_ref_authority:"open-secrets",approved_secret_refs:{env:r$.secrets.env,aws:r$.secrets.aws,s3:r$.secrets.s3,rds:r$.secrets.rds},db_url_rotation_decision:{status:"blocked_without_secret_authority",reason:"No live secret mutation authority is available in @hasna/knowledge. Rotate the DB URL only through the approved secret authority if separate evidence proves the URL propagated to backups, exports, sync bundles, reports, or copied artifacts.",authority_required:!0}},source_ownership:{owner:"open-files",preferred_ref:$.sources.preferred_ref,allowed_schemes:$.sources.allowed_schemes,raw_source_bytes_stored_in_open_knowledge:!1,stores:["source refs","source revisions and hashes","citation spans","redacted extracted chunks","embeddings","generated wiki artifacts","indexes","run ledgers"],does_not_store:["raw open-files bytes","S3 object credentials","connector secrets","hosted tenant ownership state"]},private_fleet_boundary:{manifest_authority:"open-machines",source_ref_authority:"open-files",secret_ref_authority:"open-secrets",raw_private_manifest_bytes_stored_in_open_knowledge:!1,accepted_source_ref_schemes:$.sources.allowed_schemes.filter((L)=>["open-files","s3","file"].includes(L)),stores:["source refs for private manifests","redacted setup decisions","runbook summaries","citation spans into approved knowledge sources","machine setup evidence hashes"],does_not_store:["private fleet manifests","machine hostnames","machine serial numbers","sudo passwords","VNC passwords","SSH private keys","GitHub App private keys","secret values"],example_manifest_ref:"open-files://source/private-fleet-manifest/path/machines.json"},generated_artifacts:H3,scalability:{catalog:"knowledge.db tracks sources, revisions, chunks, citations, indexes, runs, and storage_objects.",indexes:"Indexes are cataloged DB rows plus sharded artifacts, not one giant index.md.",logs:"Logs use dated JSONL partitions under logs/yyyy/mm/dd.jsonl.",markdown:"Markdown pages are the readable wiki layer over DB/object-store state."},warnings:U.warnings}}function gQ($,_){let J=[],U=[],W=N3(_);for(let X of W)J.push(`Forbidden Knowledge workspace file present: ${X}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`);if(!_.home.endsWith(K4))U.push(`Workspace home does not end with ${K4}: ${_.home}`);if($.storage.type==="s3"){if(!$.storage.s3?.bucket)J.push("storage.s3.bucket is required when storage.type is s3.");if(!$.storage.s3?.prefix)U.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root.");if($.mode==="local")U.push("storage.type is s3 while mode is local; this is valid for BYO S3, but hosted wrappers should set mode to hosted.")}if($.storage.type==="local"&&$.storage.s3)U.push("storage.s3 is configured but ignored while storage.type is local.");if($.sources.preferred_ref!=="open-files")U.push("sources.preferred_ref should stay open-files for durable company knowledge.");if(!$.sources.allowed_schemes.includes("open-files"))J.push("sources.allowed_schemes must include open-files.");if($.mode==="hosted"&&$.hosted?.api_url)try{x4($.hosted.api_url)}catch{J.push("hosted.api_url must be an http(s) URL when mode is hosted.")}return{ok:J.length===0,errors:J,warnings:U}}function u4($,_,J=new Date){let U=J.toISOString(),W=$.prepare(` + `),_.exec(bQ)}function SS(_){let $=_.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean($?.sql&&$.sql.includes("remove_diacritics"))}function wQ(_){if(!e$(_,"chunks_fts"))return!1;return v_(_)<9||!SS(_)}function uQ(_){if(!e$(_,"chunks_fts"))return;if(SS(_)){_.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}_.exec(HQ)}function xQ(_){return v_(_)<10||!e$(_,"knowledge_promotion_candidates")||!e$(_,"durable_knowledge_records")}function yQ(_){_.exec(kQ)}function sN(_){let $=v(_);try{return{schema_version:v_($),sources:F_($,"sources"),source_revisions:F_($,"source_revisions"),chunks:F_($,"chunks"),wiki_pages:F_($,"wiki_pages"),citations:F_($,"citations"),indexes:F_($,"knowledge_indexes"),runs:F_($,"runs"),run_events:F_($,"run_events"),redaction_findings:F_($,"redaction_findings"),audit_events:F_($,"audit_events"),approval_gates:F_($,"approval_gates"),storage_objects:F_($,"storage_objects"),embeddings:F_($,"chunk_embeddings"),vector_entries:F_($,"vector_index_entries"),reindex_queue:F_($,"reindex_queue"),knowledge_machines:F_($,"knowledge_machines"),sync_snapshots:F_($,"knowledge_sync_snapshots"),sync_changes:F_($,"knowledge_sync_changes"),sync_conflicts:F_($,"knowledge_sync_conflicts"),sync_table_clocks:F_($,"knowledge_sync_table_clocks"),sync_imports:F_($,"knowledge_sync_imports"),promotion_candidates:F_($,"knowledge_promotion_candidates"),durable_records:F_($,"durable_knowledge_records")}}finally{$.close()}}import{chmodSync as hQ,existsSync as cQ,mkdirSync as WS,readFileSync as nQ,statSync as dQ,writeFileSync as mQ}from"fs";import{dirname as iQ,join as _E,relative as lQ,sep as tQ}from"path";import{pathToFileURL as oQ}from"url";function f$(_){let $=_.replace(/\\/g,"/").trim();if(!$||$.startsWith("/"))throw Error(`Invalid artifact key: ${_}`);let g=$.split("/").filter(Boolean);if(g.length===0||g.some((U)=>U==="."||U===".."))throw Error(`Invalid artifact key: ${_}`);return g.join("/")}function $E(_,$){let g=lQ(_,$);if(g.startsWith("..")||g===".."||g.startsWith(`..${tQ}`))throw Error(`Artifact path escapes root: ${$}`)}function pQ(_){if(!_)return;let $={};for(let[g,U]of Object.entries(_))if(typeof U==="string")$[g]=U;else if(typeof U==="number"||typeof U==="boolean")$[g]=String(U);return Object.keys($).length>0?$:void 0}class XS{root;type="local";canRead=!0;canWrite=!0;constructor(_){this.root=_;WS(_,{recursive:!0,mode:448})}async put(_){let $=f$(_.key),g=_E(this.root,$);return $E(this.root,g),WS(iQ(g),{recursive:!0,mode:448}),mQ(g,_.body,{mode:384}),hQ(g,384),{key:$,uri:oQ(g).href,modified_at:dQ(g).mtime.toISOString()}}async getText(_){let $=f$(_),g=_E(this.root,$);return $E(this.root,g),nQ(g,"utf8")}async exists(_){let $=f$(_),g=_E(this.root,$);return $E(this.root,g),cQ(g)}}class RS{options;type="s3";canRead=!0;canWrite=!0;client;constructor(_){this.options=_;this.client=_.client}async getClient(){if(this.client)return this.client;let[{S3Client:_},{fromIni:$}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]);return this.client=new _({region:this.options.region,credentials:this.options.profile?$({profile:this.options.profile}):void 0,maxAttempts:this.options.max_attempts}),this.client}objectKey(_){let $=f$(_),g=this.options.prefix?f$(this.options.prefix):"";return g?`${g}/${$}`:$}async put(_){let[{PutObjectCommand:$},g]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=f$(_.key),D=this.objectKey(U);return await g.send(new $({Bucket:this.options.bucket,Key:D,Body:_.body,ContentType:_.content_type,Metadata:pQ(_.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:U,uri:`s3://${this.options.bucket}/${D}`,modified_at:new Date().toISOString()}}async getText(_){let[{GetObjectCommand:$},g]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey(_),D=await g.send(new $({Bucket:this.options.bucket,Key:U}));if(!D.Body)return"";return await D.Body.transformToString()}async exists(_){let[{HeadObjectCommand:$},g]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey(_);try{return await g.send(new $({Bucket:this.options.bucket,Key:U})),!0}catch(D){let I=D instanceof Error?D.name:"";if(I==="NotFound"||I==="NoSuchKey"||I==="NotFoundError")return!1;throw D}}}function gE(_,$){if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new RS({bucket:_.storage.s3.bucket,prefix:_.storage.s3.prefix,region:_.storage.s3.region,profile:_.storage.s3.profile,max_attempts:_.storage.s3.max_attempts,server_side_encryption:_.storage.s3.server_side_encryption,kms_key_id:_.storage.s3.kms_key_id})}return new XS($.artifactsDir)}import{createHash as AU}from"crypto";import{spawnSync as nZ}from"child_process";import{existsSync as W_,readFileSync as dZ}from"fs";import{hostname as mZ}from"os";import{join as kG,resolve as iG}from"path";import{createHash as T7,randomUUID as q7}from"crypto";import{createHash as IT,randomUUID as jT}from"crypto";import{existsSync as UE,readdirSync as NT}from"fs";import{join as VS}from"path";import{pathToFileURL as ET}from"url";import{existsSync as eQ,mkdirSync as aQ,readFileSync as sQ,unlinkSync as _T,writeFileSync as $T}from"fs";import{homedir as gT}from"os";import{dirname as DT,join as GS}from"path";var DE="https://knowledge.md";function a$(_){let $=new URL(_);if($.protocol!=="http:"&&$.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let g=$.pathname.replace(/\/+$/,"");if(g==="/api"||g==="/api/v1")$.pathname="/";else if(g.endsWith("/api/v1"))$.pathname=g.slice(0,-7)||"/";else if(g.endsWith("/api"))$.pathname=g.slice(0,-4)||"/";return $.toString().replace(/\/+$/,"")}function nU(_=process.env){if(_.HASNA_KNOWLEDGE_AUTH_PATH)return _.HASNA_KNOWLEDGE_AUTH_PATH;let $=_.HASNA_KNOWLEDGE_AUTH_DIR??GS(gT(),".hasna","knowledge");return GS($,"auth.json")}function YS(_,$=process.env){return a$($.KNOWLEDGE_API_URL??_?.hosted?.api_url??DE)}function QS(_=process.env){try{let $=nU(_);if(!eQ($))return null;let g=JSON.parse(sQ($,"utf8"));return typeof g.api_key==="string"&&g.api_key.length>0?g:null}catch{return null}}function TS(_,$=process.env){let g=nU($),U={..._,api_url:_.api_url?a$(_.api_url):void 0,created_at:_.created_at??new Date().toISOString()};return aQ(DT(g),{recursive:!0,mode:448}),$T(g,`${JSON.stringify(U,null,2)} +`,{mode:384}),U}function qS(_=process.env){try{return _T(nU(_)),!0}catch{return!1}}function UT(_=process.env){if(_.KNOWLEDGE_API_KEY)return{apiKey:_.KNOWLEDGE_API_KEY,source:"env"};if(_.HASNA_KNOWLEDGE_API_KEY)return{apiKey:_.HASNA_KNOWLEDGE_API_KEY,source:"env"};let $=QS(_);return $?.api_key?{apiKey:$.api_key,source:"file"}:{apiKey:null,source:"none"}}function BS(_,$=process.env){let g=QS($),U=UT($),D=$.KNOWLEDGE_API_URL?YS(_,$):g?.api_url?a$(g.api_url):YS(_,$);return{authenticated:Boolean(U.apiKey),source:U.source,api_url:D,auth_path:nU($),email:U.source==="file"?g?.email??null:null,org_id:U.source==="file"?g?.org_id??null:null,org_slug:U.source==="file"?g?.org_slug??null:null,user_id:U.source==="file"?g?.user_id??null:null,api_key_present:Boolean(U.apiKey)}}var KS=2;var FS=[{kind:"schema",prefix:"schemas/",description:"Machine-readable agent schemas and source rules."},{kind:"index",prefix:"indexes/",description:"Small orientation indexes and future shard manifests."},{kind:"log",prefix:"logs/",description:"Append-only JSONL run and wiki-maintenance log partitions."},{kind:"run",prefix:"runs/",description:"Prompt/tool/cost ledgers and generated output records."},{kind:"wiki_page",prefix:"wiki/",description:"Generated cited Markdown pages, not raw source files."},{kind:"export",prefix:"exports/",description:"Portable exports and snapshots of derived knowledge state."}],OT=["cloud.env","knowledge.db.pre-cloud-*.bak","db.json.pre-cloud-*.bak","migration-exports"];function MS(_){let $=[];if(UE(VS(_.home,"cloud.env")))$.push("cloud.env");if(UE(VS(_.home,"migration-exports")))$.push("migration-exports");if(UE(_.home)){for(let g of NT(_.home))if(/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(g))$.push(g)}return $}function L0(_){let $=typeof _==="string"?Buffer.from(_):Buffer.from(_);return{hash:`sha256:${IT("sha256").update($).digest("hex")}`,size_bytes:$.byteLength}}function ZS(_){return FS.find((g)=>_.startsWith(g.prefix))?.kind??"artifact"}function dU(_,$,g="global"){let U=IE(_,$),D=_.storage.s3??null,I=D?.prefix?.replace(/^\/+|\/+$/g,"")??"",j=D?`s3://${D.bucket}/${I?`${I}/`:""}`:"",N=P_.s3.prefix.replace(/^\/+|\/+$/g,""),O=`s3://${P_.s3.bucket}/${N}/`,A=_.storage.type==="s3"&&D?.bucket===P_.s3.bucket&&(D.region??null)===P_.s3.region;return{scope:g,mode:_.mode,storage_type:_.storage.type,workspace_home:$.home,local_layout:{app_path:l$,config_path:$.configPath,json_store_path:$.jsonStorePath,knowledge_db_path:$.knowledgeDbPath,directories:{artifacts:$.artifactsDir,cache:$.cacheDir,exports:$.exportsDir,indexes:$.indexesDir,logs:$.logsDir,runs:$.runsDir,schemas:$.schemasDir,wiki:$.wikiDir}},artifact_store:{type:_.storage.type,artifacts_root:_.storage.artifacts_root,uri_prefix:_.storage.type==="s3"?j:ET(`${$.artifactsDir}/`).href,s3:D?{bucket:D.bucket,prefix:I,region:D.region??null,profile:D.profile??null,server_side_encryption:D.server_side_encryption??null,kms_key_configured:Boolean(D.kms_key_id)}:null},canonical_example:{division:P_.division,app_type:P_.app_type,app:P_.app,env:P_.env,active:A,local_path:P_.local_path,s3:{bucket:P_.s3.bucket,region:P_.s3.region,profile:P_.s3.profile,prefix:N,uri_prefix:O,server_side_encryption:P_.s3.server_side_encryption},secrets:{env:P_.secrets.env,aws:P_.secrets.aws,s3:P_.secrets.s3,rds:P_.secrets.rds,future_rds:P_.secrets.future_rds},evidence_doc:P_.evidence_doc},hosted:{enabled:_.mode==="hosted",api_url:a$(_.hosted?.api_url??DE),api_url_env:"KNOWLEDGE_API_URL",api_key_env:"KNOWLEDGE_API_KEY",auth_storage:"~/.hasna/knowledge/auth.json",registry_contract_version:KS,requires_hosted_account_for_local_use:!1},secret_handling:{workspace_env_files_supported:!1,forbidden_workspace_files:OT,forbidden_workspace_files_present:MS($),runtime_env_keys:["HASNA_KNOWLEDGE_STORAGE_MODE","KNOWLEDGE_STORAGE_MODE","HASNA_KNOWLEDGE_DATABASE_URL","KNOWLEDGE_DATABASE_URL"],secret_ref_authority:"open-secrets",approved_secret_refs:{env:P_.secrets.env,aws:P_.secrets.aws,s3:P_.secrets.s3,rds:P_.secrets.rds},db_url_rotation_decision:{status:"blocked_without_secret_authority",reason:"No live secret mutation authority is available in @hasna/knowledge. Rotate the DB URL only through the approved secret authority if separate evidence proves the URL propagated to backups, exports, sync bundles, reports, or copied artifacts.",authority_required:!0}},source_ownership:{owner:"open-files",preferred_ref:_.sources.preferred_ref,allowed_schemes:_.sources.allowed_schemes,raw_source_bytes_stored_in_open_knowledge:!1,stores:["source refs","source revisions and hashes","citation spans","redacted extracted chunks","embeddings","generated wiki artifacts","indexes","run ledgers"],does_not_store:["raw open-files bytes","S3 object credentials","connector secrets","hosted tenant ownership state"]},private_fleet_boundary:{manifest_authority:"open-machines",source_ref_authority:"open-files",secret_ref_authority:"open-secrets",raw_private_manifest_bytes_stored_in_open_knowledge:!1,accepted_source_ref_schemes:_.sources.allowed_schemes.filter((L)=>["open-files","s3","file"].includes(L)),stores:["source refs for private manifests","redacted setup decisions","runbook summaries","citation spans into approved knowledge sources","machine setup evidence hashes"],does_not_store:["private fleet manifests","machine hostnames","machine serial numbers","sudo passwords","VNC passwords","SSH private keys","GitHub App private keys","secret values"],example_manifest_ref:"open-files://source/private-fleet-manifest/path/machines.json"},generated_artifacts:FS,scalability:{catalog:"knowledge.db tracks sources, revisions, chunks, citations, indexes, runs, and storage_objects.",indexes:"Indexes are cataloged DB rows plus sharded artifacts, not one giant index.md.",logs:"Logs use dated JSONL partitions under logs/yyyy/mm/dd.jsonl.",markdown:"Markdown pages are the readable wiki layer over DB/object-store state."},warnings:U.warnings}}function IE(_,$){let g=[],U=[],D=MS($);for(let I of D)g.push(`Forbidden Knowledge workspace file present: ${I}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`);if(!$.home.endsWith(l$))U.push(`Workspace home does not end with ${l$}: ${$.home}`);if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)g.push("storage.s3.bucket is required when storage.type is s3.");if(!_.storage.s3?.prefix)U.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root.");if(_.mode==="local")U.push("storage.type is s3 while mode is local; this is valid for BYO S3, but hosted wrappers should set mode to hosted.")}if(_.storage.type==="local"&&_.storage.s3)U.push("storage.s3 is configured but ignored while storage.type is local.");if(_.sources.preferred_ref!=="open-files")U.push("sources.preferred_ref should stay open-files for durable company knowledge.");if(!_.sources.allowed_schemes.includes("open-files"))g.push("sources.allowed_schemes must include open-files.");if(_.mode==="hosted"&&_.hosted?.api_url)try{a$(_.hosted.api_url)}catch{g.push("hosted.api_url must be an http(s) URL when mode is hosted.")}return{ok:g.length===0,errors:g,warnings:U}}function s$(_,$,g=new Date){let U=g.toISOString(),D=_.prepare(` INSERT INTO storage_objects ( id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at ) @@ -589,49 +590,49 @@ VALUES (10, datetime('now')); size_bytes = excluded.size_bytes, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);$.transaction((G)=>{for(let Y of G){let Q={key:Y.key,...Y.modified_at?{artifact_modified_at:Y.modified_at}:{},...Y.metadata??{}};W.run(BZ(),Y.uri,Y.kind,Y.content_type??null,Y.hash??null,Y.size_bytes??null,JSON.stringify(Q),U,U)}})(_)}function kQ($){return["deleted","stale","invalidated","reindex_required"].includes(($??"").toLowerCase())}function E0($){let _=$.status??null;return{source_owner:"open-files",source_ref:$.source_ref??null,source_uri:$.source_uri??null,source_kind:$.source_kind??null,source_revision_id:$.source_revision_id??null,revision:$.revision??null,hash:$.hash??null,chunk_id:$.chunk_id??null,start_offset:$.start_offset??null,end_offset:$.end_offset??null,status:_,read_only:!0,citation_required:!0,resolver:$.resolver??null,stale:kQ(_)}}function X6($){return{source_owner:"open-files",generated_from:$.generated_from,artifact_key:$.artifact_key,source_refs:$.source_refs??[],read_only_sources:!0,citation_required:$.citation_required??!0,raw_source_bytes_stored_in_open_knowledge:!1}}function R3($,_){return{...$,provenance:_}}import{createHash as Ev}from"crypto";import{existsSync as Mv,readFileSync as Av}from"fs";import{basename as c9}from"path";import{createHash as iZ}from"crypto";import{existsSync as lZ,readFileSync as rZ}from"fs";import{basename as pZ}from"path";import{fileURLToPath as RZ}from"url";function K3($,_){if(!$)throw Error(_);return $}function KZ($){let J=$.slice(13).split("/").filter(Boolean),U=J[0];if(U!=="file"&&U!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let W=K3(J[1],"Invalid open-files ref. Missing id.");if(U==="file"){if(J.length===2)return{kind:"open-files",uri:$,entity:U,id:W};if(J[2]==="revision"&&J[3]&&J.length===4)return{kind:"open-files",uri:$,entity:U,id:W,revision_id:decodeURIComponent(J[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let X=J.indexOf("path"),G=X>=0?decodeURIComponent(J.slice(X+1).join("/")):void 0;return{kind:"open-files",uri:$,entity:U,id:W,path:G}}function FZ($){let _=new URL($),J=K3(_.hostname,"Invalid s3 ref. Missing bucket."),U=decodeURIComponent(_.pathname.replace(/^\/+/,""));if(!U)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:$,bucket:J,key:U}}function EZ($){return{kind:"file",uri:$,path:RZ($)}}function MZ($){let _=new URL($);return{kind:"web",uri:$,url:_.toString()}}function B6($){if($.startsWith("open-files://"))return KZ($);if($.startsWith("s3://"))return FZ($);if($.startsWith("file://"))return EZ($);if($.startsWith("https://")||$.startsWith("http://"))return MZ($);throw Error(`Unsupported source ref scheme: ${$}`)}function F3($,_=B6($)){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function E3($){let _=B6($);return _.kind==="open-files"&&_.entity==="file"?_.revision_id??null:null}import{createHash as AZ,randomUUID as fQ}from"crypto";import{relative as bZ,resolve as A3,sep as wZ}from"path";function M3($){let _=process.env[$];return _==="1"||_==="true"||_==="yes"}function b3($,_){let J=$,U=new Set(J.safety?.network?.allowed_s3_buckets??[]);if($.storage.type==="s3"&&$.storage.s3?.bucket)U.add($.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let W of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((X)=>X.trim()).filter(Boolean))U.add(W);return{mode:$.mode,allowWriteRoots:[_.home,_.artifactsDir,_.cacheDir,_.exportsDir,_.indexesDir,_.logsDir,_.runsDir,_.schemasDir,_.wikiDir].map((W)=>A3(W)),readOnlySourceAccess:!0,network:{webSearchEnabled:J.safety?.network?.web_search_enabled??M3("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:J.safety?.network?.s3_reads_enabled??M3("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...U].sort()},redaction:{enabled:J.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:J.safety?.approvals?.generated_writes_require_approval??!0}}}function gZ($,_){let J=bZ($,_);return J===""||!J.startsWith("..")&&J!==".."&&!J.startsWith(`..${wZ}`)}function d4($,_){let J=A3($);if(!_.allowWriteRoots.some((U)=>gZ(U,J)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${$}`)}function M0($,_){let U=new URL($).hostname;if(!_.network.s3ReadsEnabled)throw Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1.");if(!_.network.allowedS3Buckets.includes(U))throw Error(`Safety policy denied S3 bucket "${U}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function fJ($){if(!$.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var w3=[{type:"private_key_block",severity:"high",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,replacement:"[REDACTED:private_key_block]"},{type:"secret_assignment",severity:"high",regex:/\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi,replacement:"[REDACTED:secret_assignment]"},{type:"openai_api_key",severity:"high",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:openai_api_key]"},{type:"anthropic_api_key",severity:"high",regex:new RegExp(`\\b${["sk","ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`,"g"),replacement:"[REDACTED:anthropic_api_key]"},{type:"aws_access_key_id",severity:"high",regex:/\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g,replacement:"[REDACTED:aws_access_key_id]"}];function k_($,_){if(_&&!_.redaction.enabled)return{text:$,findings:[]};let J=$,U=[];for(let W of w3)J=J.replace(W.regex,(X,...G)=>{let Y=typeof G.at(-2)==="number"?G.at(-2):J.indexOf(X);return U.push({type:W.type,severity:W.severity,start:Math.max(0,Y),end:Math.max(0,Y+X.length)}),W.replacement});return{text:J,findings:U}}function kZ($){return`audit_${AZ("sha256").update(`${$.event_type}\x00${$.action}\x00${$.target_uri??""}\x00${$.created_at??""}\x00${JSON.stringify($.metadata??{})}\x00${fQ()}`).digest("hex").slice(0,24)}`}function IQ($,_=0){if(_>6)return"[Truncated:depth]";if(typeof $==="string")return $.length>1000?`${$.slice(0,1000)}...[Truncated:${$.length-1000} chars]`:$;if(typeof $==="number"||typeof $==="boolean"||$===null||$===void 0)return $;if(Array.isArray($)){let J=$.slice(0,25).map((U)=>IQ(U,_+1));if($.length>25)J.push(`[Truncated:${$.length-25} items]`);return J}if(typeof $==="object"){let J={},U=Object.entries($).slice(0,50);for(let[X,G]of U)J[X]=IQ(G,_+1);let W=Object.keys($).length;if(W>U.length)J.__truncated_keys=W-U.length;return J}return String($)}function __($,_){let J=_.created_at??new Date().toISOString(),U=IQ(_.metadata??{}),W=kZ({..._,metadata:U,created_at:J});return $.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`,[W,_.event_type,_.action,_.target_uri??null,_.decision,JSON.stringify(U),J]),W}function CJ($,_){let J=_.created_at??new Date().toISOString();for(let U of _.findings)$.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`,[`redact_${fQ()}`,_.source_uri??null,_.run_id??null,U.severity,U.type,JSON.stringify({..._.metadata??{},start:U.start,end:U.end}),J]);return _.findings.length}function u9($,_){let J=_.created_at??new Date().toISOString(),U=`approval_${fQ()}`;return $.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.action,_.target_uri??null,"approved",_.reason??null,_.approved_by??"local-cli",JSON.stringify(_.metadata??{}),J,J]),{id:U,status:"approved"}}var IZ=[{type:"github_token",severity:"high",regex:/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_token]"},{type:"github_pat_token",severity:"high",regex:/\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_pat_token]"},{type:"package_registry_token",severity:"high",regex:/\bnpm_[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:package_registry_token]"},{type:"context7_token",severity:"high",regex:/\bctx7sk[-][A-Za-z0-9_-]{10,}\b/g,replacement:"[REDACTED:context7_token]"},{type:"xai_api_key",severity:"high",regex:/\bxai[-][A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:xai_api_key]"},{type:"google_api_key",severity:"high",regex:/\bAIza[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:google_api_key]"}];w3.push(...IZ);function fZ($,_,J){let U=$.query(`SELECT id FROM approval_gates + `);_.transaction((j)=>{for(let N of j){let O={key:N.key,...N.modified_at?{artifact_modified_at:N.modified_at}:{},...N.metadata??{}};D.run(jT(),N.uri,N.kind,N.content_type??null,N.hash??null,N.size_bytes??null,JSON.stringify(O),U,U)}})($)}function jE(_){return["deleted","stale","invalidated","reindex_required"].includes((_??"").toLowerCase())}function T6(_){let $=_.status??null;return{source_owner:"open-files",source_ref:_.source_ref??null,source_uri:_.source_uri??null,source_kind:_.source_kind??null,source_revision_id:_.source_revision_id??null,revision:_.revision??null,hash:_.hash??null,chunk_id:_.chunk_id??null,start_offset:_.start_offset??null,end_offset:_.end_offset??null,status:$,read_only:!0,citation_required:!0,resolver:_.resolver??null,stale:jE($)}}function U$(_){return{source_owner:"open-files",generated_from:_.generated_from,artifact_key:_.artifact_key,source_refs:_.source_refs??[],read_only_sources:!0,citation_required:_.citation_required??!0,raw_source_bytes_stored_in_open_knowledge:!1}}function bS(_,$){return{..._,provenance:$}}import{createHash as P7}from"crypto";import{existsSync as z7,readFileSync as S7}from"fs";import{basename as tU}from"path";import{createHash as fT}from"crypto";import{existsSync as wT,readFileSync as uT}from"fs";import{basename as xT}from"path";import{fileURLToPath as AT}from"url";function HS(_,$){if(!_)throw Error($);return _}function LT(_){let g=_.slice(13).split("/").filter(Boolean),U=g[0];if(U!=="file"&&U!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let D=HS(g[1],"Invalid open-files ref. Missing id.");if(U==="file"){if(g.length===2)return{kind:"open-files",uri:_,entity:U,id:D};if(g[2]==="revision"&&g[3]&&g.length===4)return{kind:"open-files",uri:_,entity:U,id:D,revision_id:decodeURIComponent(g[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let I=g.indexOf("path"),j=I>=0?decodeURIComponent(g.slice(I+1).join("/")):void 0;return{kind:"open-files",uri:_,entity:U,id:D,path:j}}function JT(_){let $=new URL(_),g=HS($.hostname,"Invalid s3 ref. Missing bucket."),U=decodeURIComponent($.pathname.replace(/^\/+/,""));if(!U)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:_,bucket:g,key:U}}function PT(_){return{kind:"file",uri:_,path:AT(_)}}function zT(_){let $=new URL(_);return{kind:"web",uri:_,url:$.toString()}}function A$(_){if(_.startsWith("open-files://"))return LT(_);if(_.startsWith("s3://"))return JT(_);if(_.startsWith("file://"))return PT(_);if(_.startsWith("https://")||_.startsWith("http://"))return zT(_);throw Error(`Unsupported source ref scheme: ${_}`)}function kS(_,$=A$(_)){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function CS(_){let $=A$(_);return $.kind==="open-files"&&$.entity==="file"?$.revision_id??null:null}import{createHash as ST,randomUUID as EE}from"crypto";import{relative as WT,resolve as vS,sep as XT}from"path";function rS(_){let $=process.env[_];return $==="1"||$==="true"||$==="yes"}function fS(_,$){let g=_,U=new Set(g.safety?.network?.allowed_s3_buckets??[]);if(_.storage.type==="s3"&&_.storage.s3?.bucket)U.add(_.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let D of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((I)=>I.trim()).filter(Boolean))U.add(D);return{mode:_.mode,allowWriteRoots:[$.home,$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir].map((D)=>vS(D)),readOnlySourceAccess:!0,network:{webSearchEnabled:g.safety?.network?.web_search_enabled??rS("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:g.safety?.network?.s3_reads_enabled??rS("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...U].sort()},redaction:{enabled:g.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:g.safety?.approvals?.generated_writes_require_approval??!0}}}function RT(_,$){let g=WT(_,$);return g===""||!g.startsWith("..")&&g!==".."&&!g.startsWith(`..${XT}`)}function _6(_,$){let g=vS(_);if(!$.allowWriteRoots.some((U)=>RT(U,g)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${_}`)}function q6(_,$){let U=new URL(_).hostname;if(!$.network.s3ReadsEnabled)throw Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1.");if(!$.network.allowedS3Buckets.includes(U))throw Error(`Safety policy denied S3 bucket "${U}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function J0(_){if(!_.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var wS=[{type:"private_key_block",severity:"high",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,replacement:"[REDACTED:private_key_block]"},{type:"secret_assignment",severity:"high",regex:/\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi,replacement:"[REDACTED:secret_assignment]"},{type:"openai_api_key",severity:"high",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:openai_api_key]"},{type:"anthropic_api_key",severity:"high",regex:new RegExp(`\\b${["sk","ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`,"g"),replacement:"[REDACTED:anthropic_api_key]"},{type:"aws_access_key_id",severity:"high",regex:/\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g,replacement:"[REDACTED:aws_access_key_id]"}];function u_(_,$){if($&&!$.redaction.enabled)return{text:_,findings:[]};let g=_,U=[];for(let D of wS)g=g.replace(D.regex,(I,...j)=>{let N=typeof j.at(-2)==="number"?j.at(-2):g.indexOf(I);return U.push({type:D.type,severity:D.severity,start:Math.max(0,N),end:Math.max(0,N+I.length)}),D.replacement});return{text:g,findings:U}}function GT(_){return`audit_${ST("sha256").update(`${_.event_type}\x00${_.action}\x00${_.target_uri??""}\x00${_.created_at??""}\x00${JSON.stringify(_.metadata??{})}\x00${EE()}`).digest("hex").slice(0,24)}`}function NE(_,$=0){if($>6)return"[Truncated:depth]";if(typeof _==="string")return _.length>1000?`${_.slice(0,1000)}...[Truncated:${_.length-1000} chars]`:_;if(typeof _==="number"||typeof _==="boolean"||_===null||_===void 0)return _;if(Array.isArray(_)){let g=_.slice(0,25).map((U)=>NE(U,$+1));if(_.length>25)g.push(`[Truncated:${_.length-25} items]`);return g}if(typeof _==="object"){let g={},U=Object.entries(_).slice(0,50);for(let[I,j]of U)g[I]=NE(j,$+1);let D=Object.keys(_).length;if(D>U.length)g.__truncated_keys=D-U.length;return g}return String(_)}function X_(_,$){let g=$.created_at??new Date().toISOString(),U=NE($.metadata??{}),D=GT({...$,metadata:U,created_at:g});return _.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`,[D,$.event_type,$.action,$.target_uri??null,$.decision,JSON.stringify(U),g]),D}function P0(_,$){let g=$.created_at??new Date().toISOString();for(let U of $.findings)_.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`,[`redact_${EE()}`,$.source_uri??null,$.run_id??null,U.severity,U.type,JSON.stringify({...$.metadata??{},start:U.start,end:U.end}),g]);return $.findings.length}function mU(_,$){let g=$.created_at??new Date().toISOString(),U=`approval_${EE()}`;return _.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,$.action,$.target_uri??null,"approved",$.reason??null,$.approved_by??"local-cli",JSON.stringify($.metadata??{}),g,g]),{id:U,status:"approved"}}var YT=[{type:"github_token",severity:"high",regex:/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_token]"},{type:"github_pat_token",severity:"high",regex:/\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_pat_token]"},{type:"package_registry_token",severity:"high",regex:/\bnpm_[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:package_registry_token]"},{type:"context7_token",severity:"high",regex:/\bctx7sk[-][A-Za-z0-9_-]{10,}\b/g,replacement:"[REDACTED:context7_token]"},{type:"xai_api_key",severity:"high",regex:/\bxai[-][A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:xai_api_key]"},{type:"google_api_key",severity:"high",regex:/\bAIza[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:google_api_key]"}];wS.push(...YT);function QT(_,$,g){let U=_.query(`SELECT id FROM approval_gates WHERE action = ? AND status = 'approved' AND (target_uri IS NULL OR target_uri = ? OR ? IS NULL) - ORDER BY updated_at DESC LIMIT 1`).get(_,J??null,J??null);return Boolean(U)}function g3($,_,J,U){let W=J==="generated_write"&&_.approvals.generatedWritesRequireApproval,X=!W||fZ($,J,U);return{action:J,target_uri:U??null,approval_required:W,approved:X,decision:X?"allow":"requires_approval"}}import{createHash as CZ}from"crypto";import{realpathSync as PZ}from"fs";import{homedir as TZ,tmpdir as SZ}from"os";var F1=String.raw`[^\s"'<>),\]}]`,PQ=String.raw`[^/\\\s"'<>]+`,f3=/file:\/\/[^\s"'<>),\]}]+/gi,ZZ=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,C3=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,P3=new RegExp(String.raw`/(?:home|Users)/${PQ}/(?:workspace|Workspace)/${F1}*`,"g"),vZ=[new RegExp(String.raw`/(?:home|Users)/${PQ}(?:/${F1}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${F1}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${F1}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,S3=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,yZ=new Set(["content_base64"]);function hZ($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mZ($){return $.length>=4&&$!=="/"&&!/^[A-Za-z]:[\\/]?$/.test($)}var k3=null,CQ=[];function xZ(){let $=new Set;for(let J of[TZ(),SZ()]){if(!J)continue;$.add(J);try{$.add(PZ(J))}catch{}}let _=[...$].sort().join("\x00");if(_===k3)return CQ;return k3=_,CQ=[...$].filter(mZ).sort((J,U)=>U.length-J.length).map((J)=>new RegExp(`${hZ(J)}(?:[/\\\\]${F1}*)?`,"g")),CQ}function H6($){return CZ("sha256").update($).digest("hex").slice(0,12)}function uZ($){return $.length<=80?$:`${$.slice(0,77)}...`}function I3($){return/(?:^|\/)\.hasna(?:\/|$)/i.test($)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test($)||/\bmigration-exports\//i.test($)}function dZ($,_,J,U){for(let W of $.matchAll(f3)){let X=W[0];if(!J.allowFileSourceRefs||I3(X))U.push({type:I3(X)?"private_file_uri":"local_file_uri",severity:"high",path:_,preview:uZ(X.replace(/^file:\/\/.*/,`[redacted:file-uri:${H6(X)}]`))})}for(let W of $.matchAll(C3))U.push({type:"private_hasna_path",severity:"high",path:_,preview:`[redacted:.hasna:${H6(W[0])}]`});for(let W of $.matchAll(T3))U.push({type:W[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:_,preview:`[redacted:${H6(W[0])}]`});for(let W of $.matchAll(S3))U.push({type:"database_url",severity:"high",path:_,preview:`[redacted:database-url:${H6(W[0])}]`});if(!J.allowPrivateWorkspaceRefs)for(let W of $.matchAll(P3))U.push({type:"private_workspace_path",severity:"medium",path:_,preview:`[redacted:workspace:${H6(W[0])}]`})}function nZ($,_={},J="$"){let U=[],W=(X,G)=>{if(typeof X==="string"){dZ(X,G,_,U);return}if(!X||typeof X!=="object")return;if(Array.isArray(X)){X.forEach((Y,Q)=>W(Y,`${G}[${Q}]`));return}for(let[Y,Q]of Object.entries(X))W(Q,`${G}.${Y}`)};return W($,J),U}function E1($,_={}){let J=nZ($,_);if(J.length===0)return;let U=new Map;for(let X of J)U.set(X.type,(U.get(X.type)??0)+1);let W=[...U.entries()].map(([X,G])=>`${X}:${G}`).join(", ");throw Error(`Knowledge private-ref lint failed (${W}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function cZ($){let _=k_($).text.replace(S3,(J)=>`[REDACTED:database-url:${H6(J)}]`).replace(f3,(J)=>`[REDACTED:local-file-uri:${H6(J)}]`).replace(ZZ,(J)=>`[REDACTED:local-hasna-path:${H6(J)}]`).replace(P3,(J)=>`[REDACTED:private-workspace:${H6(J)}]`);for(let J of[...xZ(),...vZ])_=_.replace(J,(U)=>`[REDACTED:local-path:${H6(U)}]`);return _.replace(C3,(J)=>`[REDACTED:hasna-path:${H6(J)}]`).replace(T3,(J)=>`[REDACTED:private-artifact:${H6(J)}]`)}function j_($){if(typeof $==="string")return cZ($);if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((J)=>j_(J));let _={};for(let[J,U]of Object.entries($))_[J]=yZ.has(J)?U:j_(U);return _}var oZ=20971520,Z3=1e4,tZ=10;function SQ($,_){return`${$}_${iZ("sha256").update(_).digest("hex").slice(0,20)}`}function M1($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function d$($){return typeof $==="string"&&$.length>0?$:void 0}function aZ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function sZ($){let _=d$($.source_ref)??d$($.source_uri)??d$($.uri);if(_)return _;let J=d$($.file_id);if(J){let X=d$($.revision_id)??d$($.revision),G=`open-files://file/${encodeURIComponent(J)}`;return X?`${G}/revision/${encodeURIComponent(X)}`:G}let U=d$($.source_id),W=d$($.path);if(U&&W)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(W)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function eZ($,_){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function $v($){let _=d$($.extracted_text)??d$($.text)??d$($.content_text)??d$($.markdown);if(_!==void 0)return _;let J=$.content;return typeof J==="string"?J:null}function _v($){let _=d$($.extracted_text_ref)??d$($.extracted_text_uri)??d$($.text_ref);if(_)return _;let J=M1($.content);return d$(J?.extracted_text_ref)??d$(J?.extracted_text_uri)??null}function Jv($){let _=d$($.path);return d$($.title)??d$($.name)??(_?pZ(_):null)}function Wv($){return d$($.hash)??d$($.checksum)??d$($.sha256)??null}var v3=new Set(["text","content","content_text","extracted_text","markdown","raw","raw_text","raw_bytes","raw_content","raw_body","raw_file","source_raw","source_raw_bytes","source_bytes","source_content","source_body","file_bytes","file_content","content_bytes","content_base64","document_bytes","document_content","document_base64","binary","binary_content","binary_base64","bytes","body","blob","data","payload"]);function y3($){return $.toLowerCase().replace(/[\s-]+/g,"_")}function TQ($){if(Array.isArray($))return $.map((U)=>TQ(U));let _=M1($);if(!_)return $;let J={};for(let[U,W]of Object.entries(_)){if(v3.has(y3(U)))continue;J[U]=TQ(W)}return J}function Uv($,_,J){return d$($.revision_id)??d$($.revision)??d$($.version_id)??(_.kind==="open-files"?_.revision_id:void 0)??J??d$($.updated_at)??"current"}function Xv($,_){let J={};for(let[U,W]of Object.entries($)){if(v3.has(y3(U)))continue;J[U]=j_(TQ(W))}return J.source_ref=_.sourceRef,J.source_uri=_.sourceUri,J.status=_.status,J}function Gv($,_,J={}){let U=sZ($);E1(U,{allowFileSourceRefs:J.allowFileSourceRefs===!0});let W=B6(U),X=eZ(U,W),G=Wv($),Y=d$($.status)??"active";return{raw:$,sourceRef:U,sourceUri:X,kind:W.kind,title:Jv($),revision:Uv($,W,G),hash:G,extractedTextUri:_v($),text:$v($),metadata:Xv($,{sourceRef:U,sourceUri:X,status:Y}),acl:$.permissions??$.acl??{},status:Y,updatedAt:d$($.updated_at)??_}}function Yv($){let _=$.trim();if(!_)return[];if(_.startsWith("[")){let J=JSON.parse(_);if(!Array.isArray(J))throw Error("Manifest array parse failed.");return J.map((U)=>{let W=M1(U);if(!W)throw Error("Manifest array entries must be objects.");return W})}if(_.startsWith("{"))try{let J=JSON.parse(_),U=M1(J);if(!U)throw Error("Manifest object parse failed.");if(Array.isArray(U.items))return U.items.map((W)=>{let X=M1(W);if(!X)throw Error("Manifest items entries must be objects.");return X});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(J){let U=_.split(/\r?\n/).filter((W)=>W.trim().length>0);if(U.length<=1)throw J;return U.map((W)=>{let X=M1(JSON.parse(W));if(!X)throw Error("Manifest JSONL entries must be objects.");return X})}return _.split(/\r?\n/).filter((J)=>J.trim().length>0).map((J)=>{let U=M1(JSON.parse(J));if(!U)throw Error("Manifest JSONL entries must be objects.");return U})}async function Qv($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 manifest URI: ${$}`);if(J)M0($,J);let[{S3Client:G,GetObjectCommand:Y},{fromIni:Q}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Q({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Y({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function qv($,_,J,U=oZ){let W=$.startsWith("s3://")?await Qv($,_,J):(()=>{if(!lZ($))throw Error(`Manifest not found: ${$}`);return rZ($,"utf8")})(),X=Buffer.byteLength(W);if(X>U)throw Error(`Manifest input is too large: ${X} bytes exceeds ${U} byte limit.`);return W}function zv($,_,J){let U=$.replace(/\r\n/g,` -`);if(!U.trim())return[];let W=[],X=0;while(X),\]}]`,AE=String.raw`[^/\\\s"'<>]+`,hS=/file:\/\/[^\s"'<>),\]}]+/gi,VT=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,cS=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,nS=new RegExp(String.raw`/(?:home|Users)/${AE}/(?:workspace|Workspace)/${a6}*`,"g"),FT=[new RegExp(String.raw`/(?:home|Users)/${AE}(?:/${a6}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${a6}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${a6}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,mS=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,MT=new Set(["content_base64"]);function ZT(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bT(_){return _.length>=4&&_!=="/"&&!/^[A-Za-z]:[\\/]?$/.test(_)}var xS=null,OE=[];function HT(){let _=new Set;for(let g of[BT(),KT()]){if(!g)continue;_.add(g);try{_.add(qT(g))}catch{}}let $=[..._].sort().join("\x00");if($===xS)return OE;return xS=$,OE=[..._].filter(bT).sort((g,U)=>U.length-g.length).map((g)=>new RegExp(`${ZT(g)}(?:[/\\\\]${a6}*)?`,"g")),OE}function L$(_){return TT("sha256").update(_).digest("hex").slice(0,12)}function kT(_){return _.length<=80?_:`${_.slice(0,77)}...`}function yS(_){return/(?:^|\/)\.hasna(?:\/|$)/i.test(_)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test(_)||/\bmigration-exports\//i.test(_)}function CT(_,$,g,U){for(let D of _.matchAll(hS)){let I=D[0];if(!g.allowFileSourceRefs||yS(I))U.push({type:yS(I)?"private_file_uri":"local_file_uri",severity:"high",path:$,preview:kT(I.replace(/^file:\/\/.*/,`[redacted:file-uri:${L$(I)}]`))})}for(let D of _.matchAll(cS))U.push({type:"private_hasna_path",severity:"high",path:$,preview:`[redacted:.hasna:${L$(D[0])}]`});for(let D of _.matchAll(dS))U.push({type:D[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:$,preview:`[redacted:${L$(D[0])}]`});for(let D of _.matchAll(mS))U.push({type:"database_url",severity:"high",path:$,preview:`[redacted:database-url:${L$(D[0])}]`});if(!g.allowPrivateWorkspaceRefs)for(let D of _.matchAll(nS))U.push({type:"private_workspace_path",severity:"medium",path:$,preview:`[redacted:workspace:${L$(D[0])}]`})}function rT(_,$={},g="$"){let U=[],D=(I,j)=>{if(typeof I==="string"){CT(I,j,$,U);return}if(!I||typeof I!=="object")return;if(Array.isArray(I)){I.forEach((N,O)=>D(N,`${j}[${O}]`));return}for(let[N,O]of Object.entries(I))D(O,`${j}.${N}`)};return D(_,g),U}function s6(_,$={}){let g=rT(_,$);if(g.length===0)return;let U=new Map;for(let I of g)U.set(I.type,(U.get(I.type)??0)+1);let D=[...U.entries()].map(([I,j])=>`${I}:${j}`).join(", ");throw Error(`Knowledge private-ref lint failed (${D}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function vT(_){let $=u_(_).text.replace(mS,(g)=>`[REDACTED:database-url:${L$(g)}]`).replace(hS,(g)=>`[REDACTED:local-file-uri:${L$(g)}]`).replace(VT,(g)=>`[REDACTED:local-hasna-path:${L$(g)}]`).replace(nS,(g)=>`[REDACTED:private-workspace:${L$(g)}]`);for(let g of[...HT(),...FT])$=$.replace(g,(U)=>`[REDACTED:local-path:${L$(U)}]`);return $.replace(cS,(g)=>`[REDACTED:hasna-path:${L$(g)}]`).replace(dS,(g)=>`[REDACTED:private-artifact:${L$(g)}]`)}function q_(_){if(typeof _==="string")return vT(_);if(!_||typeof _!=="object")return _;if(Array.isArray(_))return _.map((g)=>q_(g));let $={};for(let[g,U]of Object.entries(_))$[g]=MT.has(g)?U:q_(U);return $}var yT=20971520,iS=1e4,hT=10;function JE(_,$){return`${_}_${fT("sha256").update($).digest("hex").slice(0,20)}`}function _4(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function N_(_){return typeof _==="string"&&_.length>0?_:void 0}function cT(_){return typeof _==="number"&&Number.isFinite(_)?_:void 0}function nT(_){let $=N_(_.source_ref)??N_(_.source_uri)??N_(_.uri);if($)return $;let g=N_(_.file_id);if(g){let I=N_(_.revision_id)??N_(_.revision),j=`open-files://file/${encodeURIComponent(g)}`;return I?`${j}/revision/${encodeURIComponent(I)}`:j}let U=N_(_.source_id),D=N_(_.path);if(U&&D)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(D)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function dT(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function mT(_){let $=N_(_.extracted_text)??N_(_.text)??N_(_.content_text)??N_(_.markdown);if($!==void 0)return $;let g=_.content;return typeof g==="string"?g:null}function iT(_){let $=N_(_.extracted_text_ref)??N_(_.extracted_text_uri)??N_(_.text_ref);if($)return $;let g=_4(_.content);return N_(g?.extracted_text_ref)??N_(g?.extracted_text_uri)??null}function lT(_){let $=N_(_.path);return N_(_.title)??N_(_.name)??($?xT($):null)}function tT(_){return N_(_.hash)??N_(_.checksum)??N_(_.sha256)??null}var lS=new Set(["text","content","content_text","extracted_text","markdown","raw","raw_text","raw_bytes","raw_content","raw_body","raw_file","source_raw","source_raw_bytes","source_bytes","source_content","source_body","file_bytes","file_content","content_bytes","content_base64","document_bytes","document_content","document_base64","binary","binary_content","binary_base64","bytes","body","blob","data","payload"]);function tS(_){return _.toLowerCase().replace(/[\s-]+/g,"_")}function LE(_){if(Array.isArray(_))return _.map((U)=>LE(U));let $=_4(_);if(!$)return _;let g={};for(let[U,D]of Object.entries($)){if(lS.has(tS(U)))continue;g[U]=LE(D)}return g}function oT(_,$,g){return N_(_.revision_id)??N_(_.revision)??N_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??g??N_(_.updated_at)??"current"}function pT(_,$){let g={};for(let[U,D]of Object.entries(_)){if(lS.has(tS(U)))continue;g[U]=q_(LE(D))}return g.source_ref=$.sourceRef,g.source_uri=$.sourceUri,g.status=$.status,g}function eT(_,$,g={}){let U=nT(_);s6(U,{allowFileSourceRefs:g.allowFileSourceRefs===!0});let D=A$(U),I=dT(U,D),j=tT(_),N=N_(_.status)??"active";return{raw:_,sourceRef:U,sourceUri:I,kind:D.kind,title:lT(_),revision:oT(_,D,j),hash:j,extractedTextUri:iT(_),text:mT(_),metadata:pT(_,{sourceRef:U,sourceUri:I,status:N}),acl:_.permissions??_.acl??{},status:N,updatedAt:N_(_.updated_at)??$}}function aT(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let g=JSON.parse($);if(!Array.isArray(g))throw Error("Manifest array parse failed.");return g.map((U)=>{let D=_4(U);if(!D)throw Error("Manifest array entries must be objects.");return D})}if($.startsWith("{"))try{let g=JSON.parse($),U=_4(g);if(!U)throw Error("Manifest object parse failed.");if(Array.isArray(U.items))return U.items.map((D)=>{let I=_4(D);if(!I)throw Error("Manifest items entries must be objects.");return I});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(g){let U=$.split(/\r?\n/).filter((D)=>D.trim().length>0);if(U.length<=1)throw g;return U.map((D)=>{let I=_4(JSON.parse(D));if(!I)throw Error("Manifest JSONL entries must be objects.");return I})}return $.split(/\r?\n/).filter((g)=>g.trim().length>0).map((g)=>{let U=_4(JSON.parse(g));if(!U)throw Error("Manifest JSONL entries must be objects.");return U})}async function sT(_,$,g){let U=new URL(_),D=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!D||!I)throw Error(`Invalid S3 manifest URI: ${_}`);if(g)q6(_,g);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===D?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:D,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function _7(_,$,g,U=yT){let D=_.startsWith("s3://")?await sT(_,$,g):(()=>{if(!wT(_))throw Error(`Manifest not found: ${_}`);return uT(_,"utf8")})(),I=Buffer.byteLength(D);if(I>U)throw Error(`Manifest input is too large: ${I} bytes exceeds ${U} byte limit.`);return D}function $7(_,$,g){let U=_.replace(/\r\n/g,` +`);if(!U.trim())return[];let D=[],I=0;while(IX+Math.floor(_*0.5))Y=N+(N===q?2:1)}let Q=U.slice(X,Y).trim();if(Q)W.push({ordinal:W.length,text:Q,startOffset:X,endOffset:Y});if(Y>=U.length)break;X=Math.max(0,Y-J)}return W}function jv($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function Dv($,_){let J=$.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(_);for(let U of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);return $.run("DELETE FROM chunks WHERE source_revision_id = ?",[_]),J.length}function Ov($,_,J){let U=SQ("src",_.sourceUri);$.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) +`,j),L=U.lastIndexOf(". ",j),z=Math.max(A,L);if(z>I+Math.floor($*0.5))N=z+(z===A?2:1)}let O=U.slice(I,N).trim();if(O)D.push({ordinal:D.length,text:O,startOffset:I,endOffset:N});if(N>=U.length)break;I=Math.max(0,N-g)}return D}function g7(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function D7(_,$){let g=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($);for(let U of g)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);return _.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]),g.length}function U7(_,$,g){let U=JE("src",$.sourceUri);_.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(uri) DO UPDATE SET kind = excluded.kind, title = excluded.title, metadata_json = excluded.metadata_json, acl_json = excluded.acl_json, - updated_at = excluded.updated_at`,[U,_.sourceUri,_.kind,_.title,JSON.stringify(_.metadata),JSON.stringify(_.acl??{}),J,_.updatedAt]);let W=$.query("SELECT id FROM sources WHERE uri = ?").get(_.sourceUri);if(!W)throw Error(`Failed to upsert source: ${_.sourceUri}`);return W.id}function Lv($,_,J,U){let W=SQ("rev",`${_}\x00${J.revision}`);$.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) + updated_at = excluded.updated_at`,[U,$.sourceUri,$.kind,$.title,JSON.stringify($.metadata),JSON.stringify($.acl??{}),g,$.updatedAt]);let D=_.query("SELECT id FROM sources WHERE uri = ?").get($.sourceUri);if(!D)throw Error(`Failed to upsert source: ${$.sourceUri}`);return D.id}function I7(_,$,g,U){let D=JE("rev",`${$}\x00${g.revision}`);_.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(source_id, revision) DO UPDATE SET hash = excluded.hash, extracted_text_uri = excluded.extracted_text_uri, - metadata_json = excluded.metadata_json`,[W,_,J.revision,J.hash,J.extractedTextUri,JSON.stringify(J.metadata),U]);let X=$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(_,J.revision);if(!X)throw Error(`Failed to upsert source revision: ${J.sourceRef}`);return X.id}function Bv($,_,J,U,W,X,G){if(!J.text||J.status.toLowerCase()==="deleted")return{chunksInserted:0,redactions:0};let Y=k_(J.text,G);if(Y.findings.length>0)CJ($,{source_uri:J.sourceUri,findings:Y.findings,metadata:{source_ref:J.sourceRef,revision:J.revision},created_at:U}),__($,{event_type:"redaction",action:"source_text_redact",target_uri:J.sourceUri,decision:"redacted",metadata:{findings:Y.findings.length,source_ref:J.sourceRef,revision:J.revision},created_at:U});let Q=zv(Y.text,W,X);for(let q of Q){let L=SQ("chk",`${_}\x00${q.ordinal}\x00${q.text}`),N=E0({source_ref:J.sourceRef,source_uri:J.sourceUri,source_kind:J.kind,source_revision_id:_,revision:J.revision,hash:J.hash,chunk_id:L,start_offset:q.startOffset,end_offset:q.endOffset,status:J.status,resolver:"open-files-read-only"}),R=R3({source_ref:J.sourceRef,source_uri:J.sourceUri,source_kind:J.kind,source_revision_id:_,revision:J.revision,hash:J.hash,status:J.status,path:d$(J.raw.path)??null,mime:d$(J.raw.mime)??d$(J.raw.content_type)??null,size:aZ(J.raw.size)??null},N);$.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[L,_,"source",q.ordinal,q.text,jv(q.text),q.startOffset,q.endOffset,JSON.stringify(R),U]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[L,q.text,J.title??"",J.sourceUri])}return{chunksInserted:Q.length,redactions:Y.findings.length}}async function h3($){let _=$.now??new Date;if($.safetyPolicy)d4($.dbPath,$.safetyPolicy);a($.dbPath);let J=await qv($.input,$.config,$.safetyPolicy,$.maxInputBytes),U=Yv(J),W=$.maxItems??Z3;if(U.length>W)throw Error(`Manifest contains too many items: ${U.length} exceeds ${W} item limit.`);return A1({dbPath:$.dbPath,items:U,sourceLabel:$.input,allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")===!0,safetyPolicy:$.safetyPolicy,now:_,maxChunkChars:$.maxChunkChars,chunkOverlapChars:$.chunkOverlapChars,maxItems:$.maxItems})}async function A1($){let _=($.now??new Date).toISOString(),J=$.maxChunkChars??4000,U=$.chunkOverlapChars??200,W=$.maxItems??Z3;if(J<500)throw Error("maxChunkChars must be at least 500.");if(U<0||U>=J)throw Error("chunkOverlapChars must be less than maxChunkChars.");if($.items.length>W)throw Error(`Manifest contains too many items: ${$.items.length} exceeds ${W} item limit.`);if($.safetyPolicy)d4($.dbPath,$.safetyPolicy);a($.dbPath);let X=m($.dbPath);try{return X.transaction(()=>{let Y=new Set,Q=new Set,q=0,L=0,N=0,R=0,B=[];__(X,{event_type:"source_read",action:$.readAction??($.sourceLabel.startsWith("s3://")?"s3_manifest_read":"local_manifest_read"),target_uri:$.sourceLabel,decision:"allow",metadata:{items:$.items.length,read_only:!0},created_at:_});for(let H of $.items){let V=Gv(H,_,{allowFileSourceRefs:$.allowFileSourceRefs});if(B.length0)return U}return null}function m3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function Hv($,_){let J=$.mode;if(typeof J==="string"&&J!=="read_only")throw Error(`Source resolver denied ${_}. Permission mode is ${J}, expected read_only.`);let U=$.denied_purposes;if(Array.isArray(U)&&U.includes(_))throw Error(`Source resolver denied ${_}. Purpose is explicitly denied.`);let W=$.allowed_purposes;if(Array.isArray(W)&&W.length>0&&!W.includes(_))throw Error(`Source resolver denied ${_}. Allowed purposes: ${W.join(", ")}`)}function Nv($,_,J){if(!_)return J;try{let U=B6($);if(U.kind==="open-files"&&U.entity==="file")return`${$}/revision/${encodeURIComponent(_.revision)}`}catch{return J}return J}function Vv($,_,J){return $.query(`SELECT id, uri, kind, title, metadata_json, acl_json, updated_at + metadata_json = excluded.metadata_json`,[D,$,g.revision,g.hash,g.extractedTextUri,JSON.stringify(g.metadata),U]);let I=_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get($,g.revision);if(!I)throw Error(`Failed to upsert source revision: ${g.sourceRef}`);return I.id}function j7(_,$,g,U,D,I,j){if(!g.text||g.status.toLowerCase()==="deleted")return{chunksInserted:0,redactions:0};let N=u_(g.text,j);if(N.findings.length>0)P0(_,{source_uri:g.sourceUri,findings:N.findings,metadata:{source_ref:g.sourceRef,revision:g.revision},created_at:U}),X_(_,{event_type:"redaction",action:"source_text_redact",target_uri:g.sourceUri,decision:"redacted",metadata:{findings:N.findings.length,source_ref:g.sourceRef,revision:g.revision},created_at:U});let O=$7(N.text,D,I);for(let A of O){let L=JE("chk",`${$}\x00${A.ordinal}\x00${A.text}`),z=T6({source_ref:g.sourceRef,source_uri:g.sourceUri,source_kind:g.kind,source_revision_id:$,revision:g.revision,hash:g.hash,chunk_id:L,start_offset:A.startOffset,end_offset:A.endOffset,status:g.status,resolver:"open-files-read-only"}),W=bS({source_ref:g.sourceRef,source_uri:g.sourceUri,source_kind:g.kind,source_revision_id:$,revision:g.revision,hash:g.hash,status:g.status,path:N_(g.raw.path)??null,mime:N_(g.raw.mime)??N_(g.raw.content_type)??null,size:cT(g.raw.size)??null},z);_.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[L,$,"source",A.ordinal,A.text,g7(A.text),A.startOffset,A.endOffset,JSON.stringify(W),U]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[L,A.text,g.title??"",g.sourceUri])}return{chunksInserted:O.length,redactions:N.findings.length}}async function oS(_){let $=_.now??new Date;if(_.safetyPolicy)_6(_.dbPath,_.safetyPolicy);h(_.dbPath);let g=await _7(_.input,_.config,_.safetyPolicy,_.maxInputBytes),U=aT(g),D=_.maxItems??iS;if(U.length>D)throw Error(`Manifest contains too many items: ${U.length} exceeds ${D} item limit.`);return $4({dbPath:_.dbPath,items:U,sourceLabel:_.input,allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")===!0,safetyPolicy:_.safetyPolicy,now:$,maxChunkChars:_.maxChunkChars,chunkOverlapChars:_.chunkOverlapChars,maxItems:_.maxItems})}async function $4(_){let $=(_.now??new Date).toISOString(),g=_.maxChunkChars??4000,U=_.chunkOverlapChars??200,D=_.maxItems??iS;if(g<500)throw Error("maxChunkChars must be at least 500.");if(U<0||U>=g)throw Error("chunkOverlapChars must be less than maxChunkChars.");if(_.items.length>D)throw Error(`Manifest contains too many items: ${_.items.length} exceeds ${D} item limit.`);if(_.safetyPolicy)_6(_.dbPath,_.safetyPolicy);h(_.dbPath);let I=v(_.dbPath);try{return I.transaction(()=>{let N=new Set,O=new Set,A=0,L=0,z=0,W=0,J=[];X_(I,{event_type:"source_read",action:_.readAction??(_.sourceLabel.startsWith("s3://")?"s3_manifest_read":"local_manifest_read"),target_uri:_.sourceLabel,decision:"allow",metadata:{items:_.items.length,read_only:!0},created_at:$});for(let P of _.items){let S=eT(P,$,{allowFileSourceRefs:_.allowFileSourceRefs});if(J.length0)return U}return null}function pS(_,$){for(let g of $){let U=_[g];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function N7(_,$){let g=_.mode;if(typeof g==="string"&&g!=="read_only")throw Error(`Source resolver denied ${$}. Permission mode is ${g}, expected read_only.`);let U=_.denied_purposes;if(Array.isArray(U)&&U.includes($))throw Error(`Source resolver denied ${$}. Purpose is explicitly denied.`);let D=_.allowed_purposes;if(Array.isArray(D)&&D.length>0&&!D.includes($))throw Error(`Source resolver denied ${$}. Allowed purposes: ${D.join(", ")}`)}function E7(_,$,g){if(!$)return g;try{let U=A$(_);if(U.kind==="open-files"&&U.entity==="file")return`${_}/revision/${encodeURIComponent($.revision)}`}catch{return g}return g}function O7(_,$,g){return _.query(`SELECT id, uri, kind, title, metadata_json, acl_json, updated_at FROM sources WHERE uri = ? OR uri = ? ORDER BY CASE WHEN uri = ? THEN 0 ELSE 1 END - LIMIT 1`).get(_,J,_)??null}function Rv($,_,J){if(J)return $.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at + LIMIT 1`).get($,g,$)??null}function A7(_,$,g){if(g)return _.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at FROM source_revisions WHERE source_id = ? AND revision = ? - LIMIT 1`).get(_,J)??null;return $.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at + LIMIT 1`).get($,g)??null;return _.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at FROM source_revisions WHERE source_id = ? ORDER BY created_at DESC, revision DESC - LIMIT 1`).get(_)??null}function Kv($,_){if(!_)return 0;return $.query("SELECT COUNT(*) AS n FROM chunks WHERE source_revision_id = ?").get(_)?.n??0}function Fv($,_,J){if(!_||J<=0)return[];return $.query(`SELECT id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json + LIMIT 1`).get($)??null}function L7(_,$){if(!$)return 0;return _.query("SELECT COUNT(*) AS n FROM chunks WHERE source_revision_id = ?").get($)?.n??0}function J7(_,$,g){if(!$||g<=0)return[];return _.query(`SELECT id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json FROM chunks WHERE source_revision_id = ? ORDER BY ordinal ASC - LIMIT ?`).all(_,J)}async function n9($){let _=$.purpose??"knowledge_answer",J=Math.max(0,Math.min($.limit??10,100)),U=($.now??new Date).toISOString(),W=B6($.sourceRef),X=F3($.sourceRef,W),G=E3($.sourceRef);if($.safetyPolicy){if(!$.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");d4($.dbPath,$.safetyPolicy)}a($.dbPath);let Y=m($.dbPath);try{return Y.transaction(()=>{let Q=Vv(Y,X,$.sourceRef);if(!Q)return __(Y,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:$.sourceRef,decision:"allow",metadata:{purpose:_,read_only:!0,source_uri:X},created_at:U}),{source_ref:$.sourceRef,source_uri:X,purpose:_,read_only:!0,resolved:!1,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:null,revision:null,content:{mime:null,size:null,hash:null,text_available:!1,chunks_total:0,chunks_returned:0,char_count_returned:0,extracted_text_ref:null,bytes_available:!1,bytes_exposed:!1},chunks:[],citations:[]};let q=d9(Q.metadata_json),L=d9(Q.acl_json);try{Hv(L,_)}catch(A){throw __(Y,{event_type:"source_read",action:"open_files_resolve",target_uri:$.sourceRef,decision:"deny",metadata:{purpose:_,read_only:!0,source_uri:Q.uri,error:A instanceof Error?A.message:String(A)},created_at:U}),A}let N=Rv(Y,Q.id,G),R=d9(N?.metadata_json),B=Kv(Y,N?.id??null),H=Fv(Y,N?.id??null,J),V=Nv(Q.uri,N,$.sourceRef),K=H.map((A)=>{let g=d9(A.metadata_json),v={resolver:"open-files-read-only",mode:"local_catalog",purpose:_,read_only:!0,source_ref:b1(g,["source_ref"])??V,source_uri:Q.uri,source_revision_id:N?.id??null,revision:N?.revision??null,hash:N?.hash??b1(g,["hash"]),chunk_id:A.id,start_offset:A.start_offset,end_offset:A.end_offset,resolved_at:U},k=E0({source_ref:v.source_ref,source_uri:v.source_uri,source_kind:Q.kind,source_revision_id:v.source_revision_id,revision:v.revision,hash:v.hash,chunk_id:A.id,start_offset:A.start_offset,end_offset:A.end_offset,status:b1(g,["status"]),resolver:v.resolver});return{id:A.id,kind:A.kind,ordinal:A.ordinal,text:A.text,token_count:A.token_count,start_offset:A.start_offset,end_offset:A.end_offset,metadata:g,evidence:v,provenance:k}}),E=K.map((A)=>({source_ref:A.evidence.source_ref,source_uri:Q.uri,chunk_id:A.id,quote:A.text.slice(0,500),start_offset:A.start_offset,end_offset:A.end_offset,evidence:A.evidence,provenance:A.provenance}));__(Y,{event_type:"source_read",action:"open_files_resolve",target_uri:$.sourceRef,decision:"allow",metadata:{purpose:_,read_only:!0,source_uri:Q.uri,revision:N?.revision??null,chunks_returned:K.length,chunks_total:B},created_at:U});let F=b1(q,["mime","content_type"])??b1(R,["mime","content_type"]),w=m3(q,["size","size_bytes"])??m3(R,["size","size_bytes"]);return{source_ref:V,source_uri:Q.uri,purpose:_,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:Q.id,uri:Q.uri,kind:Q.kind,title:Q.title,metadata:q,permissions:L,updated_at:Q.updated_at},revision:N?{id:N.id,revision:N.revision,hash:N.hash,extracted_text_uri:N.extracted_text_uri,metadata:R,created_at:N.created_at,reindex_required:R.reindex_required===!0}:null,content:{mime:F,size:w,hash:N?.hash??b1(q,["hash","checksum","sha256"]),text_available:B>0,chunks_total:B,chunks_returned:K.length,char_count_returned:K.reduce((A,g)=>A+g.text.length,0),extracted_text_ref:N?.extracted_text_uri??b1(R,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:K,citations:E}})()}finally{Y.close()}}function PJ($){return`sha256:${Ev("sha256").update($).digest("hex")}`}function bv($){return $.replace(//gi," ").replace(//gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+\n/g,` + LIMIT ?`).all($,g)}async function lU(_){let $=_.purpose??"knowledge_answer",g=Math.max(0,Math.min(_.limit??10,100)),U=(_.now??new Date).toISOString(),D=A$(_.sourceRef),I=kS(_.sourceRef,D),j=CS(_.sourceRef);if(_.safetyPolicy){if(!_.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");_6(_.dbPath,_.safetyPolicy)}h(_.dbPath);let N=v(_.dbPath);try{return N.transaction(()=>{let O=O7(N,I,_.sourceRef);if(!O)return X_(N,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:I},created_at:U}),{source_ref:_.sourceRef,source_uri:I,purpose:$,read_only:!0,resolved:!1,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:null,revision:null,content:{mime:null,size:null,hash:null,text_available:!1,chunks_total:0,chunks_returned:0,char_count_returned:0,extracted_text_ref:null,bytes_available:!1,bytes_exposed:!1},chunks:[],citations:[]};let A=iU(O.metadata_json),L=iU(O.acl_json);try{N7(L,$)}catch(Q){throw X_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"deny",metadata:{purpose:$,read_only:!0,source_uri:O.uri,error:Q instanceof Error?Q.message:String(Q)},created_at:U}),Q}let z=A7(N,O.id,j),W=iU(z?.metadata_json),J=L7(N,z?.id??null),P=J7(N,z?.id??null,g),S=E7(O.uri,z,_.sourceRef),X=P.map((Q)=>{let T=iU(Q.metadata_json),q={resolver:"open-files-read-only",mode:"local_catalog",purpose:$,read_only:!0,source_ref:g4(T,["source_ref"])??S,source_uri:O.uri,source_revision_id:z?.id??null,revision:z?.revision??null,hash:z?.hash??g4(T,["hash"]),chunk_id:Q.id,start_offset:Q.start_offset,end_offset:Q.end_offset,resolved_at:U},V=T6({source_ref:q.source_ref,source_uri:q.source_uri,source_kind:O.kind,source_revision_id:q.source_revision_id,revision:q.revision,hash:q.hash,chunk_id:Q.id,start_offset:Q.start_offset,end_offset:Q.end_offset,status:g4(T,["status"]),resolver:q.resolver});return{id:Q.id,kind:Q.kind,ordinal:Q.ordinal,text:Q.text,token_count:Q.token_count,start_offset:Q.start_offset,end_offset:Q.end_offset,metadata:T,evidence:q,provenance:V}}),G=X.map((Q)=>({source_ref:Q.evidence.source_ref,source_uri:O.uri,chunk_id:Q.id,quote:Q.text.slice(0,500),start_offset:Q.start_offset,end_offset:Q.end_offset,evidence:Q.evidence,provenance:Q.provenance}));X_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:O.uri,revision:z?.revision??null,chunks_returned:X.length,chunks_total:J},created_at:U});let R=g4(A,["mime","content_type"])??g4(W,["mime","content_type"]),K=pS(A,["size","size_bytes"])??pS(W,["size","size_bytes"]);return{source_ref:S,source_uri:O.uri,purpose:$,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:O.id,uri:O.uri,kind:O.kind,title:O.title,metadata:A,permissions:L,updated_at:O.updated_at},revision:z?{id:z.id,revision:z.revision,hash:z.hash,extracted_text_uri:z.extracted_text_uri,metadata:W,created_at:z.created_at,reindex_required:W.reindex_required===!0}:null,content:{mime:R,size:K,hash:z?.hash??g4(A,["hash","checksum","sha256"]),text_available:J>0,chunks_total:J,chunks_returned:X.length,char_count_returned:X.reduce((Q,T)=>Q+T.text.length,0),extracted_text_ref:z?.extracted_text_uri??g4(W,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:X,citations:G}})()}finally{N.close()}}function z0(_){return`sha256:${P7("sha256").update(_).digest("hex")}`}function W7(_){return _.replace(//gi," ").replace(//gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+\n/g,` `).replace(/\n\s+/g,` -`).replace(/[ \t]{2,}/g," ").trim()}async function wv($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 source URI: ${$}`);if(J)M0($,J);let[{S3Client:G,GetObjectCommand:Y},{fromIni:Q}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Q({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Y({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function gv($,_){if(_)fJ(_);let J=await C9($,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!J.ok)throw Error(`Web source read failed ${J.status}: ${$}`);let U=J.headers.get("content-type"),W=await J.text();return{text:U?.includes("html")?bv(W):W,mime:U}}function i9($){if($.kind==="file")return c9($.path);if($.kind==="s3")return c9($.key);if($.kind==="web")return c9(new URL($.url).pathname)||$.url;return $.path?c9($.path):$.id}async function x3($,_,J){if($.kind==="file"){if(!Mv($.path))throw Error(`Source file not found: ${$.path}`);let U=Av($.path,"utf8");return{text:U,contentSource:"file",title:i9($),mime:"text/plain",size:U.length,hash:PJ(U),revision:null,extractedTextRef:null,metadata:{path:$.path},permissions:{mode:"read_only"}}}if($.kind==="s3"){let U=await wv($.uri,_,J);return{text:U,contentSource:"s3",title:i9($),mime:"text/plain",size:U.length,hash:PJ(U),revision:null,extractedTextRef:null,metadata:{bucket:$.bucket,key:$.key},permissions:{mode:"read_only"}}}if($.kind==="web"){let U=await gv($.url,J);return{text:U.text,contentSource:"web",title:i9($),mime:U.mime,size:U.text.length,hash:PJ(U.text),revision:null,extractedTextRef:null,metadata:{url:$.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${$.uri}`)}async function kv($,_,J){if($.startsWith("open-files://"))throw Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://.");let U=B6($);return{text:(await x3(U,_,J)).text,contentSource:"extracted_text_ref"}}async function Iv($){let _=await n9({dbPath:$.dbPath,sourceRef:$.sourceRef,purpose:$.purpose??"knowledge_index",limit:100,safetyPolicy:$.safetyPolicy,now:$.now});if(!_.resolved)throw Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API.");if(_.revision?.extracted_text_uri&&!_.content.text_available){let U=await kv(_.revision.extracted_text_uri,$.config,$.safetyPolicy);return{text:U.text,contentSource:U.contentSource,title:_.source?.title??null,mime:_.content.mime,size:U.text.length,hash:_.revision.hash??PJ(U.text),revision:_.revision.revision,extractedTextRef:_.revision.extracted_text_uri,metadata:_.source?.metadata??{},permissions:_.source?.permissions??{mode:"read_only"}}}if(_.chunks.length===0)throw Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first.");let J=_.chunks.map((U)=>U.text).join(` +`).replace(/[ \t]{2,}/g," ").trim()}async function X7(_,$,g){let U=new URL(_),D=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!D||!I)throw Error(`Invalid S3 source URI: ${_}`);if(g)q6(_,g);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===D?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:D,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function R7(_,$){if($)J0($);let g=await vU(_,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!g.ok)throw Error(`Web source read failed ${g.status}: ${_}`);let U=g.headers.get("content-type"),D=await g.text();return{text:U?.includes("html")?W7(D):D,mime:U}}function oU(_){if(_.kind==="file")return tU(_.path);if(_.kind==="s3")return tU(_.key);if(_.kind==="web")return tU(new URL(_.url).pathname)||_.url;return _.path?tU(_.path):_.id}async function eS(_,$,g){if(_.kind==="file"){if(!z7(_.path))throw Error(`Source file not found: ${_.path}`);let U=S7(_.path,"utf8");return{text:U,contentSource:"file",title:oU(_),mime:"text/plain",size:U.length,hash:z0(U),revision:null,extractedTextRef:null,metadata:{path:_.path},permissions:{mode:"read_only"}}}if(_.kind==="s3"){let U=await X7(_.uri,$,g);return{text:U,contentSource:"s3",title:oU(_),mime:"text/plain",size:U.length,hash:z0(U),revision:null,extractedTextRef:null,metadata:{bucket:_.bucket,key:_.key},permissions:{mode:"read_only"}}}if(_.kind==="web"){let U=await R7(_.url,g);return{text:U.text,contentSource:"web",title:oU(_),mime:U.mime,size:U.text.length,hash:z0(U.text),revision:null,extractedTextRef:null,metadata:{url:_.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${_.uri}`)}async function G7(_,$,g){if(_.startsWith("open-files://"))throw Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://.");let U=A$(_);return{text:(await eS(U,$,g)).text,contentSource:"extracted_text_ref"}}async function Y7(_){let $=await lU({dbPath:_.dbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",limit:100,safetyPolicy:_.safetyPolicy,now:_.now});if(!$.resolved)throw Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API.");if($.revision?.extracted_text_uri&&!$.content.text_available){let U=await G7($.revision.extracted_text_uri,_.config,_.safetyPolicy);return{text:U.text,contentSource:U.contentSource,title:$.source?.title??null,mime:$.content.mime,size:U.text.length,hash:$.revision.hash??z0(U.text),revision:$.revision.revision,extractedTextRef:$.revision.extracted_text_uri,metadata:$.source?.metadata??{},permissions:$.source?.permissions??{mode:"read_only"}}}if($.chunks.length===0)throw Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first.");let g=$.chunks.map((U)=>U.text).join(` -`);return{text:J,contentSource:"catalog_chunks",title:_.source?.title??null,mime:_.content.mime,size:J.length,hash:_.revision?.hash??PJ(J),revision:_.revision?.revision??null,extractedTextRef:_.revision?.extracted_text_uri??null,metadata:_.source?.metadata??{},permissions:_.source?.permissions??{mode:"read_only"}}}function fv($,_,J,U){let W=J.hash??PJ(J.text),X={...j_(J.metadata),source_ref:$,content_source:J.contentSource,read_only:!0},G={source_ref:$,name:J.title??i9(_),mime:J.mime??"text/plain",size:J.size??J.text.length,hash:W,revision:J.revision??W,status:"active",updated_at:new Date().toISOString(),permissions:{mode:"read_only",allowed_purposes:[U],...J.permissions},metadata:X,extracted_text_ref:J.extractedTextRef,extracted_text:J.text};if(_.kind==="open-files"){if(_.entity==="file")G.file_id=_.id;if(_.entity==="source")G.source_id=_.id,G.path=_.path}if(_.kind==="file")G.path=_.path;if(_.kind==="s3")G.path=_.key;if(_.kind==="web")G.url=_.url;return G}async function l9($){let _=$.purpose??"knowledge_index";E1($.sourceRef,{allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1});let J=B6($.sourceRef),U=J.kind==="open-files"?await Iv($):await x3(J,$.config,$.safetyPolicy),W=fv($.sourceRef,J,U,_);return{...await A1({dbPath:$.dbPath,items:[W],sourceLabel:$.sourceRef,readAction:"source_ref_ingest_read",allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1,safetyPolicy:$.safetyPolicy,now:$.now}),source_ref:$.sourceRef,content_source:U.contentSource,read_only:!0,hash:String(W.hash)}}function r9($,_){return`${$}_${Cv("sha256").update(_).digest("hex").slice(0,20)}`}function Tv($){return $.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"note"}function ZQ($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function Sv($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function u3($){return Array.from(new Set(($??[]).map((_)=>_.trim()).filter(Boolean)))}function Zv($){let _=$.path?.trim()||`wiki/notes/${Tv($.title)}.md`,J=_.replace(/\\/g,"/");if(!J.startsWith("wiki/notes/")||!J.endsWith(".md"))throw Error("App wiki note paths must be relative wiki/notes/*.md artifact keys.");if(J.startsWith("/")||J.split("/").some((U)=>U===".."||U==="."))throw Error(`Invalid app wiki note path: ${_}`);return J}function vv($){let _=[`# ${$.title}`,"",$.content.trim(),"",`Updated: ${$.now}`];if($.tags.length>0)_.push("","Tags:",...$.tags.map((J)=>`- ${J}`));if($.sourceRefs.length>0)_.push("","Source refs:",...$.sourceRefs.map((J)=>`- ${J}`));return _.push(""),_.join(` -`)}async function d3($,_){let J=await $.put(_);return{key:J.key,uri:J.uri,kind:_.key.startsWith("logs/")?"log":"wiki_page",content_type:_.content_type,modified_at:J.modified_at,...IJ(_.body),metadata:{..._.metadata??{}}}}async function yv($,_,J){let U=String(J.getUTCFullYear()),W=String(J.getUTCMonth()+1).padStart(2,"0"),X=String(J.getUTCDate()).padStart(2,"0"),G=`logs/${U}/${W}/${X}.jsonl`,Y="";try{Y=await $.getText(G)}catch{Y=""}return d3($,{key:G,body:`${Y}${JSON.stringify(_)} -`,content_type:"application/x-ndjson",metadata:{provenance:X6({generated_from:String(_.event??"app_wiki_log"),artifact_key:G})}})}function hv($){return{...j_($.metadata??{}),app_wiki:!0,note:!0,artifact_key:$.path,tags:$.tags,source_refs:$.sourceRefs,provenance:$.provenance}}function vQ($){let _=ZQ($.metadata_json);return{id:$.id,path:$.path,title:$.title,artifact_uri:$.artifact_uri,content_hash:$.content_hash,tags:Array.isArray(_.tags)?_.tags.filter((J)=>typeof J==="string"):[],source_refs:Array.isArray(_.source_refs)?_.source_refs.filter((J)=>typeof J==="string"):[],created_at:$.created_at,updated_at:$.updated_at}}function mv($,_){return _.map((J)=>{let U=$.query(`SELECT +`);return{text:g,contentSource:"catalog_chunks",title:$.source?.title??null,mime:$.content.mime,size:g.length,hash:$.revision?.hash??z0(g),revision:$.revision?.revision??null,extractedTextRef:$.revision?.extracted_text_uri??null,metadata:$.source?.metadata??{},permissions:$.source?.permissions??{mode:"read_only"}}}function Q7(_,$,g,U){let D=g.hash??z0(g.text),I={...q_(g.metadata),source_ref:_,content_source:g.contentSource,read_only:!0},j={source_ref:_,name:g.title??oU($),mime:g.mime??"text/plain",size:g.size??g.text.length,hash:D,revision:g.revision??D,status:"active",updated_at:new Date().toISOString(),permissions:{mode:"read_only",allowed_purposes:[U],...g.permissions},metadata:I,extracted_text_ref:g.extractedTextRef,extracted_text:g.text};if($.kind==="open-files"){if($.entity==="file")j.file_id=$.id;if($.entity==="source")j.source_id=$.id,j.path=$.path}if($.kind==="file")j.path=$.path;if($.kind==="s3")j.path=$.key;if($.kind==="web")j.url=$.url;return j}async function pU(_){let $=_.purpose??"knowledge_index";s6(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1});let g=A$(_.sourceRef),U=g.kind==="open-files"?await Y7(_):await eS(g,_.config,_.safetyPolicy),D=Q7(_.sourceRef,g,U,$);return{...await $4({dbPath:_.dbPath,items:[D],sourceLabel:_.sourceRef,readAction:"source_ref_ingest_read",allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1,safetyPolicy:_.safetyPolicy,now:_.now}),source_ref:_.sourceRef,content_source:U.contentSource,read_only:!0,hash:String(D.hash)}}function eU(_,$){return`${_}_${T7("sha256").update($).digest("hex").slice(0,20)}`}function B7(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"note"}function PE(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function K7(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function aS(_){return Array.from(new Set((_??[]).map(($)=>$.trim()).filter(Boolean)))}function V7(_){let $=_.path?.trim()||`wiki/notes/${B7(_.title)}.md`,g=$.replace(/\\/g,"/");if(!g.startsWith("wiki/notes/")||!g.endsWith(".md"))throw Error("App wiki note paths must be relative wiki/notes/*.md artifact keys.");if(g.startsWith("/")||g.split("/").some((U)=>U===".."||U==="."))throw Error(`Invalid app wiki note path: ${$}`);return g}function F7(_){let $=[`# ${_.title}`,"",_.content.trim(),"",`Updated: ${_.now}`];if(_.tags.length>0)$.push("","Tags:",..._.tags.map((g)=>`- ${g}`));if(_.sourceRefs.length>0)$.push("","Source refs:",..._.sourceRefs.map((g)=>`- ${g}`));return $.push(""),$.join(` +`)}async function sS(_,$){let g=await _.put($);return{key:g.key,uri:g.uri,kind:$.key.startsWith("logs/")?"log":"wiki_page",content_type:$.content_type,modified_at:g.modified_at,...L0($.body),metadata:{...$.metadata??{}}}}async function M7(_,$,g){let U=String(g.getUTCFullYear()),D=String(g.getUTCMonth()+1).padStart(2,"0"),I=String(g.getUTCDate()).padStart(2,"0"),j=`logs/${U}/${D}/${I}.jsonl`,N="";try{N=await _.getText(j)}catch{N=""}return sS(_,{key:j,body:`${N}${JSON.stringify($)} +`,content_type:"application/x-ndjson",metadata:{provenance:U$({generated_from:String($.event??"app_wiki_log"),artifact_key:j})}})}function Z7(_){return{...q_(_.metadata??{}),app_wiki:!0,note:!0,artifact_key:_.path,tags:_.tags,source_refs:_.sourceRefs,provenance:_.provenance}}function zE(_){let $=PE(_.metadata_json);return{id:_.id,path:_.path,title:_.title,artifact_uri:_.artifact_uri,content_hash:_.content_hash,tags:Array.isArray($.tags)?$.tags.filter((g)=>typeof g==="string"):[],source_refs:Array.isArray($.source_refs)?$.source_refs.filter((g)=>typeof g==="string"):[],created_at:_.created_at,updated_at:_.updated_at}}function b7(_,$){return $.map((g)=>{let U=_.query(`SELECT s.uri AS source_uri, c.id AS chunk_id, c.text, @@ -645,13 +646,13 @@ VALUES (10, datetime('now')); LEFT JOIN chunks c ON c.source_revision_id = sr.id WHERE s.uri = ? OR s.metadata_json LIKE ? ORDER BY sr.created_at DESC, c.ordinal ASC - LIMIT 1`).get(J,`%${J}%`),W=ZQ(U?.metadata_json);return{source_ref:J,source_uri:U?.source_uri??J,chunk_id:U?.chunk_id??null,quote:U?.text?U.text.replace(/\s+/g," ").slice(0,240):null,start_offset:U?.start_offset??null,end_offset:U?.end_offset??null,metadata:{source_ref:J,revision:U?.revision??W.revision,hash:U?.hash??W.hash}}})}function xv($,_,J,U){$.run("DELETE FROM citations WHERE wiki_page_id = ?",[_]);let W=mv($,J);for(let X of W)$.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r9("cit",`${_}\x00${X.source_uri}\x00${X.chunk_id??Pv()}`),_,X.chunk_id,X.source_uri,X.quote,X.start_offset,X.end_offset,JSON.stringify(X.metadata),U]);return W.length}function uv($,_){$.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + LIMIT 1`).get(g,`%${g}%`),D=PE(U?.metadata_json);return{source_ref:g,source_uri:U?.source_uri??g,chunk_id:U?.chunk_id??null,quote:U?.text?U.text.replace(/\s+/g," ").slice(0,240):null,start_offset:U?.start_offset??null,end_offset:U?.end_offset??null,metadata:{source_ref:g,revision:U?.revision??D.revision,hash:U?.hash??D.hash}}})}function H7(_,$,g,U){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);let D=b7(_,g);for(let I of D)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[eU("cit",`${$}\x00${I.source_uri}\x00${I.chunk_id??q7()}`),$,I.chunk_id,I.source_uri,I.quote,I.start_offset,I.end_offset,JSON.stringify(I.metadata),U]);return D.length}function k7(_,$){_.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[r9("idx",`app-wiki-note\x00${_.path}`),"app_wiki_note",_.title,_.artifactUri,_.path,JSON.stringify({artifact_key:_.path,content_hash:_.contentHash,tags:_.tags,source_refs:_.sourceRefs}),_.now,_.now])}function dv($,_){$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + updated_at = excluded.updated_at`,[eU("idx",`app-wiki-note\x00${$.path}`),"app_wiki_note",$.title,$.artifactUri,$.path,JSON.stringify({artifact_key:$.path,content_hash:$.contentHash,tags:$.tags,source_refs:$.sourceRefs}),$.now,$.now])}function C7(_,$){_.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title = excluded.title, @@ -659,22 +660,22 @@ VALUES (10, datetime('now')); content_hash = excluded.content_hash, status = excluded.status, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[_.pageId,_.path,_.title,_.artifactUri,_.contentHash,"active",JSON.stringify(_.metadata),_.now,_.now]);let J=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_.pageId);for(let W of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[W.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_.pageId]);let U=r9("chk",`${_.pageId}\x00${_.contentHash}`);$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.pageId,"wiki",0,_.body,Sv(_.body),0,_.body.length,JSON.stringify({..._.metadata,artifact_uri:_.artifactUri,content_hash:_.contentHash}),_.now]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,_.body,_.title,_.artifactUri])}function FU($){if($.scope==="global"&&$.allowGlobal!==!0)throw Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global.");if($.workspace.home.includes("/.husna/")||$.workspace.home.endsWith("/.husna"))throw Error(`Refusing app-wiki writes to legacy .husna path: ${$.workspace.home}`);if($.workspace.home.includes("/.hasna/apps/knowledge"))throw Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${$.workspace.home}`);if($.safetyPolicy)d4($.workspace.knowledgeDbPath,$.safetyPolicy)}async function n3($){FU($);let _=a($.workspace.knowledgeDbPath),J=m($.workspace.knowledgeDbPath);try{__(J,{event_type:"write",action:"app_wiki_init",target_uri:$.workspace.home,decision:"allow",metadata:{scope:$.scope,store_type:$.store.type,app_path:".hasna/knowledge"},created_at:($.now??new Date).toISOString()})}finally{J.close()}return{ok:!0,scope:$.scope,workspace_home:$.workspace.home,knowledge_db_path:$.workspace.knowledgeDbPath,schema_version:_.schema_version,store_type:$.store.type,global_write_allowed:$.scope==="global"&&$.allowGlobal===!0,message:`Initialized app wiki scope at ${$.workspace.home}`}}async function c3($){FU($);let _=$.now??new Date,J=_.toISOString(),U=u3($.tags),W=u3($.sourceRefs);for(let N of W)E1(N,{allowFileSourceRefs:$.safetyPolicy?.readOnlySourceAccess===!0});let X=Zv($),G=vv({title:$.title,content:$.content,tags:U,sourceRefs:W,now:J}),Y=X6({generated_from:"app_wiki_note",artifact_key:X,source_refs:W}),Q=await d3($.store,{key:X,body:G,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:Y,scope:$.scope,tags:U.join(","),source_refs:W.join(",")}}),q=await yv($.store,{ts:J,event:"app_wiki_note_written",page_key:X,source_refs:W,tags:U},_);a($.workspace.knowledgeDbPath);let L=m($.workspace.knowledgeDbPath);try{let N=r9("wiki",X),R=hv({path:X,tags:U,sourceRefs:W,provenance:Y,metadata:$.metadata});u4(L,[Q,q],_),dv(L,{pageId:N,path:X,title:$.title,artifactUri:Q.uri,contentHash:Q.hash??"",body:G,metadata:R,now:J});let B=xv(L,N,W,J);uv(L,{title:$.title,path:X,artifactUri:Q.uri,contentHash:Q.hash??"",tags:U,sourceRefs:W,now:J}),__(L,{event_type:"write",action:"app_wiki_note_write",target_uri:Q.uri,decision:"allow",metadata:{scope:$.scope,path:X,source_refs:W,tags:U},created_at:J});let H=L.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(N);if(!H)throw Error(`Failed to write app wiki note: ${X}`);return{ok:!0,scope:$.scope,workspace_home:$.workspace.home,note:vQ(H),artifact_uri:Q.uri,content_hash:Q.hash??"",citations_written:B,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${X}`}}finally{L.close()}}function i3($){let _=Math.max(1,Math.min($.limit??50,200));if(!$.dbPath)return[];a($.dbPath);let J=m($.dbPath);try{return J.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + updated_at = excluded.updated_at`,[$.pageId,$.path,$.title,$.artifactUri,$.contentHash,"active",JSON.stringify($.metadata),$.now,$.now]);let g=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($.pageId);for(let D of g)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[D.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$.pageId]);let U=eU("chk",`${$.pageId}\x00${$.contentHash}`);_.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,$.pageId,"wiki",0,$.body,K7($.body),0,$.body.length,JSON.stringify({...$.metadata,artifact_uri:$.artifactUri,content_hash:$.contentHash}),$.now]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,$.body,$.title,$.artifactUri])}function wg(_){if(_.scope==="global"&&_.allowGlobal!==!0)throw Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global.");if(_.workspace.home.includes("/.husna/")||_.workspace.home.endsWith("/.husna"))throw Error(`Refusing app-wiki writes to legacy .husna path: ${_.workspace.home}`);if(_.workspace.home.includes("/.hasna/apps/knowledge"))throw Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${_.workspace.home}`);if(_.safetyPolicy)_6(_.workspace.knowledgeDbPath,_.safetyPolicy)}async function _W(_){wg(_);let $=h(_.workspace.knowledgeDbPath),g=v(_.workspace.knowledgeDbPath);try{X_(g,{event_type:"write",action:"app_wiki_init",target_uri:_.workspace.home,decision:"allow",metadata:{scope:_.scope,store_type:_.store.type,app_path:".hasna/knowledge"},created_at:(_.now??new Date).toISOString()})}finally{g.close()}return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,knowledge_db_path:_.workspace.knowledgeDbPath,schema_version:$.schema_version,store_type:_.store.type,global_write_allowed:_.scope==="global"&&_.allowGlobal===!0,message:`Initialized app wiki scope at ${_.workspace.home}`}}async function $W(_){wg(_);let $=_.now??new Date,g=$.toISOString(),U=aS(_.tags),D=aS(_.sourceRefs);for(let z of D)s6(z,{allowFileSourceRefs:_.safetyPolicy?.readOnlySourceAccess===!0});let I=V7(_),j=F7({title:_.title,content:_.content,tags:U,sourceRefs:D,now:g}),N=U$({generated_from:"app_wiki_note",artifact_key:I,source_refs:D}),O=await sS(_.store,{key:I,body:j,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:N,scope:_.scope,tags:U.join(","),source_refs:D.join(",")}}),A=await M7(_.store,{ts:g,event:"app_wiki_note_written",page_key:I,source_refs:D,tags:U},$);h(_.workspace.knowledgeDbPath);let L=v(_.workspace.knowledgeDbPath);try{let z=eU("wiki",I),W=Z7({path:I,tags:U,sourceRefs:D,provenance:N,metadata:_.metadata});s$(L,[O,A],$),C7(L,{pageId:z,path:I,title:_.title,artifactUri:O.uri,contentHash:O.hash??"",body:j,metadata:W,now:g});let J=H7(L,z,D,g);k7(L,{title:_.title,path:I,artifactUri:O.uri,contentHash:O.hash??"",tags:U,sourceRefs:D,now:g}),X_(L,{event_type:"write",action:"app_wiki_note_write",target_uri:O.uri,decision:"allow",metadata:{scope:_.scope,path:I,source_refs:D,tags:U},created_at:g});let P=L.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(z);if(!P)throw Error(`Failed to write app wiki note: ${I}`);return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,note:zE(P),artifact_uri:O.uri,content_hash:O.hash??"",citations_written:J,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${I}`}}finally{L.close()}}function gW(_){let $=Math.max(1,Math.min(_.limit??50,200));if(!_.dbPath)return[];h(_.dbPath);let g=v(_.dbPath);try{return g.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE status = 'active' AND path LIKE 'wiki/notes/%' AND metadata_json LIKE '%"app_wiki":true%' ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(_).map(vQ)}finally{J.close()}}async function l3($){a($.dbPath);let _=m($.dbPath);try{let J=_.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + LIMIT ?`).all($).map(zE)}finally{g.close()}}async function DW(_){h(_.dbPath);let $=v(_.dbPath);try{let g=$.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE (id = ? OR path = ?) AND path LIKE 'wiki/notes/%' - AND metadata_json LIKE '%"app_wiki":true%'`).get($.id,$.id);if(!J)return null;let U=_.query(`SELECT id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at + AND metadata_json LIKE '%"app_wiki":true%'`).get(_.id,_.id);if(!g)return null;let U=$.query(`SELECT id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at FROM citations WHERE wiki_page_id = ? - ORDER BY created_at ASC`).all(J.id).map((X)=>({...X,metadata:ZQ(X.metadata_json),metadata_json:void 0})),W=null;if($.includeContent!==!1)try{W=await $.store.getText(J.path)}catch{W=null}return{ok:!0,note:vQ(J),citations:U,content:W}}finally{_.close()}}async function r3($){return FU($),E1($.sourceRef,{allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1}),l9({dbPath:$.workspace.knowledgeDbPath,sourceRef:$.sourceRef,purpose:$.purpose??"knowledge_index",config:$.config,safetyPolicy:$.safetyPolicy})}import{randomUUID as iQ}from"crypto";import{randomUUID as nv}from"crypto";var yQ={openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},cv={openai:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!0,reasoning:!0,embeddings:!0},anthropic:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!1,reasoning:!0,embeddings:!1},deepseek:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!1,native_web_search:!1,reasoning:!0,embeddings:!1}},iv={default:"openai:gpt-5.2",fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"};function o3($){return $?.providers??{}}function n4($,_){let J=o3($)[_]??{};return{...yQ[_],...J}}function t3($){let _=o3($);return{...iv,..._.default_model?{default:_.default_model}:{},..._.aliases??{}}}function w_($){let[_,...J]=$.split(":"),U=J.join(":");if(_!=="openai"&&_!=="anthropic"&&_!=="deepseek")throw Error(`Unsupported AI provider: ${_}`);if(!U)throw Error(`Invalid model ref: ${$}. Expected provider:model.`);return{provider:_,model:U}}function y6($,_){return t3(_)[$]??$}function hQ($){let _=t3($);return Object.entries(_).map(([J,U])=>{let W=w_(U);return{alias:J,model_ref:U,provider:W.provider,model:W.model,default:J==="default",capabilities:cv[W.provider]}})}function a3($,_=process.env){return Object.keys(yQ).map((J)=>{let U=n4($,J),W=Boolean(_[U.api_key_env]);return{provider:J,api_key_env:U.api_key_env,configured:W,source:W?"env":"missing",base_url:U.base_url??null,default_model:U.default_model}})}function s3($,_=process.env){return{default_model:y6("default",$),providers:a3($,_),models:hQ($)}}function w1($,_,J=process.env){let U=a3(_,J).find((W)=>W.provider===$);if(!U)throw Error(`Unsupported AI provider: ${$}`);if(!U.configured)throw Error(`Missing ${U.api_key_env} for ${$}. Set the env var to use this provider.`);return U}async function lv($){if($==="openai"){let{createOpenAI:J}=await import("@ai-sdk/openai");return J}if($==="anthropic"){let{createAnthropic:J}=await import("@ai-sdk/anthropic");return J}let{createDeepSeek:_}=await import("@ai-sdk/deepseek");return _}async function rv($={}){let{createProviderRegistry:_}=await import("ai"),J=$.env??process.env,U={};for(let W of Object.keys(yQ)){let X=n4($.config,W),G=J[X.api_key_env];if(!G)continue;let Y=$.factories?.[W]??await lv(W);U[W]=Y({apiKey:G,baseURL:X.base_url})}return _(U)}async function EU($,_={}){let J=y6($,_.config),U=w_(J);return w1(U.provider,_.config,_.env),(await rv(_)).languageModel(J)}function p3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return 0}function g1($){let _=$.usage??{};return{provider:$.provider,model:$.model,input_tokens:p3(_,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:p3(_,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:$.costUsd??0,metadata:{usage:_,provider_metadata:$.providerMetadata??{}}}}function TJ($,_){let J=`usage_${nv()}`;return $.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[J,_.run_id??null,_.provider,_.model,_.input_tokens,_.output_tokens,_.cost_usd,JSON.stringify(_.metadata),_.created_at??new Date().toISOString()]),J}import{createHash as Vy}from"crypto";import{existsSync as _y,readFileSync as Jy}from"fs";import{createHash as _V}from"crypto";var pv="openai:text-embedding-3-small",JV=1536;function p9($){return $?.embeddings??{}}function e3($,_){return`${$}_${_V("sha256").update(_).digest("hex").slice(0,20)}`}function xQ($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function h6($,_){for(let J of _){let U=$[J];if(typeof U==="string"&&U.length>0)return U}return null}function $V($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function mQ($){return Math.sqrt($.reduce((_,J)=>_+J*J,0))}function ov($,_,J=mQ(_)){let U=mQ($);if(U===0||J===0)return 0;let W=Math.min($.length,_.length),X=0;for(let G=0;G{let X=J[W%J.length]/255;return Number((X*2-1).toFixed(6))})}async function av($,_,J=process.env){w1("openai",_,J);let U=n4(_,"openai"),{createOpenAI:W}=await import("@ai-sdk/openai"),X=W({apiKey:J[U.api_key_env],baseURL:U.base_url});if(X.embeddingModel)return X.embeddingModel($);if(X.textEmbedding)return X.textEmbedding($);if(X.textEmbeddingModel)return X.textEmbeddingModel($);throw Error("OpenAI provider does not expose an embedding model factory.")}function k1($,_){if(!$||$==="default"||$==="embedding")return p9(_).default_model??pv;return $}async function WV($,_={}){let J=k1(_.modelRef,_.config),U=w_(J);if(U.provider!=="openai")throw Error(`Embedding provider ${U.provider} is not supported yet. Use openai:text-embedding-3-small.`);let W=_.dimensions??p9(_.config).dimensions??JV;if(_.fake)return{provider:U.provider,model:U.model,dimensions:W,vectors:$.map((q)=>tv(q,W)),usage:{input_tokens:$.reduce((q,L)=>q+Math.max(1,Math.ceil(L.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:X}=await import("ai"),G=await av(U.model,_.config,_.env),Y=await X({model:G,values:$,maxParallelCalls:_.maxParallelCalls??p9(_.config).max_parallel_calls,providerOptions:{openai:{dimensions:W}}}),Q=Y.embeddings;return{provider:U.provider,model:U.model,dimensions:Q[0]?.length??W,vectors:Q,usage:{input_tokens:Y.usage?.tokens??0}}}function sv($,_){if(_.sourceRevisionId)return $.query(`SELECT + ORDER BY created_at ASC`).all(g.id).map((I)=>({...I,metadata:PE(I.metadata_json),metadata_json:void 0})),D=null;if(_.includeContent!==!1)try{D=await _.store.getText(g.path)}catch{D=null}return{ok:!0,note:zE(g),citations:U,content:D}}finally{$.close()}}async function UW(_){return wg(_),s6(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1}),pU({dbPath:_.workspace.knowledgeDbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",config:_.config,safetyPolicy:_.safetyPolicy})}import{randomUUID as qE}from"crypto";import{randomUUID as r7}from"crypto";var SE={openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},v7={openai:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!0,reasoning:!0,embeddings:!0},anthropic:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!1,reasoning:!0,embeddings:!1},deepseek:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!1,native_web_search:!1,reasoning:!0,embeddings:!1}},f7={default:"openai:gpt-5.2",fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"};function jW(_){return _?.providers??{}}function $6(_,$){let g=jW(_)[$]??{};return{...SE[$],...g}}function NW(_){let $=jW(_);return{...f7,...$.default_model?{default:$.default_model}:{},...$.aliases??{}}}function f_(_){let[$,...g]=_.split(":"),U=g.join(":");if($!=="openai"&&$!=="anthropic"&&$!=="deepseek")throw Error(`Unsupported AI provider: ${$}`);if(!U)throw Error(`Invalid model ref: ${_}. Expected provider:model.`);return{provider:$,model:U}}function G$(_,$){return NW($)[_]??_}function WE(_){let $=NW(_);return Object.entries($).map(([g,U])=>{let D=f_(U);return{alias:g,model_ref:U,provider:D.provider,model:D.model,default:g==="default",capabilities:v7[D.provider]}})}function EW(_,$=process.env){return Object.keys(SE).map((g)=>{let U=$6(_,g),D=Boolean($[U.api_key_env]);return{provider:g,api_key_env:U.api_key_env,configured:D,source:D?"env":"missing",base_url:U.base_url??null,default_model:U.default_model}})}function OW(_,$=process.env){return{default_model:G$("default",_),providers:EW(_,$),models:WE(_)}}function D4(_,$,g=process.env){let U=EW($,g).find((D)=>D.provider===_);if(!U)throw Error(`Unsupported AI provider: ${_}`);if(!U.configured)throw Error(`Missing ${U.api_key_env} for ${_}. Set the env var to use this provider.`);return U}async function w7(_){if(_==="openai"){let{createOpenAI:g}=await import("@ai-sdk/openai");return g}if(_==="anthropic"){let{createAnthropic:g}=await import("@ai-sdk/anthropic");return g}let{createDeepSeek:$}=await import("@ai-sdk/deepseek");return $}async function u7(_={}){let{createProviderRegistry:$}=await import("ai"),g=_.env??process.env,U={};for(let D of Object.keys(SE)){let I=$6(_.config,D),j=g[I.api_key_env];if(!j)continue;let N=_.factories?.[D]??await w7(D);U[D]=N({apiKey:j,baseURL:I.base_url})}return $(U)}async function ug(_,$={}){let g=G$(_,$.config),U=f_(g);return D4(U.provider,$.config,$.env),(await u7($)).languageModel(g)}function IW(_,$){for(let g of $){let U=_[g];if(typeof U==="number"&&Number.isFinite(U))return U}return 0}function U4(_){let $=_.usage??{};return{provider:_.provider,model:_.model,input_tokens:IW($,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:IW($,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:_.costUsd??0,metadata:{usage:$,provider_metadata:_.providerMetadata??{}}}}function S0(_,$){let g=`usage_${r7()}`;return _.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[g,$.run_id??null,$.provider,$.model,$.input_tokens,$.output_tokens,$.cost_usd,JSON.stringify($.metadata),$.created_at??new Date().toISOString()]),g}import{createHash as Oq}from"crypto";import{existsSync as i7,readFileSync as l7}from"fs";import{createHash as JW}from"crypto";var x7="openai:text-embedding-3-small",PW=1536;function aU(_){return _?.embeddings??{}}function AW(_,$){return`${_}_${JW("sha256").update($).digest("hex").slice(0,20)}`}function RE(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function Y$(_,$){for(let g of $){let U=_[g];if(typeof U==="string"&&U.length>0)return U}return null}function LW(_,$){for(let g of $){let U=_[g];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function XE(_){return Math.sqrt(_.reduce(($,g)=>$+g*g,0))}function y7(_,$,g=XE($)){let U=XE(_);if(U===0||g===0)return 0;let D=Math.min(_.length,$.length),I=0;for(let j=0;j{let I=g[D%g.length]/255;return Number((I*2-1).toFixed(6))})}async function c7(_,$,g=process.env){D4("openai",$,g);let U=$6($,"openai"),{createOpenAI:D}=await import("@ai-sdk/openai"),I=D({apiKey:g[U.api_key_env],baseURL:U.base_url});if(I.embeddingModel)return I.embeddingModel(_);if(I.textEmbedding)return I.textEmbedding(_);if(I.textEmbeddingModel)return I.textEmbeddingModel(_);throw Error("OpenAI provider does not expose an embedding model factory.")}function I4(_,$){if(!_||_==="default"||_==="embedding")return aU($).default_model??x7;return _}async function zW(_,$={}){let g=I4($.modelRef,$.config),U=f_(g);if(U.provider!=="openai")throw Error(`Embedding provider ${U.provider} is not supported yet. Use openai:text-embedding-3-small.`);let D=$.dimensions??aU($.config).dimensions??PW;if($.fake)return{provider:U.provider,model:U.model,dimensions:D,vectors:_.map((A)=>h7(A,D)),usage:{input_tokens:_.reduce((A,L)=>A+Math.max(1,Math.ceil(L.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:I}=await import("ai"),j=await c7(U.model,$.config,$.env),N=await I({model:j,values:_,maxParallelCalls:$.maxParallelCalls??aU($.config).max_parallel_calls,providerOptions:{openai:{dimensions:D}}}),O=N.embeddings;return{provider:U.provider,model:U.model,dimensions:O[0]?.length??D,vectors:O,usage:{input_tokens:N.usage?.tokens??0}}}function n7(_,$){if($.sourceRevisionId)return _.query(`SELECT c.id, c.text, c.token_count, @@ -693,7 +694,7 @@ VALUES (10, datetime('now')); ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? WHERE v.id IS NULL AND c.source_revision_id = ? ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`).all(_.provider,_.model,_.sourceRevisionId,_.limit);return $.query(`SELECT + LIMIT ?`).all($.provider,$.model,$.sourceRevisionId,$.limit);return _.query(`SELECT c.id, c.text, c.token_count, @@ -712,14 +713,14 @@ VALUES (10, datetime('now')); ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? WHERE v.id IS NULL ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`).all(_.provider,_.model,_.limit)}function ev($){let _=xQ($.metadata_json),J=_.provenance;if(J&&typeof J==="object"&&!Array.isArray(J))return J;return E0({source_ref:h6(_,["source_ref"]),source_uri:$.source_uri??h6(_,["source_uri"]),source_kind:$.source_kind??h6(_,["source_kind"]),source_revision_id:$.source_revision_id,revision:$.revision??h6(_,["revision"]),hash:$.hash??h6(_,["hash"]),chunk_id:$.id,start_offset:$.start_offset??$V(_,["start_offset"]),end_offset:$.end_offset??$V(_,["end_offset"]),status:h6(_,["status"]),resolver:"open-files-read-only"})}function $y($,_,J,U){let W=$.prepare(` + LIMIT ?`).all($.provider,$.model,$.limit)}function d7(_){let $=RE(_.metadata_json),g=$.provenance;if(g&&typeof g==="object"&&!Array.isArray(g))return g;return T6({source_ref:Y$($,["source_ref"]),source_uri:_.source_uri??Y$($,["source_uri"]),source_kind:_.source_kind??Y$($,["source_kind"]),source_revision_id:_.source_revision_id,revision:_.revision??Y$($,["revision"]),hash:_.hash??Y$($,["hash"]),chunk_id:_.id,start_offset:_.start_offset??LW($,["start_offset"]),end_offset:_.end_offset??LW($,["end_offset"]),status:Y$($,["status"]),resolver:"open-files-read-only"})}function m7(_,$,g,U){let D=_.prepare(` INSERT INTO chunk_embeddings (id, chunk_id, provider, model, dimensions, vector_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(chunk_id, provider, model) DO UPDATE SET dimensions = excluded.dimensions, vector_json = excluded.vector_json, created_at = excluded.created_at - `),X=$.prepare(` + `),I=_.prepare(` INSERT INTO vector_index_entries ( id, chunk_id, source_revision_id, provider, model, dimensions, vector_json, vector_norm, source_uri, source_ref, revision, hash, start_offset, end_offset, token_count, status, @@ -741,10 +742,10 @@ VALUES (10, datetime('now')); status = excluded.status, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);return $.transaction(()=>{for(let Y=0;Y<_.length;Y+=1){let Q=_[Y],q=J.vectors[Y];if(!q)continue;let L=xQ(Q.metadata_json),N=ev(Q),R=N.source_ref??h6(L,["source_ref"]),B=N.source_uri??Q.source_uri??h6(L,["source_uri"]),H=N.revision??Q.revision??h6(L,["revision"]),V=N.hash??Q.hash??h6(L,["hash"]),K=N.status??h6(L,["status"])??"active",E=JSON.stringify(q);W.run(e3("emb",`${Q.id}\x00${J.provider}\x00${J.model}`),Q.id,J.provider,J.model,J.dimensions,E,U),X.run(e3("vec",`${Q.id}\x00${J.provider}\x00${J.model}`),Q.id,Q.source_revision_id,J.provider,J.model,J.dimensions,E,mQ(q),B,R,H,V,N.start_offset,N.end_offset,Q.token_count,K,JSON.stringify({...L,provenance:N,embedded_at:U}),U,U)}})(),_.length}async function o9($){let _=k1($.modelRef,$.config),J=w_(_);if(J.provider!=="openai")throw Error(`Embedding provider ${J.provider} is not supported yet.`);let U=($.now??new Date).toISOString(),W=Math.max(1,Math.min($.limit??100,1000));a($.dbPath);let X=m($.dbPath),G;try{G=sv(X,{provider:J.provider,model:J.model,limit:W,sourceRevisionId:$.sourceRevisionId})}finally{X.close()}if(G.length===0)return{provider:J.provider,model:J.model,dimensions:$.dimensions??p9($.config).dimensions??JV,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let Y=await WV(G.map((q)=>q.text),$),Q=m($.dbPath);try{let q=$y(Q,G,Y,U);return{provider:Y.provider,model:Y.model,dimensions:Y.dimensions,chunks_seen:G.length,chunks_embedded:G.length,embeddings_upserted:q,vector_entries_upserted:q,usage:Y.usage}}finally{Q.close()}}function UV($){a($);let _=m($);try{let J=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,W=_.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at + `);return _.transaction(()=>{for(let N=0;N<$.length;N+=1){let O=$[N],A=g.vectors[N];if(!A)continue;let L=RE(O.metadata_json),z=d7(O),W=z.source_ref??Y$(L,["source_ref"]),J=z.source_uri??O.source_uri??Y$(L,["source_uri"]),P=z.revision??O.revision??Y$(L,["revision"]),S=z.hash??O.hash??Y$(L,["hash"]),X=z.status??Y$(L,["status"])??"active",G=JSON.stringify(A);D.run(AW("emb",`${O.id}\x00${g.provider}\x00${g.model}`),O.id,g.provider,g.model,g.dimensions,G,U),I.run(AW("vec",`${O.id}\x00${g.provider}\x00${g.model}`),O.id,O.source_revision_id,g.provider,g.model,g.dimensions,G,XE(A),J,W,P,S,z.start_offset,z.end_offset,O.token_count,X,JSON.stringify({...L,provenance:z,embedded_at:U}),U,U)}})(),$.length}async function sU(_){let $=I4(_.modelRef,_.config),g=f_($);if(g.provider!=="openai")throw Error(`Embedding provider ${g.provider} is not supported yet.`);let U=(_.now??new Date).toISOString(),D=Math.max(1,Math.min(_.limit??100,1000));h(_.dbPath);let I=v(_.dbPath),j;try{j=n7(I,{provider:g.provider,model:g.model,limit:D,sourceRevisionId:_.sourceRevisionId})}finally{I.close()}if(j.length===0)return{provider:g.provider,model:g.model,dimensions:_.dimensions??aU(_.config).dimensions??PW,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let N=await zW(j.map((A)=>A.text),_),O=v(_.dbPath);try{let A=m7(O,j,N,U);return{provider:N.provider,model:N.model,dimensions:N.dimensions,chunks_seen:j.length,chunks_embedded:j.length,embeddings_upserted:A,vector_entries_upserted:A,usage:N.usage}}finally{O.close()}}function SW(_){h(_);let $=v(_);try{let g=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,D=$.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at FROM vector_index_entries GROUP BY provider, model, dimensions - ORDER BY provider, model`).all();return{total_embeddings:J,total_vector_entries:U,indexes:W}}finally{_.close()}}async function t9($){let _=k1($.modelRef,$.config),J=w_(_),U=Math.max(1,Math.min($.limit??10,100)),W=await WV([$.query],$),X=W.vectors[0]??[];a($.dbPath);let G=m($.dbPath);try{let Q=G.query(`SELECT + ORDER BY provider, model`).all();return{total_embeddings:g,total_vector_entries:U,indexes:D}}finally{$.close()}}async function _I(_){let $=I4(_.modelRef,_.config),g=f_($),U=Math.max(1,Math.min(_.limit??10,100)),D=await zW([_.query],_),I=D.vectors[0]??[];h(_.dbPath);let j=v(_.dbPath);try{let O=j.query(`SELECT v.chunk_id, c.text, v.vector_json, @@ -756,7 +757,7 @@ VALUES (10, datetime('now')); v.metadata_json FROM vector_index_entries v JOIN chunks c ON c.id = v.chunk_id - WHERE v.provider = ? AND v.model = ? AND v.status = 'active'`).all(J.provider,J.model).map((q)=>{let L=JSON.parse(q.vector_json),N=xQ(q.metadata_json),R=N.provenance&&typeof N.provenance==="object"&&!Array.isArray(N.provenance)?N.provenance:null;return{chunk_id:q.chunk_id,score:ov(X,L,q.vector_norm),text:q.text,source_uri:q.source_uri,source_ref:q.source_ref,revision:q.revision,hash:q.hash,provenance:R}}).sort((q,L)=>L.score-q.score).slice(0,U);return{provider:J.provider,model:J.model,dimensions:W.dimensions,query:$.query,results:Q}}finally{G.close()}}function a9($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function G6($,_){for(let J of _){let U=$[J];if(typeof U==="string"&&U.length>0)return U}return null}function XV($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function QV($){return Array.from(new Set($))}function qV($){let _=$.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];return QV(_.filter((J)=>J.length>0)).slice(0,16)}function GV($){return $.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]}function Wy($){let _=[],J=/"([^"]*)"|(\S+)/g,U,W=!1;while((U=J.exec($))!==null){if(U[1]!==void 0){let q=GV(U[1]);if(q.length>0)_.push({type:"phrase",value:q.join(" "),negate:W,prefix:!1});W=!1;continue}let X=U[2]??"";if(X==="OR"||X==="||"||X==="|"){_.push({type:"or",value:"",negate:!1,prefix:!1});continue}if(X==="AND"||X==="&&")continue;if(X==="NOT"){W=!0;continue}let G=W;if(W=!1,X.startsWith("-")&&X.length>1)G=!0,X=X.slice(1);let Y=!1;if(X.endsWith("*"))Y=!0,X=X.slice(0,-1);let Q=GV(X);if(Q.length===0)continue;_.push({type:Q.length>1?"phrase":"term",value:Q.join(" "),negate:G,prefix:Y})}return _.slice(0,24)}function Uy($){if($.type==="phrase")return`"${$.value}"`;return`"${$.value}"*`}function Xy($){let _=Wy($);if(_.filter((G)=>G.type!=="or"&&!G.negate).length===0)return{and:null,or:null};let U=(G)=>{let Y="",Q=!1,q=[];for(let L of _){if(L.type==="or"){Q=!0;continue}let N=Uy(L);if(L.negate){q.push(N);continue}if(Y.length===0)Y=N;else Y=Q?`${Y} OR ${N}`:`${Y} ${G} ${N}`;Q=!1}for(let L of q)Y=`(${Y}) NOT ${L}`;return Y.length>0?Y:null},W=U("AND"),X=U("OR");return{and:W,or:X!==W?X:null}}function Gy($){return $.replace(/[\\%_]/g,(_)=>`\\${_}`)}function zV($,_){return $.flatMap((J)=>Array.from({length:_},()=>`%${Gy(J)}%`))}function Yy($,_){let J=Number.isFinite($)?1/(1+Math.abs($)):0,U=1/(1+_);return s9(Math.max(J,U))}function uQ($,_){if(_.length===0)return 0;let J=_.filter((U)=>$.includes(U)).length;if(J===0)return 0;return s9(Math.min(0.85,0.35+J/_.length*0.5))}function Qy($){return s9(Math.max(0,Math.min(1,($+1)/2)))}function s9($){return Number($.toFixed(6))}function ZJ($,_){let J=$.keyword??0,U=$.semantic??0,W=$.catalog??0,X=_?.chunk_id?0.05:0;return s9(Math.min(1,J*0.55+U*0.4+W*0.35+X))}function dQ($){let _=$.provenance;return _&&typeof _==="object"&&!Array.isArray(_)?_:null}function qy($){let _=a9($.chunk_metadata_json),J=dQ(_);if(J)return J;if(!$.source_revision_id&&!$.source_uri)return null;return E0({source_ref:G6(_,["source_ref"]),source_uri:$.source_uri??G6(_,["source_uri"]),source_kind:$.source_kind??G6(_,["source_kind"]),source_revision_id:$.source_revision_id,revision:$.revision??G6(_,["revision"]),hash:$.hash??G6(_,["hash"]),chunk_id:$.chunk_id,start_offset:$.start_offset??XV(_,["start_offset"]),end_offset:$.end_offset??XV(_,["end_offset"]),status:G6(_,["status"]),resolver:"open-files-read-only"})}function YV($,_,J){if(!_)return[];try{return zy($,_,J)}catch{return[]}}function zy($,_,J){return $.query(`SELECT + WHERE v.provider = ? AND v.model = ? AND v.status = 'active'`).all(g.provider,g.model).map((A)=>{let L=JSON.parse(A.vector_json),z=RE(A.metadata_json),W=z.provenance&&typeof z.provenance==="object"&&!Array.isArray(z.provenance)?z.provenance:null;return{chunk_id:A.chunk_id,score:y7(I,L,A.vector_norm),text:A.text,source_uri:A.source_uri,source_ref:A.source_ref,revision:A.revision,hash:A.hash,provenance:W}}).sort((A,L)=>L.score-A.score).slice(0,U);return{provider:g.provider,model:g.model,dimensions:D.dimensions,query:_.query,results:O}}finally{j.close()}}function $I(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function I$(_,$){for(let g of $){let U=_[g];if(typeof U==="string"&&U.length>0)return U}return null}function WW(_,$){for(let g of $){let U=_[g];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function GW(_){return Array.from(new Set(_))}function YW(_){let $=_.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];return GW($.filter((g)=>g.length>0)).slice(0,16)}function XW(_){return _.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]}function t7(_){let $=[],g=/"([^"]*)"|(\S+)/g,U,D=!1;while((U=g.exec(_))!==null){if(U[1]!==void 0){let A=XW(U[1]);if(A.length>0)$.push({type:"phrase",value:A.join(" "),negate:D,prefix:!1});D=!1;continue}let I=U[2]??"";if(I==="OR"||I==="||"||I==="|"){$.push({type:"or",value:"",negate:!1,prefix:!1});continue}if(I==="AND"||I==="&&")continue;if(I==="NOT"){D=!0;continue}let j=D;if(D=!1,I.startsWith("-")&&I.length>1)j=!0,I=I.slice(1);let N=!1;if(I.endsWith("*"))N=!0,I=I.slice(0,-1);let O=XW(I);if(O.length===0)continue;$.push({type:O.length>1?"phrase":"term",value:O.join(" "),negate:j,prefix:N})}return $.slice(0,24)}function o7(_){if(_.type==="phrase")return`"${_.value}"`;return`"${_.value}"*`}function p7(_){let $=t7(_);if($.filter((j)=>j.type!=="or"&&!j.negate).length===0)return{and:null,or:null};let U=(j)=>{let N="",O=!1,A=[];for(let L of $){if(L.type==="or"){O=!0;continue}let z=o7(L);if(L.negate){A.push(z);continue}if(N.length===0)N=z;else N=O?`${N} OR ${z}`:`${N} ${j} ${z}`;O=!1}for(let L of A)N=`(${N}) NOT ${L}`;return N.length>0?N:null},D=U("AND"),I=U("OR");return{and:D,or:I!==D?I:null}}function e7(_){return _.replace(/[\\%_]/g,($)=>`\\${$}`)}function QW(_,$){return _.flatMap((g)=>Array.from({length:$},()=>`%${e7(g)}%`))}function a7(_,$){let g=Number.isFinite(_)?1/(1+Math.abs(_)):0,U=1/(1+$);return gI(Math.max(g,U))}function GE(_,$){if($.length===0)return 0;let g=$.filter((U)=>_.includes(U)).length;if(g===0)return 0;return gI(Math.min(0.85,0.35+g/$.length*0.5))}function s7(_){return gI(Math.max(0,Math.min(1,(_+1)/2)))}function gI(_){return Number(_.toFixed(6))}function X0(_,$){let g=_.keyword??0,U=_.semantic??0,D=_.catalog??0,I=$?.chunk_id?0.05:0;return gI(Math.min(1,g*0.55+U*0.4+D*0.35+I))}function YE(_){let $=_.provenance;return $&&typeof $==="object"&&!Array.isArray($)?$:null}function _q(_){let $=$I(_.chunk_metadata_json),g=YE($);if(g)return g;if(!_.source_revision_id&&!_.source_uri)return null;return T6({source_ref:I$($,["source_ref"]),source_uri:_.source_uri??I$($,["source_uri"]),source_kind:_.source_kind??I$($,["source_kind"]),source_revision_id:_.source_revision_id,revision:_.revision??I$($,["revision"]),hash:_.hash??I$($,["hash"]),chunk_id:_.chunk_id,start_offset:_.start_offset??WW($,["start_offset"]),end_offset:_.end_offset??WW($,["end_offset"]),status:I$($,["status"]),resolver:"open-files-read-only"})}function RW(_,$,g){if(!$)return[];try{return $q(_,$,g)}catch{return[]}}function $q(_,$,g){return _.query(`SELECT chunks_fts.chunk_id, c.kind AS chunk_kind, c.wiki_page_id, @@ -785,49 +786,49 @@ VALUES (10, datetime('now')); LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id WHERE chunks_fts MATCH ? ORDER BY rank ASC - LIMIT ?`).all(_,J)}function jV($,_){if(_.length===0)return"1 = 0";return _.map(()=>`(${$.map((U)=>`lower(COALESCE(${U}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`).join(" OR ")}function jy($,_,J){let U=["path","title","artifact_uri","metadata_json"];return $.query(`SELECT id, path, title, artifact_uri, content_hash, status, metadata_json + LIMIT ?`).all($,g)}function TW(_,$){if($.length===0)return"1 = 0";return $.map(()=>`(${_.map((U)=>`lower(COALESCE(${U}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`).join(" OR ")}function gq(_,$,g){let U=["path","title","artifact_uri","metadata_json"];return _.query(`SELECT id, path, title, artifact_uri, content_hash, status, metadata_json FROM wiki_pages - WHERE status = 'active' AND (${jV(U,_)}) + WHERE status = 'active' AND (${TW(U,$)}) ORDER BY updated_at DESC - LIMIT ?`).all(...zV(_,U.length),J)}function Dy($,_,J){let U=["kind","name","shard_key","artifact_uri","metadata_json"];return $.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json + LIMIT ?`).all(...QW($,U.length),g)}function Dq(_,$,g){let U=["kind","name","shard_key","artifact_uri","metadata_json"];return _.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json FROM knowledge_indexes - WHERE ${jV(U,_)} + WHERE ${TW(U,$)} ORDER BY updated_at DESC - LIMIT ?`).all(...zV(_,U.length),J)}function DV($){if(!$||!_y($))return[];try{let _=JSON.parse(Jy($,"utf8"));if(!_||!Array.isArray(_.items))return[];return _.items.filter((J)=>{return Boolean(J&&typeof J==="object"&&typeof J.id==="string"&&typeof J.title==="string"&&typeof J.content==="string")})}catch{return[]}}function Oy($){return[$.id,$.short_id,$.title,$.content,$.url,...$.tags??[]].filter((_)=>typeof _==="string"&&_.length>0).join(" ").toLowerCase()}function OV($,_,J){if(_.length===0)return[];return $.filter((U)=>U.archived!==!0).map((U)=>({item:U,haystack:Oy(U)})).filter(({haystack:U})=>_.some((W)=>U.includes(W))).map(({item:U,haystack:W})=>({item:U,score:uQ(W,_)})).sort((U,W)=>W.score-U.score||U.item.id.localeCompare(W.item.id)).slice(0,J)}function Ly($,_,J){return OV(DV($),_,J)}function By($,_){let J=a9($.chunk_metadata_json),U=qy($),W=G6(J,["source_ref"]),X=$.source_uri??G6(J,["source_uri"]),G=Boolean($.wiki_page_id),Y={kind:G?"wiki_chunk":"source_chunk",id:$.chunk_id,title:G?$.wiki_title:$.source_title,text:$.text,score:0,scores:{keyword:_},source:X||W?{uri:X,ref:W,kind:$.source_kind??G6(J,["source_kind"]),revision:$.revision??G6(J,["revision"]),hash:$.hash??G6(J,["hash"])}:null,citation:{chunk_id:$.chunk_id,start_offset:$.start_offset,end_offset:$.end_offset},artifact:G?{uri:$.wiki_artifact_uri,path:$.wiki_path,hash:$.wiki_content_hash,shard_key:$.wiki_path}:null,provenance:U,reasons:["keyword_match"]};return Y.score=ZJ(Y.scores,Y.citation),Y}function LV($,_){let J=`knowledge://item/${encodeURIComponent($.id)}`,U={kind:"legacy_item",id:$.id,title:$.title,text:$.content,score:0,scores:{keyword:_},source:{uri:J,ref:J,kind:"legacy_item",revision:null,hash:null},citation:null,artifact:null,provenance:null,reasons:["legacy_note_match","keyword_match"]};return U.score=ZJ(U.scores,U.citation),U}function Hy($,_){let J=a9($.metadata_json),U=uQ(`${$.path} ${$.title} ${$.artifact_uri??""} ${$.metadata_json}`.toLowerCase(),_),W={kind:"wiki_page",id:$.id,title:$.title,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:$.artifact_uri,path:$.path,hash:$.content_hash,shard_key:$.path},provenance:dQ(J),reasons:["wiki_catalog_match"]};return W.score=ZJ(W.scores,W.citation),W}function Ny($,_){let J=a9($.metadata_json),U=uQ(`${$.kind} ${$.name} ${$.shard_key??""} ${$.artifact_uri??""} ${$.metadata_json}`.toLowerCase(),_),W={kind:"knowledge_index",id:$.id,title:$.name,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:$.artifact_uri,path:G6(J,["artifact_key"]),hash:G6(J,["content_hash"]),shard_key:$.shard_key},provenance:dQ(J),reasons:["index_catalog_match"]};return W.score=ZJ(W.scores,W.citation),W}function SJ($,_){let J=`${_.kind}:${_.id}`,U=$.get(J);if(!U){$.set(J,_);return}U.scores={keyword:Math.max(U.scores.keyword??0,_.scores.keyword??0)||void 0,semantic:Math.max(U.scores.semantic??0,_.scores.semantic??0)||void 0,catalog:Math.max(U.scores.catalog??0,_.scores.catalog??0)||void 0},U.reasons=QV([...U.reasons,..._.reasons]),U.text=U.text??_.text,U.title=U.title??_.title,U.source=U.source??_.source,U.citation=U.citation??_.citation,U.artifact=U.artifact??_.artifact,U.provenance=U.provenance??_.provenance,U.score=ZJ(U.scores,U.citation)}function BV($){let _={source_chunk:0,wiki_chunk:1,legacy_item:2,wiki_page:3,knowledge_index:4};return $.sort((J,U)=>{if(U.score!==J.score)return U.score-J.score;return _[J.kind]-_[U.kind]||J.id.localeCompare(U.id)})}async function e9($){let _=$.query.trim();if(!_)throw Error("Search query is required.");let J=Math.max(1,Math.min($.limit??10,100)),U=Math.max(0,Math.floor($.offset??0)),W=U+J,X=qV(_),G=Xy(_),Y=$.semantic===!0||$.fake===!0||Boolean($.modelRef),Q=[],q=null,L=null,N=null,R=0,B=0,H=0,V=new Map;a($.dbPath);let K=m($.dbPath);try{let w=Math.max(W*3,20),A=YV(K,G.and,w);if(A.length===0&&G.or)A=YV(K,G.or,w);R=A.length,A.forEach((u,W_)=>SJ(V,By(u,Yy(u.rank,W_))));let g=jy(K,X,Math.max(W,10)),v=Dy(K,X,Math.max(W,10)),k=Ly($.legacyStorePath,X,Math.max(W,10));B=g.length+v.length,R+=k.length,k.forEach(({item:u,score:W_})=>SJ(V,LV(u,W_))),g.forEach((u)=>SJ(V,Hy(u,X))),v.forEach((u)=>SJ(V,Ny(u,X)))}finally{K.close()}if(Y)try{let w=await t9({dbPath:$.dbPath,query:_,limit:Math.max(W*3,20),config:$.config,env:$.env,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake,batchSize:$.batchSize,maxParallelCalls:$.maxParallelCalls});q=w.provider,L=w.model,N=w.dimensions,H=w.results.length;for(let A of w.results){let g={kind:"source_chunk",id:A.chunk_id,title:null,text:A.text,score:0,scores:{semantic:Qy(A.score)},source:{uri:A.source_uri,ref:A.source_ref,kind:A.provenance?.source_kind??null,revision:A.revision,hash:A.hash},citation:{chunk_id:A.chunk_id,start_offset:A.provenance?.start_offset??null,end_offset:A.provenance?.end_offset??null},artifact:null,provenance:A.provenance,reasons:["semantic_match"]};g.score=ZJ(g.scores,g.citation),SJ(V,g)}}catch(w){Q.push(`semantic_search_failed: ${w instanceof Error?w.message:String(w)}`)}let F=BV(Array.from(V.values())).slice(U,U+J);return{query:_,limit:J,offset:U,mode:{keyword:!0,catalog:!0,semantic:Y},semantic_provider:q,semantic_model:L,semantic_dimensions:N,counts:{keyword_results:R,catalog_results:B,semantic_results:H,merged_results:F.length},warnings:Q,results:F}}async function $8($){return I1(DV($.legacyStorePath),$,["knowledge_db_missing"])}async function I1($,_,J=[]){let U=_.query.trim();if(!U)throw Error("Search query is required.");let W=Math.max(1,Math.min(_.limit??10,100)),X=Math.max(0,Math.floor(_.offset??0)),G=qV(U),Y=_.semantic===!0||_.fake===!0||Boolean(_.modelRef),Q=new Map,q=OV($,G,Math.max(X+W,10));q.forEach(({item:R,score:B})=>SJ(Q,LV(R,B)));let L=[...J];if(Y)L.push("semantic_search_requires_local_catalog");let N=BV(Array.from(Q.values())).slice(X,X+W);return{query:U,limit:W,offset:X,mode:{keyword:!0,catalog:!0,semantic:Y},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:q.length,catalog_results:0,semantic_results:0,merged_results:N.length},warnings:L,results:N}}function HV($,_){return`${$}_${Vy("sha256").update(_).digest("hex").slice(0,20)}`}function NV($){return $.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function Ry($){return Array.from(new Set(NV($).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,16)}function Ky($){return[$.title,$.text].filter(Boolean).join(" ").toLowerCase()}function Fy($,_){if(_.length===0)return 0;let J=Ky($),U=_.filter((W)=>J.includes(W)).length;return Number((U/_.length).toFixed(6))}function Ey($){if(!$)return!0;if("read_only"in $)return $.read_only===!0;if("read_only_sources"in $)return $.read_only_sources===!0;return!0}function VV($){if(!$)return!1;if("stale"in $&&$.stale)return!0;if("status"in $)return kQ($.status);return!1}function My($){if(VV($.provenance))return 0;if($.source?.hash||$.source?.revision)return 1;if($.artifact?.hash)return 0.85;if($.provenance&&"source_refs"in $.provenance&&$.provenance.source_refs.length>0)return 0.75;return 0.55}function Ay($){if($.citation?.chunk_id&&($.source?.uri||$.artifact?.uri))return 1;if($.provenance&&"citation_required"in $.provenance&&$.provenance.citation_required)return 0.75;if($.artifact?.uri)return 0.65;return 0.35}function by($){if($.kind==="wiki_chunk")return 0.85;if($.kind==="source_chunk")return 0.8;if($.kind==="legacy_item")return 0.6;if($.kind==="wiki_page")return 0.65;return 0.55}function wy($,_){let J={base_score:$.score,exact_score:Fy($,_),citation_score:Ay($),freshness_score:My($),authority_score:by($)},U=Math.min(1,J.base_score*0.65+J.exact_score*0.1+J.citation_score*0.1+J.freshness_score*0.1+J.authority_score*0.05),W=new Set($.reasons);if(J.exact_score>0.5)W.add("exact_term");if(J.citation_score>=0.75)W.add("cited_source");if(J.freshness_score>=0.85)W.add("fresh_source");return{...$,score:Number(U.toFixed(6)),reasons:Array.from(W),rerank:{...J,final_score:Number(U.toFixed(6))}}}function RV($,_){let J=$.text??$.title;if(!J)return null;let U=J.replace(/\s+/g," ").trim();return U.length<=_?U:`${U.slice(0,Math.max(0,_-1)).trim()}...`}function gy($){return{id:HV("cite",`${$.kind}\x00${$.id}\x00${$.source?.uri??""}\x00${$.artifact?.uri??""}`),result_id:$.id,kind:$.kind,source_uri:$.source?.uri??null,source_ref:$.source?.ref??null,artifact_uri:$.artifact?.uri??null,artifact_path:$.artifact?.path??null,revision:$.source?.revision??null,hash:$.source?.hash??$.artifact?.hash??null,chunk_id:$.citation?.chunk_id??null,start_offset:$.citation?.start_offset??null,end_offset:$.citation?.end_offset??null,quote:RV($,500),provenance:$.provenance}}function ky($,_,J){let U=RV($,J);if(!U)return null;return{id:HV("excerpt",`${$.kind}\x00${$.id}`),result_id:$.id,citation_id:_.id,kind:$.kind,text:U,score:$.score}}function _8($){return $.map(()=>"?").join(", ")}function Iy($,_){let J=_.map((Y)=>Y.citation?.chunk_id).filter((Y)=>Boolean(Y)),U=_.filter((Y)=>Y.kind==="wiki_page").map((Y)=>Y.id),W=[],X=[];if(J.length===0&&U.length===0)return{citations:W,backlinks:X};let G=m($);try{if(J.length>0)W.push(...G.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset + LIMIT ?`).all(...QW($,U.length),g)}function qW(_){if(!_||!i7(_))return[];try{let $=JSON.parse(l7(_,"utf8"));if(!$||!Array.isArray($.items))return[];return $.items.filter((g)=>{return Boolean(g&&typeof g==="object"&&typeof g.id==="string"&&typeof g.title==="string"&&typeof g.content==="string")})}catch{return[]}}function Uq(_){return[_.id,_.short_id,_.title,_.content,_.url,..._.tags??[]].filter(($)=>typeof $==="string"&&$.length>0).join(" ").toLowerCase()}function BW(_,$,g){if($.length===0)return[];return _.filter((U)=>U.archived!==!0).map((U)=>({item:U,haystack:Uq(U)})).filter(({haystack:U})=>$.some((D)=>U.includes(D))).map(({item:U,haystack:D})=>({item:U,score:GE(D,$)})).sort((U,D)=>D.score-U.score||U.item.id.localeCompare(D.item.id)).slice(0,g)}function Iq(_,$,g){return BW(qW(_),$,g)}function jq(_,$){let g=$I(_.chunk_metadata_json),U=_q(_),D=I$(g,["source_ref"]),I=_.source_uri??I$(g,["source_uri"]),j=Boolean(_.wiki_page_id),N={kind:j?"wiki_chunk":"source_chunk",id:_.chunk_id,title:j?_.wiki_title:_.source_title,text:_.text,score:0,scores:{keyword:$},source:I||D?{uri:I,ref:D,kind:_.source_kind??I$(g,["source_kind"]),revision:_.revision??I$(g,["revision"]),hash:_.hash??I$(g,["hash"])}:null,citation:{chunk_id:_.chunk_id,start_offset:_.start_offset,end_offset:_.end_offset},artifact:j?{uri:_.wiki_artifact_uri,path:_.wiki_path,hash:_.wiki_content_hash,shard_key:_.wiki_path}:null,provenance:U,reasons:["keyword_match"]};return N.score=X0(N.scores,N.citation),N}function KW(_,$){let g=`knowledge://item/${encodeURIComponent(_.id)}`,U={kind:"legacy_item",id:_.id,title:_.title,text:_.content,score:0,scores:{keyword:$},source:{uri:g,ref:g,kind:"legacy_item",revision:null,hash:null},citation:null,artifact:null,provenance:null,reasons:["legacy_note_match","keyword_match"]};return U.score=X0(U.scores,U.citation),U}function Nq(_,$){let g=$I(_.metadata_json),U=GE(`${_.path} ${_.title} ${_.artifact_uri??""} ${_.metadata_json}`.toLowerCase(),$),D={kind:"wiki_page",id:_.id,title:_.title,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:_.artifact_uri,path:_.path,hash:_.content_hash,shard_key:_.path},provenance:YE(g),reasons:["wiki_catalog_match"]};return D.score=X0(D.scores,D.citation),D}function Eq(_,$){let g=$I(_.metadata_json),U=GE(`${_.kind} ${_.name} ${_.shard_key??""} ${_.artifact_uri??""} ${_.metadata_json}`.toLowerCase(),$),D={kind:"knowledge_index",id:_.id,title:_.name,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:_.artifact_uri,path:I$(g,["artifact_key"]),hash:I$(g,["content_hash"]),shard_key:_.shard_key},provenance:YE(g),reasons:["index_catalog_match"]};return D.score=X0(D.scores,D.citation),D}function W0(_,$){let g=`${$.kind}:${$.id}`,U=_.get(g);if(!U){_.set(g,$);return}U.scores={keyword:Math.max(U.scores.keyword??0,$.scores.keyword??0)||void 0,semantic:Math.max(U.scores.semantic??0,$.scores.semantic??0)||void 0,catalog:Math.max(U.scores.catalog??0,$.scores.catalog??0)||void 0},U.reasons=GW([...U.reasons,...$.reasons]),U.text=U.text??$.text,U.title=U.title??$.title,U.source=U.source??$.source,U.citation=U.citation??$.citation,U.artifact=U.artifact??$.artifact,U.provenance=U.provenance??$.provenance,U.score=X0(U.scores,U.citation)}function VW(_){let $={source_chunk:0,wiki_chunk:1,legacy_item:2,wiki_page:3,knowledge_index:4};return _.sort((g,U)=>{if(U.score!==g.score)return U.score-g.score;return $[g.kind]-$[U.kind]||g.id.localeCompare(U.id)})}async function DI(_){let $=_.query.trim();if(!$)throw Error("Search query is required.");let g=Math.max(1,Math.min(_.limit??10,100)),U=Math.max(0,Math.floor(_.offset??0)),D=U+g,I=YW($),j=p7($),N=_.semantic===!0||_.fake===!0||Boolean(_.modelRef),O=[],A=null,L=null,z=null,W=0,J=0,P=0,S=new Map;h(_.dbPath);let X=v(_.dbPath);try{let K=Math.max(D*3,20),Q=RW(X,j.and,K);if(Q.length===0&&j.or)Q=RW(X,j.or,K);W=Q.length,Q.forEach((Z,a)=>W0(S,jq(Z,a7(Z.rank,a))));let T=gq(X,I,Math.max(D,10)),q=Dq(X,I,Math.max(D,10)),V=Iq(_.legacyStorePath,I,Math.max(D,10));J=T.length+q.length,W+=V.length,V.forEach(({item:Z,score:a})=>W0(S,KW(Z,a))),T.forEach((Z)=>W0(S,Nq(Z,I))),q.forEach((Z)=>W0(S,Eq(Z,I)))}finally{X.close()}if(N)try{let K=await _I({dbPath:_.dbPath,query:$,limit:Math.max(D*3,20),config:_.config,env:_.env,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake,batchSize:_.batchSize,maxParallelCalls:_.maxParallelCalls});A=K.provider,L=K.model,z=K.dimensions,P=K.results.length;for(let Q of K.results){let T={kind:"source_chunk",id:Q.chunk_id,title:null,text:Q.text,score:0,scores:{semantic:s7(Q.score)},source:{uri:Q.source_uri,ref:Q.source_ref,kind:Q.provenance?.source_kind??null,revision:Q.revision,hash:Q.hash},citation:{chunk_id:Q.chunk_id,start_offset:Q.provenance?.start_offset??null,end_offset:Q.provenance?.end_offset??null},artifact:null,provenance:Q.provenance,reasons:["semantic_match"]};T.score=X0(T.scores,T.citation),W0(S,T)}}catch(K){O.push(`semantic_search_failed: ${K instanceof Error?K.message:String(K)}`)}let R=VW(Array.from(S.values())).slice(U,U+g);return{query:$,limit:g,offset:U,mode:{keyword:!0,catalog:!0,semantic:N},semantic_provider:A,semantic_model:L,semantic_dimensions:z,counts:{keyword_results:W,catalog_results:J,semantic_results:P,merged_results:R.length},warnings:O,results:R}}async function UI(_){return j4(qW(_.legacyStorePath),_,["knowledge_db_missing"])}async function j4(_,$,g=[]){let U=$.query.trim();if(!U)throw Error("Search query is required.");let D=Math.max(1,Math.min($.limit??10,100)),I=Math.max(0,Math.floor($.offset??0)),j=YW(U),N=$.semantic===!0||$.fake===!0||Boolean($.modelRef),O=new Map,A=BW(_,j,Math.max(I+D,10));A.forEach(({item:W,score:J})=>W0(O,KW(W,J)));let L=[...g];if(N)L.push("semantic_search_requires_local_catalog");let z=VW(Array.from(O.values())).slice(I,I+D);return{query:U,limit:D,offset:I,mode:{keyword:!0,catalog:!0,semantic:N},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:A.length,catalog_results:0,semantic_results:0,merged_results:z.length},warnings:L,results:z}}function FW(_,$){return`${_}_${Oq("sha256").update($).digest("hex").slice(0,20)}`}function MW(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function Aq(_){return Array.from(new Set(MW(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,16)}function Lq(_){return[_.title,_.text].filter(Boolean).join(" ").toLowerCase()}function Jq(_,$){if($.length===0)return 0;let g=Lq(_),U=$.filter((D)=>g.includes(D)).length;return Number((U/$.length).toFixed(6))}function Pq(_){if(!_)return!0;if("read_only"in _)return _.read_only===!0;if("read_only_sources"in _)return _.read_only_sources===!0;return!0}function ZW(_){if(!_)return!1;if("stale"in _&&_.stale)return!0;if("status"in _)return jE(_.status);return!1}function zq(_){if(ZW(_.provenance))return 0;if(_.source?.hash||_.source?.revision)return 1;if(_.artifact?.hash)return 0.85;if(_.provenance&&"source_refs"in _.provenance&&_.provenance.source_refs.length>0)return 0.75;return 0.55}function Sq(_){if(_.citation?.chunk_id&&(_.source?.uri||_.artifact?.uri))return 1;if(_.provenance&&"citation_required"in _.provenance&&_.provenance.citation_required)return 0.75;if(_.artifact?.uri)return 0.65;return 0.35}function Wq(_){if(_.kind==="wiki_chunk")return 0.85;if(_.kind==="source_chunk")return 0.8;if(_.kind==="legacy_item")return 0.6;if(_.kind==="wiki_page")return 0.65;return 0.55}function Xq(_,$){let g={base_score:_.score,exact_score:Jq(_,$),citation_score:Sq(_),freshness_score:zq(_),authority_score:Wq(_)},U=Math.min(1,g.base_score*0.65+g.exact_score*0.1+g.citation_score*0.1+g.freshness_score*0.1+g.authority_score*0.05),D=new Set(_.reasons);if(g.exact_score>0.5)D.add("exact_term");if(g.citation_score>=0.75)D.add("cited_source");if(g.freshness_score>=0.85)D.add("fresh_source");return{..._,score:Number(U.toFixed(6)),reasons:Array.from(D),rerank:{...g,final_score:Number(U.toFixed(6))}}}function bW(_,$){let g=_.text??_.title;if(!g)return null;let U=g.replace(/\s+/g," ").trim();return U.length<=$?U:`${U.slice(0,Math.max(0,$-1)).trim()}...`}function Rq(_){return{id:FW("cite",`${_.kind}\x00${_.id}\x00${_.source?.uri??""}\x00${_.artifact?.uri??""}`),result_id:_.id,kind:_.kind,source_uri:_.source?.uri??null,source_ref:_.source?.ref??null,artifact_uri:_.artifact?.uri??null,artifact_path:_.artifact?.path??null,revision:_.source?.revision??null,hash:_.source?.hash??_.artifact?.hash??null,chunk_id:_.citation?.chunk_id??null,start_offset:_.citation?.start_offset??null,end_offset:_.citation?.end_offset??null,quote:bW(_,500),provenance:_.provenance}}function Gq(_,$,g){let U=bW(_,g);if(!U)return null;return{id:FW("excerpt",`${_.kind}\x00${_.id}`),result_id:_.id,citation_id:$.id,kind:_.kind,text:U,score:_.score}}function II(_){return _.map(()=>"?").join(", ")}function Yq(_,$){let g=$.map((N)=>N.citation?.chunk_id).filter((N)=>Boolean(N)),U=$.filter((N)=>N.kind==="wiki_page").map((N)=>N.id),D=[],I=[];if(g.length===0&&U.length===0)return{citations:D,backlinks:I};let j=v(_);try{if(g.length>0)D.push(...j.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset FROM citations - WHERE chunk_id IN (${_8(J)}) + WHERE chunk_id IN (${II(g)}) ORDER BY created_at DESC - LIMIT 50`).all(...J));if(U.length>0)W.push(...G.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset + LIMIT 50`).all(...g));if(U.length>0)D.push(...j.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset FROM citations - WHERE wiki_page_id IN (${_8(U)}) + WHERE wiki_page_id IN (${II(U)}) ORDER BY created_at DESC - LIMIT 50`).all(...U)),X.push(...G.query(`SELECT from_page_id, to_page_id, label + LIMIT 50`).all(...U)),I.push(...j.query(`SELECT from_page_id, to_page_id, label FROM wiki_backlinks - WHERE from_page_id IN (${_8(U)}) OR to_page_id IN (${_8(U)}) - LIMIT 50`).all(...U,...U))}finally{G.close()}return{citations:W,backlinks:X}}function vJ($,_={}){let J=Math.max(200,Math.min(_.contextChars??1200,4000)),U=Ry($.query),W=[...$.warnings],X=new Set,G=new Set,Q=$.results.filter((N)=>{if(!Ey(N.provenance))return W.push(`permission_filtered: ${N.kind}:${N.id}`),X.add("Dropped a result because provenance was not read-only."),!1;if(VV(N.provenance))return W.push(`stale_filtered: ${N.kind}:${N.id}`),G.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((N)=>wy(N,U)).sort((N,R)=>R.score-N.score||N.id.localeCompare(R.id)).slice(0,$.limit),q=Q.map(gy),L=Q.map((N,R)=>ky(N,q[R],J)).filter((N)=>Boolean(N));for(let N of Q){if(N.provenance&&"read_only"in N.provenance&&N.provenance.read_only)X.add("All source-backed excerpts are read-only and citation-required.");if(N.rerank.freshness_score>=0.85)G.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:$.query,normalized_query:NV($.query),created_at:new Date().toISOString(),mode:$.mode,warnings:W,search_counts:$.counts,results:Q,citations:q,excerpts:L,graph:_.dbPath?Iy(_.dbPath,Q):{citations:[],backlinks:[]},notes:{permissions:Array.from(X),freshness:Array.from(G)}}}async function yJ($){let _=await e9($);return vJ(_,{dbPath:$.dbPath,contextChars:$.contextChars})}async function J8($,_){let J=await I1($,_);return vJ(J,{contextChars:_.contextChars})}function hJ($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function cQ($){return`C${$+1}`}function FV($,_){if(_.excerpts.length===0)return`No indexed knowledge matched the prompt: ${$}`;return[`Found ${_.excerpts.length} relevant knowledge excerpt(s) for: ${$}`,"",..._.excerpts.slice(0,5).map((U,W)=>{let X=_.citations.find((Y)=>Y.id===U.citation_id),G=X?.source_ref??X?.source_uri??X?.artifact_path??X?.artifact_uri??"unknown source";return`[${cQ(W)}] ${U.text} (${G})`})].join(` -`)}function EV($,_){let J=_.citations.map((W,X)=>({id:cQ(X),source_ref:W.source_ref,source_uri:W.source_uri,artifact_path:W.artifact_path,revision:W.revision,hash:W.hash,quote:W.quote})),U=_.excerpts.map((W,X)=>({id:cQ(X),kind:W.kind,text:W.text,score:W.score}));return[`Prompt: ${$}`,"","Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.","",`Context excerpts: + WHERE from_page_id IN (${II(U)}) OR to_page_id IN (${II(U)}) + LIMIT 50`).all(...U,...U))}finally{j.close()}return{citations:D,backlinks:I}}function R0(_,$={}){let g=Math.max(200,Math.min($.contextChars??1200,4000)),U=Aq(_.query),D=[..._.warnings],I=new Set,j=new Set,O=_.results.filter((z)=>{if(!Pq(z.provenance))return D.push(`permission_filtered: ${z.kind}:${z.id}`),I.add("Dropped a result because provenance was not read-only."),!1;if(ZW(z.provenance))return D.push(`stale_filtered: ${z.kind}:${z.id}`),j.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((z)=>Xq(z,U)).sort((z,W)=>W.score-z.score||z.id.localeCompare(W.id)).slice(0,_.limit),A=O.map(Rq),L=O.map((z,W)=>Gq(z,A[W],g)).filter((z)=>Boolean(z));for(let z of O){if(z.provenance&&"read_only"in z.provenance&&z.provenance.read_only)I.add("All source-backed excerpts are read-only and citation-required.");if(z.rerank.freshness_score>=0.85)j.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:_.query,normalized_query:MW(_.query),created_at:new Date().toISOString(),mode:_.mode,warnings:D,search_counts:_.counts,results:O,citations:A,excerpts:L,graph:$.dbPath?Yq($.dbPath,O):{citations:[],backlinks:[]},notes:{permissions:Array.from(I),freshness:Array.from(j)}}}async function G0(_){let $=await DI(_);return R0($,{dbPath:_.dbPath,contextChars:_.contextChars})}async function jI(_,$){let g=await j4(_,$);return R0(g,{contextChars:$.contextChars})}function Y0(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function TE(_){return`C${_+1}`}function kW(_,$){if($.excerpts.length===0)return`No indexed knowledge matched the prompt: ${_}`;return[`Found ${$.excerpts.length} relevant knowledge excerpt(s) for: ${_}`,"",...$.excerpts.slice(0,5).map((U,D)=>{let I=$.citations.find((N)=>N.id===U.citation_id),j=I?.source_ref??I?.source_uri??I?.artifact_path??I?.artifact_uri??"unknown source";return`[${TE(D)}] ${U.text} (${j})`})].join(` +`)}function CW(_,$){let g=$.citations.map((D,I)=>({id:TE(I),source_ref:D.source_ref,source_uri:D.source_uri,artifact_path:D.artifact_path,revision:D.revision,hash:D.hash,quote:D.quote})),U=$.excerpts.map((D,I)=>({id:TE(I),kind:D.kind,text:D.text,score:D.score}));return[`Prompt: ${_}`,"","Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.","",`Context excerpts: ${JSON.stringify(U,null,2)}`,"",`Citations: -${JSON.stringify(J,null,2)}`].join(` -`)}function MV($,_){if(_.citations.length===0)return[];return[{kind:"answer_note",title:$.length>80?`${$.slice(0,77)}...`:$,citations:_.citations.map((J)=>J.id),requires_approval:!0}]}function fy($,_){let J=m($);try{J.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[_.runId,"knowledge-prompt",_.prompt,_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.now])}finally{J.close()}}function nQ($,_){let J=m($);try{J.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${iQ()}`,_.runId,_.level,_.event,JSON.stringify(_.metadata),_.now])}finally{J.close()}}function KV($,_){let J=m($);try{J.run(`UPDATE runs +${JSON.stringify(g,null,2)}`].join(` +`)}function rW(_,$){if($.citations.length===0)return[];return[{kind:"answer_note",title:_.length>80?`${_.slice(0,77)}...`:_,citations:$.citations.map((g)=>g.id),requires_approval:!0}]}function Qq(_,$){let g=v(_);try{g.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.runId,"knowledge-prompt",$.prompt,$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.now])}finally{g.close()}}function QE(_,$){let g=v(_);try{g.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${qE()}`,$.runId,$.level,$.event,JSON.stringify($.metadata),$.now])}finally{g.close()}}function HW(_,$){let g=v(_);try{g.run(`UPDATE runs SET status = ?, provider = ?, model = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`,[_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.runId])}finally{J.close()}}function Cy($,_,J,U,W,X,G={}){let Y=m($);try{TJ(Y,{run_id:_,provider:U,model:W,input_tokens:J.input_tokens,output_tokens:J.output_tokens,cost_usd:J.cost_usd,metadata:G,created_at:X})}finally{Y.close()}}async function AV($){let _=$.prompt.trim();if(!_)throw Error("Knowledge prompt is required.");let J=($.now??new Date).toISOString(),U=`run_${iQ()}`,W=y6($.modelRef??"default",$.config),X=w_(W);a($.dbPath),fy($.dbPath,{runId:U,prompt:_,status:$.generate?"running":"dry_run",provider:$.generate?X.provider:"local",model:$.generate?X.model:"context-draft",metadata:{semantic:$.semantic===!0||$.fake===!0||Boolean($.modelRef),approve_write:$.approveWrite===!0,generated:$.generate===!0},now:J});let{prompt:G,generate:Y,approveWrite:Q,now:q,...L}=$,N=await yJ({...L,query:_});nQ($.dbPath,{runId:U,level:"info",event:"context_retrieved",metadata:{results:N.results.length,citations:N.citations.length,warnings:N.warnings},now:J});let R=FV(_,N),B=!1,H="local",V="context-draft",K={input_tokens:hJ(_)+N.excerpts.reduce((A,g)=>A+hJ(g.text),0),output_tokens:hJ(R),cost_usd:0},E=[...N.warnings];if($.generate)try{if($.fake)B=!0,H=X.provider,V=X.model,R=`Fake generated answer for: ${_} + WHERE id = ?`,[$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.runId])}finally{g.close()}}function Tq(_,$,g,U,D,I,j={}){let N=v(_);try{S0(N,{run_id:$,provider:U,model:D,input_tokens:g.input_tokens,output_tokens:g.output_tokens,cost_usd:g.cost_usd,metadata:j,created_at:I})}finally{N.close()}}async function vW(_){let $=_.prompt.trim();if(!$)throw Error("Knowledge prompt is required.");let g=(_.now??new Date).toISOString(),U=`run_${qE()}`,D=G$(_.modelRef??"default",_.config),I=f_(D);h(_.dbPath),Qq(_.dbPath,{runId:U,prompt:$,status:_.generate?"running":"dry_run",provider:_.generate?I.provider:"local",model:_.generate?I.model:"context-draft",metadata:{semantic:_.semantic===!0||_.fake===!0||Boolean(_.modelRef),approve_write:_.approveWrite===!0,generated:_.generate===!0},now:g});let{prompt:j,generate:N,approveWrite:O,now:A,...L}=_,z=await G0({...L,query:$});QE(_.dbPath,{runId:U,level:"info",event:"context_retrieved",metadata:{results:z.results.length,citations:z.citations.length,warnings:z.warnings},now:g});let W=kW($,z),J=!1,P="local",S="context-draft",X={input_tokens:Y0($)+z.excerpts.reduce((Q,T)=>Q+Y0(T.text),0),output_tokens:Y0(W),cost_usd:0},G=[...z.warnings];if(_.generate)try{if(_.fake)J=!0,P=I.provider,S=I.model,W=`Fake generated answer for: ${$} -${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:$.config,env:$.env}),v=await A({model:g,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:EV(_,N)});B=!0,H=X.provider,V=X.model,R=v.text;let k=g1({provider:H,model:V,usage:v.usage,providerMetadata:v.providerMetadata});K={input_tokens:k.input_tokens,output_tokens:k.output_tokens,cost_usd:k.cost_usd}}}catch(A){throw nQ($.dbPath,{runId:U,level:"error",event:"answer_generation_failed",metadata:{message:A instanceof Error?A.message:String(A)},now:J}),KV($.dbPath,{runId:U,status:"failed",provider:X.provider,model:X.model,metadata:{generated:!1,error:A instanceof Error?A.message:String(A)},now:J}),A}let F=MV(_,N),w={approved:$.approveWrite===!0,durable_writes_performed:!1,reason:$.approveWrite?"Approval flag recorded; durable wiki writing is deferred to the wiki compile task.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return nQ($.dbPath,{runId:U,level:"info",event:B?"answer_generated":"answer_drafted",metadata:{provider:H,model:V,proposed_updates:F.length,durable_writes_performed:!1},now:J}),Cy($.dbPath,U,K,H,V,J,{generated:B,citations:N.citations.length}),KV($.dbPath,{runId:U,status:B?"completed":"dry_run",provider:H,model:V,metadata:{generated:B,citations:N.citations.length,proposed_updates:F.length,approve_write:$.approveWrite===!0},now:J}),{run_id:U,prompt:_,generated:B,provider:H,model:V,answer:R,context:N,citations:N.citations,proposed_wiki_updates:F,write_policy:w,usage:K,warnings:E}}async function bV($,_){let J=_.prompt.trim();if(!J)throw Error("Knowledge prompt is required.");let U=`run_${iQ()}`,W=y6(_.modelRef??"default",_.config),X=w_(W),{prompt:G,generate:Y,approveWrite:Q,now:q,...L}=_,N=await J8($,{...L,query:J}),R=FV(J,N),B=!1,H="local",V="context-draft",K={input_tokens:hJ(J)+N.excerpts.reduce((A,g)=>A+hJ(g.text),0),output_tokens:hJ(R),cost_usd:0},E=[...N.warnings];if(_.generate)if(_.fake)B=!0,H=X.provider,V=X.model,R=`Fake generated answer for: ${J} +${W}`;else{let{generateText:Q}=await import("ai"),T=await ug(D,{config:_.config,env:_.env}),q=await Q({model:T,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:CW($,z)});J=!0,P=I.provider,S=I.model,W=q.text;let V=U4({provider:P,model:S,usage:q.usage,providerMetadata:q.providerMetadata});X={input_tokens:V.input_tokens,output_tokens:V.output_tokens,cost_usd:V.cost_usd}}}catch(Q){throw QE(_.dbPath,{runId:U,level:"error",event:"answer_generation_failed",metadata:{message:Q instanceof Error?Q.message:String(Q)},now:g}),HW(_.dbPath,{runId:U,status:"failed",provider:I.provider,model:I.model,metadata:{generated:!1,error:Q instanceof Error?Q.message:String(Q)},now:g}),Q}let R=rW($,z),K={approved:_.approveWrite===!0,durable_writes_performed:!1,reason:_.approveWrite?"Approval flag recorded; durable wiki writing is deferred to the wiki compile task.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return QE(_.dbPath,{runId:U,level:"info",event:J?"answer_generated":"answer_drafted",metadata:{provider:P,model:S,proposed_updates:R.length,durable_writes_performed:!1},now:g}),Tq(_.dbPath,U,X,P,S,g,{generated:J,citations:z.citations.length}),HW(_.dbPath,{runId:U,status:J?"completed":"dry_run",provider:P,model:S,metadata:{generated:J,citations:z.citations.length,proposed_updates:R.length,approve_write:_.approveWrite===!0},now:g}),{run_id:U,prompt:$,generated:J,provider:P,model:S,answer:W,context:z,citations:z.citations,proposed_wiki_updates:R,write_policy:K,usage:X,warnings:G}}async function fW(_,$){let g=$.prompt.trim();if(!g)throw Error("Knowledge prompt is required.");let U=`run_${qE()}`,D=G$($.modelRef??"default",$.config),I=f_(D),{prompt:j,generate:N,approveWrite:O,now:A,...L}=$,z=await jI(_,{...L,query:g}),W=kW(g,z),J=!1,P="local",S="context-draft",X={input_tokens:Y0(g)+z.excerpts.reduce((Q,T)=>Q+Y0(T.text),0),output_tokens:Y0(W),cost_usd:0},G=[...z.warnings];if($.generate)if($.fake)J=!0,P=I.provider,S=I.model,W=`Fake generated answer for: ${g} -${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config,env:_.env}),v=await A({model:g,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:EV(J,N)});B=!0,H=X.provider,V=X.model,R=v.text;let k=g1({provider:H,model:V,usage:v.usage,providerMetadata:v.providerMetadata});K={input_tokens:k.input_tokens,output_tokens:k.output_tokens,cost_usd:k.cost_usd}}let F=MV(J,N),w={approved:_.approveWrite===!0,durable_writes_performed:!1,reason:_.approveWrite?"Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return{run_id:U,prompt:J,generated:B,provider:H,model:V,answer:R,context:N,citations:N.citations,proposed_wiki_updates:F,write_policy:w,usage:K,warnings:E}}import{createHash as Py}from"crypto";var Ty=1200,Sy=6,Zy=12000,vy=50,wV=800;function xJ($,_,J=16){return`${$}_${Py("sha256").update(_).digest("hex").slice(0,J)}`}function rQ($){return $.normalize("NFKC").trim().replace(/\s+/g," ")}function pQ($){return rQ($).toLowerCase()}function yy($){return Array.from(new Set(pQ($).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function c4($,_){let J=rQ($);if(J.length<=_)return J;let U="...";if(_<=U.length)return J.slice(0,Math.max(0,_));return`${J.slice(0,_-U.length).trim()}${U}`}function gV($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function oQ($){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test($)}function lQ($){return Object.keys($).filter((_)=>!oQ(_)).sort().slice(0,12)}function hy($,_){for(let J of _){if(oQ(J))continue;let U=$[J];if(typeof U==="string"&&U.trim())return U.trim()}return null}function MU($,_){if(!$)return null;let J=k_($,_).text;try{let U=new URL(J),W=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let X of W)U.searchParams.delete(X);for(let[X]of U.searchParams)if(oQ(X))U.searchParams.delete(X);return U.toString()}catch{return J}}function j4($,_,J){return MU(hy($,_),J)}function W8($){let _=[];for(let J of lQ($).slice(0,6)){let U=$[J];if(typeof U==="string"&&U.trim())_.push(`${J}=${c4(U,80)}`);else if(typeof U==="number"||typeof U==="boolean")_.push(`${J}=${String(U)}`);else if(U&&typeof U==="object")_.push(`${J}={...}`)}return _.join("; ")}function my($){if(!$.trim())return 0;return Math.max(1,Math.ceil($.length/4))}function kV($){return my(JSON.stringify($))}function xy($){if(!Number.isFinite($??NaN))return Ty;let _=Math.floor($);if(_J.includes(W)).length;return Number((U/_.length).toFixed(6))}function dy($){return["This pack is read-only and performs no durable writes.","Use citation ids and refs instead of pasting raw artifacts into prompts.","Resolve source or artifact refs explicitly only when raw content is needed and allowed.","Run generated knowledge writes through approval-gated commands before applying.",$==="loops"||$==="runs"?"Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded.":"Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata."]}function ny($,_,J){let U=MU(_.source_ref,J),W=MU(_.source_uri,J),X=MU(_.artifact_uri,J),G=MU(_.artifact_path,J),Y=U??W??G??X??_.id,Q=_.quote?mJ(_.quote,J,$<3?220:140):null;return{citation:{id:xJ("cite",`${_.id}\x00${Y}`,12),kind:_.artifact_uri||_.artifact_path?"artifact":"source",ref:Y,source_ref:U,source_uri:W,artifact_uri:X,artifact_path:G,run_id:null,run_event_id:null,revision:_.revision??null,hash:_.hash??null,chunk_id:_.chunk_id??null,offsets:{start:_.start_offset??null,end:_.end_offset??null},quote_preview:Q?.text??null},redactions:Q?.redactions??0}}async function cy($,_){let J=($.query??$.topic??"").trim();if(!J)throw Error("Context pack query is required for search source.");let{config:U,dbPath:W,limit:X,semantic:G,modelRef:Y,dimensions:Q,fake:q,env:L,batchSize:N,maxParallelCalls:R,legacyStorePath:B}=$,H=await yJ({dbPath:W,config:U,legacyStorePath:B,query:J,limit:Math.max(_,X??_),semantic:G,modelRef:Y,dimensions:Q,fake:q,env:L,batchSize:N,maxParallelCalls:R,contextChars:Math.min($.contextChars??700,1200)}),V=new Map,K=0;H.citations.forEach((A,g)=>{let v=ny(g,A,$.safetyPolicy);K+=v.redactions,V.set(A.id,v.citation)});let E=H.excerpts.slice(0,Math.max(_*2,_)).map((A)=>{let g=H.results.find((W_)=>W_.id===A.result_id),v=A.citation_id?V.get(A.citation_id):null,k=mJ(A.text,$.safetyPolicy,520);K+=k.redactions;let u=g?.title??v?.ref??A.kind;return{id:xJ("ev",`${A.kind}\x00${A.result_id}\x00${A.citation_id??""}`,14),kind:A.kind,title:c4(u,100),text_preview:k.text,score:Number(A.score.toFixed(6)),citation_ids:v?[v.id]:[],provenance:{source:"search",record_ref:`${A.kind}:${A.result_id}`,created_at:H.created_at,updated_at:null,metadata_keys:[]}}}),F=new Set(E.flatMap((A)=>A.citation_ids));return{citations:Array.from(V.values()).filter((A)=>F.has(A.id)),evidence:E,duplicateCandidates:[],redactions:K,warnings:H.warnings,available:H.excerpts.length}}function iy($,_,J){if(_)return $.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at +${W}`;else{let{generateText:Q}=await import("ai"),T=await ug(D,{config:$.config,env:$.env}),q=await Q({model:T,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:CW(g,z)});J=!0,P=I.provider,S=I.model,W=q.text;let V=U4({provider:P,model:S,usage:q.usage,providerMetadata:q.providerMetadata});X={input_tokens:V.input_tokens,output_tokens:V.output_tokens,cost_usd:V.cost_usd}}let R=rW(g,z),K={approved:$.approveWrite===!0,durable_writes_performed:!1,reason:$.approveWrite?"Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return{run_id:U,prompt:g,generated:J,provider:P,model:S,answer:W,context:z,citations:z.citations,proposed_wiki_updates:R,write_policy:K,usage:X,warnings:G}}import{createHash as qq}from"crypto";var Bq=1200,Kq=6,Vq=12000,Fq=50,wW=800;function T0(_,$,g=16){return`${_}_${qq("sha256").update($).digest("hex").slice(0,g)}`}function KE(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function VE(_){return KE(_).toLowerCase()}function Mq(_){return Array.from(new Set(VE(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function g6(_,$){let g=KE(_);if(g.length<=$)return g;let U="...";if($<=U.length)return g.slice(0,Math.max(0,$));return`${g.slice(0,$-U.length).trim()}${U}`}function uW(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function FE(_){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test(_)}function BE(_){return Object.keys(_).filter(($)=>!FE($)).sort().slice(0,12)}function Zq(_,$){for(let g of $){if(FE(g))continue;let U=_[g];if(typeof U==="string"&&U.trim())return U.trim()}return null}function xg(_,$){if(!_)return null;let g=u_(_,$).text;try{let U=new URL(g),D=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let I of D)U.searchParams.delete(I);for(let[I]of U.searchParams)if(FE(I))U.searchParams.delete(I);return U.toString()}catch{return g}}function w$(_,$,g){return xg(Zq(_,$),g)}function NI(_){let $=[];for(let g of BE(_).slice(0,6)){let U=_[g];if(typeof U==="string"&&U.trim())$.push(`${g}=${g6(U,80)}`);else if(typeof U==="number"||typeof U==="boolean")$.push(`${g}=${String(U)}`);else if(U&&typeof U==="object")$.push(`${g}={...}`)}return $.join("; ")}function bq(_){if(!_.trim())return 0;return Math.max(1,Math.ceil(_.length/4))}function xW(_){return bq(JSON.stringify(_))}function Hq(_){if(!Number.isFinite(_??NaN))return Bq;let $=Math.floor(_);if($g.includes(D)).length;return Number((U/$.length).toFixed(6))}function Cq(_){return["This pack is read-only and performs no durable writes.","Use citation ids and refs instead of pasting raw artifacts into prompts.","Resolve source or artifact refs explicitly only when raw content is needed and allowed.","Run generated knowledge writes through approval-gated commands before applying.",_==="loops"||_==="runs"?"Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded.":"Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata."]}function rq(_,$,g){let U=xg($.source_ref,g),D=xg($.source_uri,g),I=xg($.artifact_uri,g),j=xg($.artifact_path,g),N=U??D??j??I??$.id,O=$.quote?Q0($.quote,g,_<3?220:140):null;return{citation:{id:T0("cite",`${$.id}\x00${N}`,12),kind:$.artifact_uri||$.artifact_path?"artifact":"source",ref:N,source_ref:U,source_uri:D,artifact_uri:I,artifact_path:j,run_id:null,run_event_id:null,revision:$.revision??null,hash:$.hash??null,chunk_id:$.chunk_id??null,offsets:{start:$.start_offset??null,end:$.end_offset??null},quote_preview:O?.text??null},redactions:O?.redactions??0}}async function vq(_,$){let g=(_.query??_.topic??"").trim();if(!g)throw Error("Context pack query is required for search source.");let{config:U,dbPath:D,limit:I,semantic:j,modelRef:N,dimensions:O,fake:A,env:L,batchSize:z,maxParallelCalls:W,legacyStorePath:J}=_,P=await G0({dbPath:D,config:U,legacyStorePath:J,query:g,limit:Math.max($,I??$),semantic:j,modelRef:N,dimensions:O,fake:A,env:L,batchSize:z,maxParallelCalls:W,contextChars:Math.min(_.contextChars??700,1200)}),S=new Map,X=0;P.citations.forEach((Q,T)=>{let q=rq(T,Q,_.safetyPolicy);X+=q.redactions,S.set(Q.id,q.citation)});let G=P.excerpts.slice(0,Math.max($*2,$)).map((Q)=>{let T=P.results.find((a)=>a.id===Q.result_id),q=Q.citation_id?S.get(Q.citation_id):null,V=Q0(Q.text,_.safetyPolicy,520);X+=V.redactions;let Z=T?.title??q?.ref??Q.kind;return{id:T0("ev",`${Q.kind}\x00${Q.result_id}\x00${Q.citation_id??""}`,14),kind:Q.kind,title:g6(Z,100),text_preview:V.text,score:Number(Q.score.toFixed(6)),citation_ids:q?[q.id]:[],provenance:{source:"search",record_ref:`${Q.kind}:${Q.result_id}`,created_at:P.created_at,updated_at:null,metadata_keys:[]}}}),R=new Set(G.flatMap((Q)=>Q.citation_ids));return{citations:Array.from(S.values()).filter((Q)=>R.has(Q.id)),evidence:G,duplicateCandidates:[],redactions:X,warnings:P.warnings,available:P.excerpts.length}}function fq(_,$,g){if($)return _.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at FROM runs WHERE updated_at >= ? OR created_at >= ? ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(_,_,J);return $.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at + LIMIT ?`).all($,$,g);return _.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at FROM runs ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(J)}function ly($,_,J){if(_.length===0)return[];let U=_.map(()=>"?").join(", ");return $.query(`SELECT id, run_id, level, event, metadata_json, created_at + LIMIT ?`).all(g)}function wq(_,$,g){if($.length===0)return[];let U=$.map(()=>"?").join(", ");return _.query(`SELECT id, run_id, level, event, metadata_json, created_at FROM run_events WHERE run_id IN (${U}) ORDER BY created_at DESC - LIMIT ?`).all(..._,J)}function ry($,_){return`${$.type} ${$.metadata_json} ${_.map((U)=>`${U.event} ${U.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function py($,_,J){let U=j4(_,["source_ref","source_uri","evidence_uri","receipt_uri"],J),W=j4(_,["artifact_uri"],J),X=j4(_,["artifact_path","artifact_key"],J),G=U??W??X??`knowledge://project/runs/${$.id}`,Y=$.prompt?mJ($.prompt,J,180).text:null;return{id:xJ("cite",`run\x00${$.id}\x00${G}`,12),kind:W||X?"artifact":"run",ref:G,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:W,artifact_path:X,run_id:$.id,run_event_id:null,revision:j4(_,["revision"],J),hash:j4(_,["hash","content_hash"],J),chunk_id:null,offsets:{start:null,end:null},quote_preview:Y}}function oy($,_,J){let U=j4(_,["source_ref","source_uri","evidence_uri","receipt_uri"],J),W=j4(_,["artifact_uri"],J),X=j4(_,["artifact_path","artifact_key"],J),G=U??W??X??`knowledge://project/runs/${$.run_id}`,Y=mJ($.event,J,160).text;return{id:xJ("cite",`event\x00${$.id}\x00${G}`,12),kind:W||X?"artifact":"run_event",ref:G,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:W,artifact_path:X,run_id:$.run_id,run_event_id:$.id,revision:j4(_,["revision"],J),hash:j4(_,["hash","content_hash"],J),chunk_id:null,offsets:{start:null,end:null},quote_preview:Y}}function PV($){let _=new Map;for(let J of $){let U=pQ(`${J.title} ${J.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g,"").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g,"").replace(/[^a-z0-9 ]+/g,"").replace(/\b(?:run|event|completed|dry_run|pending)\b/g,"").replace(/\s+/g," ").trim().slice(0,220);if(!U)continue;_.set(U,[..._.get(U)??[],J.id])}return Array.from(_.entries()).filter(([,J])=>J.length>1).map(([J,U])=>({id:xJ("dup",J,12),reason:"normalized_text_match",evidence_ids:U,confidence:U.length>2?"high":"medium"}))}async function ty($,_,J){let U=$.source==="loops"?"loops":"runs",W=($.topic??$.query??"").trim(),X=yy(W),G=CV($.since,J),Y=G.warning?[G.warning]:[];a($.dbPath);let Q=m($.dbPath);try{let q=iy(Q,G.cutoff,Math.max(_*8,40)),L=ly(Q,q.map((E)=>E.id),Math.max(_*12,80)),N=new Map;for(let E of L)N.set(E.run_id,[...N.get(E.run_id)??[],E]);let B=(U==="loops"?q.filter((E)=>ry(E,N.get(E.id)??[])):q).map((E)=>{let F=gV(E.metadata_json),w=`${E.type} ${E.status} ${E.prompt??""} ${W8(F)} ${(N.get(E.id)??[]).map((A)=>`${A.event} ${A.metadata_json}`).join(" ")}`;return{row:E,metadata:F,score:IV(w,X),text:w}}).filter((E)=>X.length===0||E.score>0).sort((E,F)=>F.score-E.score||F.row.updated_at.localeCompare(E.row.updated_at)||E.row.id.localeCompare(F.row.id)),H=[],V=[],K=0;for(let E of B.slice(0,Math.max(_*2,_))){let F=py(E.row,E.metadata,$.safetyPolicy);H.push(F);let w=W8(E.metadata),A=[E.row.prompt,w].filter(Boolean).join(" | ")||`${E.row.type} ${E.row.status}`,g=mJ(A,$.safetyPolicy,420);K+=g.redactions,V.push({id:`run:${E.row.id}`,kind:E.row.type,title:c4(`${E.row.type}: ${E.row.status}`,100),text_preview:g.text,score:E.score,citation_ids:[F.id],provenance:{source:U,record_ref:`knowledge://project/runs/${E.row.id}`,created_at:E.row.created_at,updated_at:E.row.updated_at,metadata_keys:lQ(E.metadata)}});let v=(N.get(E.row.id)??[]).map((k)=>{let u=gV(k.metadata_json),W_=`${k.event} ${W8(u)} ${k.metadata_json}`;return{event:k,metadata:u,score:IV(W_,X),text:W_}}).filter((k)=>X.length===0||k.score>0).sort((k,u)=>u.score-k.score||u.event.created_at.localeCompare(k.event.created_at)||k.event.id.localeCompare(u.event.id)).slice(0,2);for(let k of v){let u=oy(k.event,k.metadata,$.safetyPolicy);H.push(u);let W_=mJ(`${k.event}: ${W8(k.metadata)}`,$.safetyPolicy,320);K+=W_.redactions,V.push({id:`event:${k.event.id}`,kind:`run_event:${k.event.level}`,title:c4(k.event.event,100),text_preview:W_.text,score:k.score,citation_ids:[u.id],provenance:{source:U,record_ref:`knowledge://project/runs/${k.event.run_id}`,created_at:k.event.created_at,updated_at:null,metadata_keys:lQ(k.metadata)}})}}return{citations:H,evidence:V,duplicateCandidates:$.dedupe?PV(V):[],redactions:K,warnings:Y,available:B.length}}finally{Q.close()}}function ay($){let _=$.purpose==="proposal"?`Proposal context: ${c4($.query||"loop evidence",80)}`:`Knowledge context: ${c4($.query,80)}`,J=$.evidence.slice(0,8).map((X)=>X.id),U=$.duplicates.slice(0,5).map((X)=>X.id),W=$.evidence.slice(0,5).map((X)=>`${X.id}: ${X.title}`);if($.evidence.length===0)W.push("No matching bounded evidence was found.");return{title:_,bullets:W,evidence_ids:J,duplicate_candidate_ids:U,next_actions:$.source==="loops"?["Review duplicate_candidates before drafting a new proposal.","Use cited run refs for provenance; inspect a run only when more detail is needed.","Keep proposal writes approval-gated and idempotent."]:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]}}function TV($){let _=new Set($.evidence.flatMap((J)=>J.citation_ids));$.citations=$.citations.filter((J)=>_.has(J.id))}function fV($){$.outline.evidence_ids=$.evidence.slice(0,8).map((_)=>_.id),$.outline.bullets=$.evidence.length>0?$.evidence.slice(0,5).map((_)=>`${_.id}: ${_.title}`):["No matching bounded evidence was found."],$.outline.duplicate_candidate_ids=$.duplicate_candidates.slice(0,5).map((_)=>_.id)}function sy($){let _=$.budgets.max_tokens,J=new Set($.warnings);while(kV($)>_){let U=$.evidence.map((X,G)=>({entry:X,index:G})).filter(({entry:X})=>X.text_preview.length>180).sort((X,G)=>G.entry.text_preview.length-X.entry.text_preview.length)[0];if(U){U.entry.text_preview=c4(U.entry.text_preview,180),J.add("text_preview_truncated_for_token_budget");continue}let W=$.citations.filter((X)=>(X.quote_preview?.length??0)>120).sort((X,G)=>(G.quote_preview?.length??0)-(X.quote_preview?.length??0))[0];if(W?.quote_preview){W.quote_preview=c4(W.quote_preview,120),J.add("citation_quote_truncated_for_token_budget");continue}if($.evidence.length>0){$.evidence.pop(),$.budgets.items_truncated+=1,$.duplicate_candidates=$.duplicate_candidates.map((X)=>({...X,evidence_ids:X.evidence_ids.filter((G)=>$.evidence.some((Y)=>Y.id===G))})).filter((X)=>X.evidence_ids.length>1),fV($),J.add("evidence_truncated_for_token_budget"),TV($);continue}if($.outline.next_actions.length>1){$.outline.next_actions.pop(),J.add("outline_truncated_for_token_budget");continue}J.add("token_budget_floor_exceeded");break}if($.warnings=Array.from(J).sort(),$.budgets.items_included=$.evidence.length,fV($),$.budgets.estimated_tokens=kV($),$.budgets.token_budget_exceeded=$.budgets.estimated_tokens>_,$.budgets.token_budget_exceeded)throw Error(`Unable to build context pack within ${_} token budget; increase --max-tokens.`);return $.message=`${$.evidence.length} bounded evidence item(s), estimated ${$.budgets.estimated_tokens}/${_} token(s)`,$}async function SV($){let _=$.now??new Date,J=$.source??"search",U=$.purpose??(J==="loops"||J==="runs"?"proposal":"agent_context"),W=xy($.maxTokens),X=uy($.maxItems,$.limit),G=rQ($.query??$.topic??"");if(U==="proposal"&&J!=="search"&&!G)throw Error("Proposal context requires --topic or a positional topic.");if(J!=="search")a($.dbPath);let Y=CV($.since,_).cutoff??$.since??"",Q=J==="search"?await cy($,X):await ty($,X,_),q=Q.evidence.sort((H,V)=>V.score-H.score||H.id.localeCompare(V.id)).slice(0,X),L=Q.citations.filter((H,V,K)=>K.findIndex((E)=>E.id===H.id)===V).sort((H,V)=>H.id.localeCompare(V.id)),N=$.dedupe?PV(q):Q.duplicateCandidates.filter((H)=>H.evidence_ids.every((V)=>q.some((K)=>K.id===V))),R=ay({source:J,purpose:U,query:G,evidence:q,duplicates:N}),B={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:_.toISOString(),source:J,purpose:U,query:G,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:xJ("ctx",[J,U,G,Y,$.dedupe===!0?"dedupe":"no-dedupe",$.semantic===!0?"semantic":"keyword",$.modelRef??"",$.limit??"",W,X,q.map((H)=>H.id).join(","),L.map((H)=>H.id).join(",")].join("\x00"),20),budgets:{max_tokens:W,estimated_tokens:0,max_items:X,items_included:q.length,items_available:Q.available,items_truncated:Math.max(0,Q.available-q.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:Q.redactions,reminders:dy(J)},citations:L,evidence:q,duplicate_candidates:N,outline:R,warnings:Q.warnings,message:`${q.length} bounded evidence item(s), estimated under ${W} token(s)`};return TV(B),sy(B)}import{randomUUID as UF}from"crypto";import{createHash as ey,randomUUID as $h}from"crypto";import{existsSync as _h,readFileSync as Jh}from"fs";import{hostname as xV}from"os";import{fileURLToPath as uV}from"url";import{extname as Wh,relative as dV,resolve as ZV,sep as Uh}from"path";var G8=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"],w0=2,g0=1,kU={sources:["id"],wiki_pages:["id"],source_revisions:["id"],chunks:["id"],chunk_embeddings:["id"],wiki_backlinks:["from_page_id","to_page_id"],citations:["id"],knowledge_indexes:["id"],runs:["id"],run_events:["id"],provider_usage:["id"],redaction_findings:["id"],storage_objects:["id"],audit_events:["id"],approval_gates:["id"],vector_index_entries:["id"],reindex_queue:["id"],knowledge_machines:["machine_id"],knowledge_sync_snapshots:["id"],knowledge_sync_changes:["id"],knowledge_sync_conflicts:["id"],knowledge_sync_table_clocks:["table_name","machine_id"],knowledge_sync_imports:["bundle_id"]},IU=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function D4($=new Date){return $.toISOString()}function _q($){return`${$}_${Date.now().toString(36)}_${$h().slice(0,8)}`}function nV($){let _=$?.trim();if(_)return _;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??xV()}function dJ($){if(Array.isArray($))return`[${$.map(dJ).join(",")}]`;if($&&typeof $==="object"){let _=$;return`{${Object.keys(_).sort().map((J)=>`${JSON.stringify(J)}:${dJ(_[J])}`).join(",")}}`}return JSON.stringify($)}function bU($){return`sha256:${ey("sha256").update($).digest("hex")}`}function U8($,_){return $.query(`SELECT COUNT(*) AS n FROM ${_}`).get()?.n??0}function Q8($,_){try{return JSON.parse($)}catch{return _}}function Y6($){return`"${$.replace(/"/g,'""')}"`}function Xh($){if($===void 0||$===null)return null;if(typeof $==="string"||typeof $==="number"||typeof $==="bigint"||typeof $==="boolean")return $;if($ instanceof Date)return $.toISOString();if(Buffer.isBuffer($)||$ instanceof Uint8Array)return $;if(typeof $==="object")return JSON.stringify($);return String($)}function cV($,_){return _.filter((J)=>N6($,J))}function N6($,_){let J=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(_);return Boolean(J)}function Gh($,_){let J=$.query(`PRAGMA table_info(${Y6(_)})`).all();return new Set(J.map((U)=>U.name))}function Yh($,_,J){let U=Gh($,_);return J.filter((W)=>U.has(W))}function iV($){if(!$||$.length===0)return[...G8];let _=new Set(G8),J=$.map((W)=>W.trim()).filter(Boolean),U=J.filter((W)=>!_.has(W));if(U.length>0)throw Error(`Unknown knowledge sync table(s): ${U.join(", ")}`);return J}function C1($,_){return kU[$].map((U)=>`${U}=${JSON.stringify(_[U]??null)}`).join("&")}var Qh=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function wU($,_=0){if(_>8)return"[truncated-depth]";if(typeof $==="string")return $.length>4000?`${$.slice(0,4000)}...[truncated]`:$;if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.slice(0,50).map((U)=>wU(U,_+1));let J={};for(let[U,W]of Object.entries($)){if(Qh.has(U.toLowerCase()))continue;J[U]=wU(W,_+1)}return J}function AU($){if(!$)return null;return wU($)}function Jq($){return bU(dJ($))}function qh($,_){let J={};for(let[U,W]of Object.entries($))if(U==="artifact_uri"&&typeof W==="string"&&_.has(W))J[U]=`artifact:${_.get(W)}`;else J[U]=W;return J}function f1($,_=new Map){return Jq(qh($,_))}function lV($,_){if(!N6($,_))return[];return $.query(`SELECT * FROM ${Y6(_)} ORDER BY rowid ASC`).all()}function Y8($,_,J=new Map){return Jq(_.map((U)=>({key:C1($,U),hash:f1(U,J)})).sort((U,W)=>U.key.localeCompare(W.key)))}function gU($,_,J){return $.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get(_,J)??null}function zh($){if(!N6($,"knowledge_sync_table_clocks"))return[];return $.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function q8($,_){let J=_.now??D4(),W=gU($,_.table,_.machineId)?.created_at??J;$.query(` + LIMIT ?`).all(...$,g)}function uq(_,$){return`${_.type} ${_.metadata_json} ${$.map((U)=>`${U.event} ${U.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function xq(_,$,g){let U=w$($,["source_ref","source_uri","evidence_uri","receipt_uri"],g),D=w$($,["artifact_uri"],g),I=w$($,["artifact_path","artifact_key"],g),j=U??D??I??`knowledge://project/runs/${_.id}`,N=_.prompt?Q0(_.prompt,g,180).text:null;return{id:T0("cite",`run\x00${_.id}\x00${j}`,12),kind:D||I?"artifact":"run",ref:j,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:D,artifact_path:I,run_id:_.id,run_event_id:null,revision:w$($,["revision"],g),hash:w$($,["hash","content_hash"],g),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function yq(_,$,g){let U=w$($,["source_ref","source_uri","evidence_uri","receipt_uri"],g),D=w$($,["artifact_uri"],g),I=w$($,["artifact_path","artifact_key"],g),j=U??D??I??`knowledge://project/runs/${_.run_id}`,N=Q0(_.event,g,160).text;return{id:T0("cite",`event\x00${_.id}\x00${j}`,12),kind:D||I?"artifact":"run_event",ref:j,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:D,artifact_path:I,run_id:_.run_id,run_event_id:_.id,revision:w$($,["revision"],g),hash:w$($,["hash","content_hash"],g),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function nW(_){let $=new Map;for(let g of _){let U=VE(`${g.title} ${g.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g,"").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g,"").replace(/[^a-z0-9 ]+/g,"").replace(/\b(?:run|event|completed|dry_run|pending)\b/g,"").replace(/\s+/g," ").trim().slice(0,220);if(!U)continue;$.set(U,[...$.get(U)??[],g.id])}return Array.from($.entries()).filter(([,g])=>g.length>1).map(([g,U])=>({id:T0("dup",g,12),reason:"normalized_text_match",evidence_ids:U,confidence:U.length>2?"high":"medium"}))}async function hq(_,$,g){let U=_.source==="loops"?"loops":"runs",D=(_.topic??_.query??"").trim(),I=Mq(D),j=cW(_.since,g),N=j.warning?[j.warning]:[];h(_.dbPath);let O=v(_.dbPath);try{let A=fq(O,j.cutoff,Math.max($*8,40)),L=wq(O,A.map((G)=>G.id),Math.max($*12,80)),z=new Map;for(let G of L)z.set(G.run_id,[...z.get(G.run_id)??[],G]);let J=(U==="loops"?A.filter((G)=>uq(G,z.get(G.id)??[])):A).map((G)=>{let R=uW(G.metadata_json),K=`${G.type} ${G.status} ${G.prompt??""} ${NI(R)} ${(z.get(G.id)??[]).map((Q)=>`${Q.event} ${Q.metadata_json}`).join(" ")}`;return{row:G,metadata:R,score:yW(K,I),text:K}}).filter((G)=>I.length===0||G.score>0).sort((G,R)=>R.score-G.score||R.row.updated_at.localeCompare(G.row.updated_at)||G.row.id.localeCompare(R.row.id)),P=[],S=[],X=0;for(let G of J.slice(0,Math.max($*2,$))){let R=xq(G.row,G.metadata,_.safetyPolicy);P.push(R);let K=NI(G.metadata),Q=[G.row.prompt,K].filter(Boolean).join(" | ")||`${G.row.type} ${G.row.status}`,T=Q0(Q,_.safetyPolicy,420);X+=T.redactions,S.push({id:`run:${G.row.id}`,kind:G.row.type,title:g6(`${G.row.type}: ${G.row.status}`,100),text_preview:T.text,score:G.score,citation_ids:[R.id],provenance:{source:U,record_ref:`knowledge://project/runs/${G.row.id}`,created_at:G.row.created_at,updated_at:G.row.updated_at,metadata_keys:BE(G.metadata)}});let q=(z.get(G.row.id)??[]).map((V)=>{let Z=uW(V.metadata_json),a=`${V.event} ${NI(Z)} ${V.metadata_json}`;return{event:V,metadata:Z,score:yW(a,I),text:a}}).filter((V)=>I.length===0||V.score>0).sort((V,Z)=>Z.score-V.score||Z.event.created_at.localeCompare(V.event.created_at)||V.event.id.localeCompare(Z.event.id)).slice(0,2);for(let V of q){let Z=yq(V.event,V.metadata,_.safetyPolicy);P.push(Z);let a=Q0(`${V.event}: ${NI(V.metadata)}`,_.safetyPolicy,320);X+=a.redactions,S.push({id:`event:${V.event.id}`,kind:`run_event:${V.event.level}`,title:g6(V.event.event,100),text_preview:a.text,score:V.score,citation_ids:[Z.id],provenance:{source:U,record_ref:`knowledge://project/runs/${V.event.run_id}`,created_at:V.event.created_at,updated_at:null,metadata_keys:BE(V.metadata)}})}}return{citations:P,evidence:S,duplicateCandidates:_.dedupe?nW(S):[],redactions:X,warnings:N,available:J.length}}finally{O.close()}}function cq(_){let $=_.purpose==="proposal"?`Proposal context: ${g6(_.query||"loop evidence",80)}`:`Knowledge context: ${g6(_.query,80)}`,g=_.evidence.slice(0,8).map((I)=>I.id),U=_.duplicates.slice(0,5).map((I)=>I.id),D=_.evidence.slice(0,5).map((I)=>`${I.id}: ${I.title}`);if(_.evidence.length===0)D.push("No matching bounded evidence was found.");return{title:$,bullets:D,evidence_ids:g,duplicate_candidate_ids:U,next_actions:_.source==="loops"?["Review duplicate_candidates before drafting a new proposal.","Use cited run refs for provenance; inspect a run only when more detail is needed.","Keep proposal writes approval-gated and idempotent."]:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]}}function dW(_){let $=new Set(_.evidence.flatMap((g)=>g.citation_ids));_.citations=_.citations.filter((g)=>$.has(g.id))}function hW(_){_.outline.evidence_ids=_.evidence.slice(0,8).map(($)=>$.id),_.outline.bullets=_.evidence.length>0?_.evidence.slice(0,5).map(($)=>`${$.id}: ${$.title}`):["No matching bounded evidence was found."],_.outline.duplicate_candidate_ids=_.duplicate_candidates.slice(0,5).map(($)=>$.id)}function nq(_){let $=_.budgets.max_tokens,g=new Set(_.warnings);while(xW(_)>$){let U=_.evidence.map((I,j)=>({entry:I,index:j})).filter(({entry:I})=>I.text_preview.length>180).sort((I,j)=>j.entry.text_preview.length-I.entry.text_preview.length)[0];if(U){U.entry.text_preview=g6(U.entry.text_preview,180),g.add("text_preview_truncated_for_token_budget");continue}let D=_.citations.filter((I)=>(I.quote_preview?.length??0)>120).sort((I,j)=>(j.quote_preview?.length??0)-(I.quote_preview?.length??0))[0];if(D?.quote_preview){D.quote_preview=g6(D.quote_preview,120),g.add("citation_quote_truncated_for_token_budget");continue}if(_.evidence.length>0){_.evidence.pop(),_.budgets.items_truncated+=1,_.duplicate_candidates=_.duplicate_candidates.map((I)=>({...I,evidence_ids:I.evidence_ids.filter((j)=>_.evidence.some((N)=>N.id===j))})).filter((I)=>I.evidence_ids.length>1),hW(_),g.add("evidence_truncated_for_token_budget"),dW(_);continue}if(_.outline.next_actions.length>1){_.outline.next_actions.pop(),g.add("outline_truncated_for_token_budget");continue}g.add("token_budget_floor_exceeded");break}if(_.warnings=Array.from(g).sort(),_.budgets.items_included=_.evidence.length,hW(_),_.budgets.estimated_tokens=xW(_),_.budgets.token_budget_exceeded=_.budgets.estimated_tokens>$,_.budgets.token_budget_exceeded)throw Error(`Unable to build context pack within ${$} token budget; increase --max-tokens.`);return _.message=`${_.evidence.length} bounded evidence item(s), estimated ${_.budgets.estimated_tokens}/${$} token(s)`,_}async function mW(_){let $=_.now??new Date,g=_.source??"search",U=_.purpose??(g==="loops"||g==="runs"?"proposal":"agent_context"),D=Hq(_.maxTokens),I=kq(_.maxItems,_.limit),j=KE(_.query??_.topic??"");if(U==="proposal"&&g!=="search"&&!j)throw Error("Proposal context requires --topic or a positional topic.");if(g!=="search")h(_.dbPath);let N=cW(_.since,$).cutoff??_.since??"",O=g==="search"?await vq(_,I):await hq(_,I,$),A=O.evidence.sort((P,S)=>S.score-P.score||P.id.localeCompare(S.id)).slice(0,I),L=O.citations.filter((P,S,X)=>X.findIndex((G)=>G.id===P.id)===S).sort((P,S)=>P.id.localeCompare(S.id)),z=_.dedupe?nW(A):O.duplicateCandidates.filter((P)=>P.evidence_ids.every((S)=>A.some((X)=>X.id===S))),W=cq({source:g,purpose:U,query:j,evidence:A,duplicates:z}),J={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:g,purpose:U,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:T0("ctx",[g,U,j,N,_.dedupe===!0?"dedupe":"no-dedupe",_.semantic===!0?"semantic":"keyword",_.modelRef??"",_.limit??"",D,I,A.map((P)=>P.id).join(","),L.map((P)=>P.id).join(",")].join("\x00"),20),budgets:{max_tokens:D,estimated_tokens:0,max_items:I,items_included:A.length,items_available:O.available,items_truncated:Math.max(0,O.available-A.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:O.redactions,reminders:Cq(g)},citations:L,evidence:A,duplicate_candidates:z,outline:W,warnings:O.warnings,message:`${A.length} bounded evidence item(s), estimated under ${D} token(s)`};return dW(J),nq(J)}import{randomUUID as SR}from"crypto";import{createHash as dq,randomUUID as mq}from"crypto";import{existsSync as iq,readFileSync as lq}from"fs";import{hostname as eW}from"os";import{fileURLToPath as aW}from"url";import{extname as tq,relative as sW,resolve as iW,sep as oq}from"path";var AI=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"],V6=2,F6=1,dg={sources:["id"],wiki_pages:["id"],source_revisions:["id"],chunks:["id"],chunk_embeddings:["id"],wiki_backlinks:["from_page_id","to_page_id"],citations:["id"],knowledge_indexes:["id"],runs:["id"],run_events:["id"],provider_usage:["id"],redaction_findings:["id"],storage_objects:["id"],audit_events:["id"],approval_gates:["id"],vector_index_entries:["id"],reindex_queue:["id"],knowledge_machines:["machine_id"],knowledge_sync_snapshots:["id"],knowledge_sync_changes:["id"],knowledge_sync_conflicts:["id"],knowledge_sync_table_clocks:["table_name","machine_id"],knowledge_sync_imports:["bundle_id"]},mg=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function u$(_=new Date){return _.toISOString()}function CE(_){return`${_}_${Date.now().toString(36)}_${mq().slice(0,8)}`}function _X(_){let $=_?.trim();if($)return $;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??eW()}function B0(_){if(Array.isArray(_))return`[${_.map(B0).join(",")}]`;if(_&&typeof _==="object"){let $=_;return`{${Object.keys($).sort().map((g)=>`${JSON.stringify(g)}:${B0($[g])}`).join(",")}}`}return JSON.stringify(_)}function hg(_){return`sha256:${dq("sha256").update(_).digest("hex")}`}function EI(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function JI(_,$){try{return JSON.parse(_)}catch{return $}}function j$(_){return`"${_.replace(/"/g,'""')}"`}function pq(_){if(_===void 0||_===null)return null;if(typeof _==="string"||typeof _==="number"||typeof _==="bigint"||typeof _==="boolean")return _;if(_ instanceof Date)return _.toISOString();if(Buffer.isBuffer(_)||_ instanceof Uint8Array)return _;if(typeof _==="object")return JSON.stringify(_);return String(_)}function $X(_,$){return $.filter((g)=>J$(_,g))}function J$(_,$){let g=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get($);return Boolean(g)}function eq(_,$){let g=_.query(`PRAGMA table_info(${j$($)})`).all();return new Set(g.map((U)=>U.name))}function aq(_,$,g){let U=eq(_,$);return g.filter((D)=>U.has(D))}function gX(_){if(!_||_.length===0)return[...AI];let $=new Set(AI),g=_.map((D)=>D.trim()).filter(Boolean),U=g.filter((D)=>!$.has(D));if(U.length>0)throw Error(`Unknown knowledge sync table(s): ${U.join(", ")}`);return g}function E4(_,$){return dg[_].map((U)=>`${U}=${JSON.stringify($[U]??null)}`).join("&")}var sq=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function cg(_,$=0){if($>8)return"[truncated-depth]";if(typeof _==="string")return _.length>4000?`${_.slice(0,4000)}...[truncated]`:_;if(_===null||typeof _!=="object")return _;if(Array.isArray(_))return _.slice(0,50).map((U)=>cg(U,$+1));let g={};for(let[U,D]of Object.entries(_)){if(sq.has(U.toLowerCase()))continue;g[U]=cg(D,$+1)}return g}function yg(_){if(!_)return null;return cg(_)}function rE(_){return hg(B0(_))}function _B(_,$){let g={};for(let[U,D]of Object.entries(_))if(U==="artifact_uri"&&typeof D==="string"&&$.has(D))g[U]=`artifact:${$.get(D)}`;else g[U]=D;return g}function N4(_,$=new Map){return rE(_B(_,$))}function DX(_,$){if(!J$(_,$))return[];return _.query(`SELECT * FROM ${j$($)} ORDER BY rowid ASC`).all()}function LI(_,$,g=new Map){return rE($.map((U)=>({key:E4(_,U),hash:N4(U,g)})).sort((U,D)=>U.key.localeCompare(D.key)))}function ng(_,$,g){return _.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get($,g)??null}function $B(_){if(!J$(_,"knowledge_sync_table_clocks"))return[];return _.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function PI(_,$){let g=$.now??u$(),D=ng(_,$.table,$.machineId)?.created_at??g;_.query(` INSERT INTO knowledge_sync_table_clocks ( table_name, machine_id, logical_clock, high_water_hash, high_water_bundle_id, origin_machine_id, updated_by_machine_id, last_applied_at, metadata_json, @@ -842,17 +843,17 @@ ${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config, last_applied_at = excluded.last_applied_at, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `).run(_.table,_.machineId,_.logicalClock,_.highWaterHash,_.highWaterBundleId??null,_.originMachineId??_.machineId,_.updatedByMachineId??_.machineId,_.lastAppliedAt??J,JSON.stringify(_.metadata??{}),W,J);let X=gU($,_.table,_.machineId);if(!X)throw Error(`Failed to record sync clock for ${_.table}:${_.machineId}`);return X}function jh($,_){let J=gU($,_.table,_.machineId),U=J?.high_water_hash===_.highWaterHash?J.logical_clock:(J?.logical_clock??0)+1,W=_.record?q8($,{table:_.table,machineId:_.machineId,logicalClock:U,highWaterHash:_.highWaterHash,highWaterBundleId:null,originMachineId:J?.origin_machine_id??_.machineId,updatedByMachineId:_.machineId,lastAppliedAt:_.now,metadata:{source:"export",row_count:_.rowCount},now:_.now}):{table_name:_.table,machine_id:_.machineId,logical_clock:U,high_water_hash:_.highWaterHash,high_water_bundle_id:J?.high_water_bundle_id??null,origin_machine_id:J?.origin_machine_id??_.machineId,updated_by_machine_id:_.machineId,last_applied_at:_.now,metadata_json:"{}",created_at:J?.created_at??_.now,updated_at:_.now};return{table:_.table,machine_id:_.machineId,logical_clock:W.logical_clock,high_water_hash:_.highWaterHash,high_water_bundle_id:W.high_water_bundle_id,row_count:_.rowCount,updated_at:W.updated_at}}function Dh($,_,J,U,W){if(_.high_water_bundle_id=J,!U)return;q8($,{table:_.table,machineId:_.machine_id,logicalClock:_.logical_clock,highWaterHash:_.high_water_hash,highWaterBundleId:J,originMachineId:_.machine_id,updatedByMachineId:_.machine_id,lastAppliedAt:W,metadata:{source:"export",row_count:_.row_count},now:W})}function rV($,_){return $.table_clocks?.find((J)=>J.table===_)??null}function Oh($,_){if(!$||!_)return!1;return _.logical_clock<$.logical_clock}function Lh($,_,J){if(J.length===0)return 0;let U=Yh($,_,Object.keys(J[0]));if(U.length===0)return 0;let W=kU[_],X=U.map(Y6).join(", "),G=U.map(()=>"?").join(", "),Y=W.map(Y6).join(", "),Q=U.filter((B)=>!W.includes(B)),q=W[0],L=Q.length>0?Q.map((B)=>`${Y6(B)} = excluded.${Y6(B)}`).join(", "):`${Y6(q)} = excluded.${Y6(q)}`,N=$.query(`INSERT INTO ${Y6(_)} (${X}) VALUES (${G}) - ON CONFLICT (${Y}) DO UPDATE SET ${L}`);return $.transaction((B)=>{for(let H of B)N.run(...U.map((V)=>Xh(H[V])))})(J),J.length}function pV($,_){let J=kU[$],U=[],W=_;for(let X=0;X=0?Q.slice(0,N):Q;try{U.push(JSON.parse(R))}catch{return null}W=N>=0&&L?Q.slice(N+1):""}return W.length===0?U:null}function oV($){return kU[$].map((_)=>`${Y6(_)} = ?`).join(" AND ")}function Bh($,_,J){if(!N6($,"knowledge_sync_changes"))return new Map;let U=$.query(`SELECT entity_id, next_hash + `).run($.table,$.machineId,$.logicalClock,$.highWaterHash,$.highWaterBundleId??null,$.originMachineId??$.machineId,$.updatedByMachineId??$.machineId,$.lastAppliedAt??g,JSON.stringify($.metadata??{}),D,g);let I=ng(_,$.table,$.machineId);if(!I)throw Error(`Failed to record sync clock for ${$.table}:${$.machineId}`);return I}function gB(_,$){let g=ng(_,$.table,$.machineId),U=g?.high_water_hash===$.highWaterHash?g.logical_clock:(g?.logical_clock??0)+1,D=$.record?PI(_,{table:$.table,machineId:$.machineId,logicalClock:U,highWaterHash:$.highWaterHash,highWaterBundleId:null,originMachineId:g?.origin_machine_id??$.machineId,updatedByMachineId:$.machineId,lastAppliedAt:$.now,metadata:{source:"export",row_count:$.rowCount},now:$.now}):{table_name:$.table,machine_id:$.machineId,logical_clock:U,high_water_hash:$.highWaterHash,high_water_bundle_id:g?.high_water_bundle_id??null,origin_machine_id:g?.origin_machine_id??$.machineId,updated_by_machine_id:$.machineId,last_applied_at:$.now,metadata_json:"{}",created_at:g?.created_at??$.now,updated_at:$.now};return{table:$.table,machine_id:$.machineId,logical_clock:D.logical_clock,high_water_hash:$.highWaterHash,high_water_bundle_id:D.high_water_bundle_id,row_count:$.rowCount,updated_at:D.updated_at}}function DB(_,$,g,U,D){if($.high_water_bundle_id=g,!U)return;PI(_,{table:$.table,machineId:$.machine_id,logicalClock:$.logical_clock,highWaterHash:$.high_water_hash,highWaterBundleId:g,originMachineId:$.machine_id,updatedByMachineId:$.machine_id,lastAppliedAt:D,metadata:{source:"export",row_count:$.row_count},now:D})}function UX(_,$){return _.table_clocks?.find((g)=>g.table===$)??null}function UB(_,$){if(!_||!$)return!1;return $.logical_clock<_.logical_clock}function IB(_,$,g){if(g.length===0)return 0;let U=aq(_,$,Object.keys(g[0]));if(U.length===0)return 0;let D=dg[$],I=U.map(j$).join(", "),j=U.map(()=>"?").join(", "),N=D.map(j$).join(", "),O=U.filter((J)=>!D.includes(J)),A=D[0],L=O.length>0?O.map((J)=>`${j$(J)} = excluded.${j$(J)}`).join(", "):`${j$(A)} = excluded.${j$(A)}`,z=_.query(`INSERT INTO ${j$($)} (${I}) VALUES (${j}) + ON CONFLICT (${N}) DO UPDATE SET ${L}`);return _.transaction((J)=>{for(let P of J)z.run(...U.map((S)=>pq(P[S])))})(g),g.length}function IX(_,$){let g=dg[_],U=[],D=$;for(let I=0;I=0?O.slice(0,z):O;try{U.push(JSON.parse(W))}catch{return null}D=z>=0&&L?O.slice(z+1):""}return D.length===0?U:null}function jX(_){return dg[_].map(($)=>`${j$($)} = ?`).join(" AND ")}function jB(_,$,g){if(!J$(_,"knowledge_sync_changes"))return new Map;let U=_.query(`SELECT entity_id, next_hash FROM knowledge_sync_changes WHERE origin_machine_id = ? AND entity_kind = ? - ORDER BY created_at ASC, id ASC`).all(J,_),W=new Map;for(let X of U)W.set(X.entity_id,X.next_hash);return W}function Hh($,_){if(N6($,"chunks_fts"))$.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(_);if(N6($,"chunk_embeddings"))$.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run(_);if(N6($,"vector_index_entries"))$.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run(_);if(N6($,"citations"))$.query("DELETE FROM citations WHERE chunk_id = ?").run(_)}function Nh($,_,J){let U=pV(_,J);if(!U)return!1;let W=oV(_),X=$.query(`SELECT * FROM ${Y6(_)} WHERE ${W} LIMIT 1`).get(...U);if(!X)return!1;if(_==="chunks"&&typeof X.id==="string")Hh($,X.id);return $.query(`DELETE FROM ${Y6(_)} WHERE ${W}`).run(...U),!0}function Vh($,_){if(!N6($,"chunks_fts"))return;for(let J of _){let U=typeof J.id==="string"?J.id:null,W=typeof J.text==="string"?J.text:null;if(!U||W===null)continue;let X="",G="",Y=typeof J.source_revision_id==="string"?J.source_revision_id:null;if(Y){let Q=$.query(`SELECT s.title, s.uri + ORDER BY created_at ASC, id ASC`).all(g,$),D=new Map;for(let I of U)D.set(I.entity_id,I.next_hash);return D}function NB(_,$){if(J$(_,"chunks_fts"))_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run($);if(J$(_,"chunk_embeddings"))_.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run($);if(J$(_,"vector_index_entries"))_.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run($);if(J$(_,"citations"))_.query("DELETE FROM citations WHERE chunk_id = ?").run($)}function EB(_,$,g){let U=IX($,g);if(!U)return!1;let D=jX($),I=_.query(`SELECT * FROM ${j$($)} WHERE ${D} LIMIT 1`).get(...U);if(!I)return!1;if($==="chunks"&&typeof I.id==="string")NB(_,I.id);return _.query(`DELETE FROM ${j$($)} WHERE ${D}`).run(...U),!0}function OB(_,$){if(!J$(_,"chunks_fts"))return;for(let g of $){let U=typeof g.id==="string"?g.id:null,D=typeof g.text==="string"?g.text:null;if(!U||D===null)continue;let I="",j="",N=typeof g.source_revision_id==="string"?g.source_revision_id:null;if(N){let O=_.query(`SELECT s.title, s.uri FROM source_revisions sr JOIN sources s ON s.id = sr.source_id WHERE sr.id = ? - LIMIT 1`).get(Y);X=Q?.title??"",G=Q?.uri??""}if(!G&&typeof J.metadata_json==="string"){let Q=Q8(J.metadata_json,{});G=typeof Q.source_uri==="string"?Q.source_uri:""}$.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(U),$.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(U,W,X,G)}}function Rh($,_,J){if(_==="chunks")Vh($,J)}function Kh($,_){let J=dV($,_);return J!==".."&&!J.startsWith("..")&&!J.startsWith(`..${Uh}`)}function Fh($,_){let J=Q8($.metadata_json,{});if(typeof J.key==="string")return J.key;if(!$.artifact_uri.startsWith("file://"))return null;try{let U=uV($.artifact_uri),W=ZV(_),X=ZV(U);if(!Kh(W,X))return null;let G=dV(W,X).replace(/\\/g,"/");return G?z4(G):null}catch{return null}}var Eh=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function Mh($,_){let J=$?.toLowerCase()??"";if(J.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(J))return!0;return _?Eh.has(Wh(_).toLowerCase()):!1}function P1($){let _=new Map;for(let J of $)if(J.key)_.set(J.artifact_uri,J.key);return _}function A0($){return Jq({key:$.key,kind:$.kind,hash:$.hash,size_bytes:$.size_bytes})}function z8($){return $.key??$.artifact_uri}function Ah($,_){return $.artifact_uri.startsWith("s3://")&&_.artifact_store.type==="s3"&&$.artifact_uri.startsWith(_.artifact_store.uri_prefix)}function tV($){return Object.fromEntries(G8.map((_)=>[_,N6($,_)?U8($,_):0]))}function bh($){return $.query(`SELECT artifact_uri, kind, hash, size_bytes + LIMIT 1`).get(N);I=O?.title??"",j=O?.uri??""}if(!j&&typeof g.metadata_json==="string"){let O=JI(g.metadata_json,{});j=typeof O.source_uri==="string"?O.source_uri:""}_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(U),_.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(U,D,I,j)}}function AB(_,$,g){if($==="chunks")OB(_,g)}function LB(_,$){let g=sW(_,$);return g!==".."&&!g.startsWith("..")&&!g.startsWith(`..${oq}`)}function JB(_,$){let g=JI(_.metadata_json,{});if(typeof g.key==="string")return g.key;if(!_.artifact_uri.startsWith("file://"))return null;try{let U=aW(_.artifact_uri),D=iW($),I=iW(U);if(!LB(D,I))return null;let j=sW(D,I).replace(/\\/g,"/");return j?f$(j):null}catch{return null}}var PB=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function zB(_,$){let g=_?.toLowerCase()??"";if(g.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(g))return!0;return $?PB.has(tq($).toLowerCase()):!1}function O4(_){let $=new Map;for(let g of _)if(g.key)$.set(g.artifact_uri,g.key);return $}function B6(_){return rE({key:_.key,kind:_.kind,hash:_.hash,size_bytes:_.size_bytes})}function zI(_){return _.key??_.artifact_uri}function SB(_,$){return _.artifact_uri.startsWith("s3://")&&$.artifact_store.type==="s3"&&_.artifact_uri.startsWith($.artifact_store.uri_prefix)}function NX(_){return Object.fromEntries(AI.map(($)=>[$,J$(_,$)?EI(_,$):0]))}function WB(_){return _.query(`SELECT artifact_uri, kind, hash, size_bytes FROM storage_objects - ORDER BY artifact_uri ASC`).all()}function wh($,_){return{machine_id:$.machine_id,hostname:$.hostname,platform:$.platform,user_label:$.user,workspace_home:$.workspace_path,tailscale_dns:$.tailscale.dns_name,tailscale_ips_json:JSON.stringify($.tailscale.ips),ssh_target:$.ssh.command_target,last_seen_at:$.local||$.tailscale.online===!0||$.heartbeat_status==="online"?_:$.last_heartbeat_at,capabilities_json:JSON.stringify({route_hints:$.route_hints,heartbeat_status:$.heartbeat_status,manifest_declared:$.manifest_declared}),metadata_json:JSON.stringify({...$.metadata,source:$.source,tags:$.tags,tailscale:$.tailscale,ssh:$.ssh}),created_at:_,updated_at:_}}function tQ($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function gh($){if(!$)return[];try{let _=JSON.parse($);return Array.isArray(_)?_:[]}catch{return[]}}function b0($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function X8($){return Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))}function uJ($){if(Array.isArray($))return`[${$.map(uJ).join(",")}]`;if($&&typeof $==="object")return`{${Object.entries($).filter(([,_])=>_!==void 0).sort(([_],[J])=>_.localeCompare(J)).map(([_,J])=>`${JSON.stringify(_)}:${uJ(J)}`).join(",")}}`;return JSON.stringify($)}function vV($){let{recorded_at:_,...J}=$;return J}function N_($){return typeof $==="string"&&$.length>0?$:null}function kh($){return typeof $==="number"&&Number.isFinite($)?$:null}function yV($){return typeof $==="boolean"?$:null}function Ih($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function aV($){let _=b0($),J=N_(_.observed_at),U=N_(_.source_authority);if(!J||!U)return null;return{observed_at:J,verified_at:N_(_.verified_at),expires_at:N_(_.expires_at),ttl_ms:kh(_.ttl_ms),source_authority:U,confidence:N_(_.confidence),cacheable:_.cacheable===!0,stale:_.stale===!0,reasons:Ih(_.reasons)}}function sV($,_){if(!$||$.stale)return!1;if(!$.expires_at)return!0;let J=Date.parse($.expires_at),U=Date.parse(_);return Number.isNaN(J)||Number.isNaN(U)||J>U}function fh($,_){return N_(_.source)===$.source&&N_(_.target)===$.target&&N_(_.route)===$.route&&N_(_.target_kind)===$.targetKind&&N_(_.confidence)===$.confidence}function Ch($,_){return N_(_.source)===$.source&&N_(_.requested_machine_id)===$.requested_machine_id&&N_(_.machine_id)===$.machine_id&&N_(_.project_id)===$.project_id&&N_(_.repo_name)===$.repo_name&&N_(_.project_root)===$.project_root&&N_(_.project_root_source)===$.project_root_source&&N_(_.workspace_root)===$.workspace_root&&N_(_.workspace_root_source)===$.workspace_root_source&&N_(_.open_files_root)===$.open_files_root&&N_(_.open_files_root_source)===$.open_files_root_source&&N_(_.trust_status)===$.trust_status&&N_(_.auth_status)===$.auth_status&&yV(_.current)===$.current&&yV(_.primary)===$.primary}function Ph($,_,J){if(!$)return null;let U=aV(_.cacheability);if(U&&sV(U,J)&&fh($,_))return{...$,cacheability:U};return $}function Th($,_,J){if(!$)return null;let U=aV(_.cacheability);if(U&&sV(U,J)&&Ch($,_))return{...$,cacheability:U};return $}function Sh($){return $.workspace?.machine_id??$.workspace?.requested_machine_id??$.machineId??$.route?.target??xV()}function Zh($,_){let J=new Set,U=Array.isArray(_.sources)?_.sources:[];for(let W of U)if(typeof W==="string")J.add(W);if(typeof _.source==="string")J.add(_.source);if($.route?.source)J.add($.route.source);if($.workspace?.source)J.add($.workspace.source);return J.add("knowledge"),[...J].sort()}function hV($,_){if(_?.target&&(_.route==="tailscale"||_.targetKind==="tailscale"))return _.target;return $?.tailscale_dns??null}function vh($,_,J){let U=b0(_.resolver_evidence),W=$.route?X8({source:$.route.source,target:$.route.target,route:$.route.route,target_kind:$.route.targetKind,confidence:$.route.confidence,adapter:$.route.adapter,evidence:$.route.evidence,cacheability:$.route.cacheability,warnings:$.route.warnings}):b0(U.route),X=$.workspace?X8({source:$.workspace.source,requested_machine_id:$.workspace.requested_machine_id,machine_id:$.workspace.machine_id,project_id:$.workspace.project_id,repo_name:$.workspace.repo_name,project_root:$.workspace.project_root,project_root_source:$.workspace.project_root_source,workspace_root:$.workspace.workspace_root,workspace_root_source:$.workspace.workspace_root_source,open_files_root:$.workspace.open_files_root,open_files_root_source:$.workspace.open_files_root_source,trust_status:$.workspace.trust_status,auth_status:$.workspace.auth_status,current:$.workspace.current,primary:$.workspace.primary,diagnostics:$.workspace.diagnostics,repair_hints:$.workspace.repair_hints,evidence:$.workspace.evidence,cacheability:$.workspace.cacheability,warnings:$.workspace.warnings}):b0(U.workspace);return X8({...U,recorded_at:J,route:W,workspace:X})}function eV($,_){a($);let J=m($);try{let U=Sh(_),W=J.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(U)??null,X=D4(_.now),G=tQ(W?.capabilities_json),Y=tQ(W?.metadata_json),Q=b0(G.resolver),q=b0(Y.resolver_evidence),L=b0(q.route),N=b0(q.workspace),R=Ph(_.route?.source==="registry"?null:_.route??null,L,X),B=Th(_.workspace?.source==="registry"?null:_.workspace??null,N,X),H={..._,route:R,workspace:B},V={...G,resolver:X8({...Q,route_source:R?.source??Q.route_source,route_kind:R?.route??Q.route_kind,route_target_kind:R?.targetKind??Q.route_target_kind,route_confidence:R?.confidence??Q.route_confidence,route_cacheable:R?.cacheability?.cacheable??Q.route_cacheable,route_stale:R?.cacheability?.stale??Q.route_stale,route_expires_at:R?.cacheability?.expires_at??Q.route_expires_at,route_observed_at:R?.cacheability?.observed_at??Q.route_observed_at,route_source_authority:R?.cacheability?.source_authority??Q.route_source_authority,workspace_source:B?.source??Q.workspace_source,project_root_source:B?.project_root_source??Q.project_root_source,workspace_root_source:B?.workspace_root_source??Q.workspace_root_source,open_files_root_source:B?.open_files_root_source??Q.open_files_root_source,trust_status:B?.trust_status??Q.trust_status,auth_status:B?.auth_status??Q.auth_status,workspace_cacheable:B?.cacheability?.cacheable??Q.workspace_cacheable,workspace_stale:B?.cacheability?.stale??Q.workspace_stale,workspace_expires_at:B?.cacheability?.expires_at??Q.workspace_expires_at,workspace_observed_at:B?.cacheability?.observed_at??Q.workspace_observed_at,workspace_source_authority:B?.cacheability?.source_authority??Q.workspace_source_authority}),route_fallback:Boolean(R?.target??W?.ssh_target),workspace_fallback:Boolean(B?.project_root??W?.workspace_home)},K=vh(H,Y,X);if(W){let F=q;if(W.workspace_home===(B?.project_root??W.workspace_home??null)&&W.tailscale_dns===hV(W,R)&&W.ssh_target===(R?.target??W.ssh_target??null)&&uJ(tQ(W.capabilities_json))===uJ(V)&&uJ(vV(F))===uJ(vV(K)))return W}let E={machine_id:U,hostname:W?.hostname??null,platform:W?.platform??null,user_label:W?.user_label??null,workspace_home:B?.project_root??W?.workspace_home??null,tailscale_dns:hV(W,R),tailscale_ips_json:JSON.stringify(gh(W?.tailscale_ips_json)),ssh_target:R?.target??W?.ssh_target??null,last_seen_at:X,capabilities_json:JSON.stringify(V),metadata_json:JSON.stringify({...Y,source:"knowledge",sources:Zh(H,Y),resolver_evidence:K}),created_at:W?.created_at??X,updated_at:X};return $R(J,E),E}finally{J.close()}}function $R($,_){$.query(` + ORDER BY artifact_uri ASC`).all()}function XB(_,$){return{machine_id:_.machine_id,hostname:_.hostname,platform:_.platform,user_label:_.user,workspace_home:_.workspace_path,tailscale_dns:_.tailscale.dns_name,tailscale_ips_json:JSON.stringify(_.tailscale.ips),ssh_target:_.ssh.command_target,last_seen_at:_.local||_.tailscale.online===!0||_.heartbeat_status==="online"?$:_.last_heartbeat_at,capabilities_json:JSON.stringify({route_hints:_.route_hints,heartbeat_status:_.heartbeat_status,manifest_declared:_.manifest_declared}),metadata_json:JSON.stringify({..._.metadata,source:_.source,tags:_.tags,tailscale:_.tailscale,ssh:_.ssh}),created_at:$,updated_at:$}}function ME(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function RB(_){if(!_)return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function K6(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function OI(_){return Object.fromEntries(Object.entries(_).filter(([,$])=>$!==void 0))}function q0(_){if(Array.isArray(_))return`[${_.map(q0).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).filter(([,$])=>$!==void 0).sort(([$],[g])=>$.localeCompare(g)).map(([$,g])=>`${JSON.stringify($)}:${q0(g)}`).join(",")}}`;return JSON.stringify(_)}function lW(_){let{recorded_at:$,...g}=_;return g}function M_(_){return typeof _==="string"&&_.length>0?_:null}function GB(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function tW(_){return typeof _==="boolean"?_:null}function YB(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function EX(_){let $=K6(_),g=M_($.observed_at),U=M_($.source_authority);if(!g||!U)return null;return{observed_at:g,verified_at:M_($.verified_at),expires_at:M_($.expires_at),ttl_ms:GB($.ttl_ms),source_authority:U,confidence:M_($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:YB($.reasons)}}function OX(_,$){if(!_||_.stale)return!1;if(!_.expires_at)return!0;let g=Date.parse(_.expires_at),U=Date.parse($);return Number.isNaN(g)||Number.isNaN(U)||g>U}function QB(_,$){return M_($.source)===_.source&&M_($.target)===_.target&&M_($.route)===_.route&&M_($.target_kind)===_.targetKind&&M_($.confidence)===_.confidence}function TB(_,$){return M_($.source)===_.source&&M_($.requested_machine_id)===_.requested_machine_id&&M_($.machine_id)===_.machine_id&&M_($.project_id)===_.project_id&&M_($.repo_name)===_.repo_name&&M_($.project_root)===_.project_root&&M_($.project_root_source)===_.project_root_source&&M_($.workspace_root)===_.workspace_root&&M_($.workspace_root_source)===_.workspace_root_source&&M_($.open_files_root)===_.open_files_root&&M_($.open_files_root_source)===_.open_files_root_source&&M_($.trust_status)===_.trust_status&&M_($.auth_status)===_.auth_status&&tW($.current)===_.current&&tW($.primary)===_.primary}function qB(_,$,g){if(!_)return null;let U=EX($.cacheability);if(U&&OX(U,g)&&QB(_,$))return{..._,cacheability:U};return _}function BB(_,$,g){if(!_)return null;let U=EX($.cacheability);if(U&&OX(U,g)&&TB(_,$))return{..._,cacheability:U};return _}function KB(_){return _.workspace?.machine_id??_.workspace?.requested_machine_id??_.machineId??_.route?.target??eW()}function VB(_,$){let g=new Set,U=Array.isArray($.sources)?$.sources:[];for(let D of U)if(typeof D==="string")g.add(D);if(typeof $.source==="string")g.add($.source);if(_.route?.source)g.add(_.route.source);if(_.workspace?.source)g.add(_.workspace.source);return g.add("knowledge"),[...g].sort()}function oW(_,$){if($?.target&&($.route==="tailscale"||$.targetKind==="tailscale"))return $.target;return _?.tailscale_dns??null}function FB(_,$,g){let U=K6($.resolver_evidence),D=_.route?OI({source:_.route.source,target:_.route.target,route:_.route.route,target_kind:_.route.targetKind,confidence:_.route.confidence,adapter:_.route.adapter,evidence:_.route.evidence,cacheability:_.route.cacheability,warnings:_.route.warnings}):K6(U.route),I=_.workspace?OI({source:_.workspace.source,requested_machine_id:_.workspace.requested_machine_id,machine_id:_.workspace.machine_id,project_id:_.workspace.project_id,repo_name:_.workspace.repo_name,project_root:_.workspace.project_root,project_root_source:_.workspace.project_root_source,workspace_root:_.workspace.workspace_root,workspace_root_source:_.workspace.workspace_root_source,open_files_root:_.workspace.open_files_root,open_files_root_source:_.workspace.open_files_root_source,trust_status:_.workspace.trust_status,auth_status:_.workspace.auth_status,current:_.workspace.current,primary:_.workspace.primary,diagnostics:_.workspace.diagnostics,repair_hints:_.workspace.repair_hints,evidence:_.workspace.evidence,cacheability:_.workspace.cacheability,warnings:_.workspace.warnings}):K6(U.workspace);return OI({...U,recorded_at:g,route:D,workspace:I})}function AX(_,$){h(_);let g=v(_);try{let U=KB($),D=g.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(U)??null,I=u$($.now),j=ME(D?.capabilities_json),N=ME(D?.metadata_json),O=K6(j.resolver),A=K6(N.resolver_evidence),L=K6(A.route),z=K6(A.workspace),W=qB($.route?.source==="registry"?null:$.route??null,L,I),J=BB($.workspace?.source==="registry"?null:$.workspace??null,z,I),P={...$,route:W,workspace:J},S={...j,resolver:OI({...O,route_source:W?.source??O.route_source,route_kind:W?.route??O.route_kind,route_target_kind:W?.targetKind??O.route_target_kind,route_confidence:W?.confidence??O.route_confidence,route_cacheable:W?.cacheability?.cacheable??O.route_cacheable,route_stale:W?.cacheability?.stale??O.route_stale,route_expires_at:W?.cacheability?.expires_at??O.route_expires_at,route_observed_at:W?.cacheability?.observed_at??O.route_observed_at,route_source_authority:W?.cacheability?.source_authority??O.route_source_authority,workspace_source:J?.source??O.workspace_source,project_root_source:J?.project_root_source??O.project_root_source,workspace_root_source:J?.workspace_root_source??O.workspace_root_source,open_files_root_source:J?.open_files_root_source??O.open_files_root_source,trust_status:J?.trust_status??O.trust_status,auth_status:J?.auth_status??O.auth_status,workspace_cacheable:J?.cacheability?.cacheable??O.workspace_cacheable,workspace_stale:J?.cacheability?.stale??O.workspace_stale,workspace_expires_at:J?.cacheability?.expires_at??O.workspace_expires_at,workspace_observed_at:J?.cacheability?.observed_at??O.workspace_observed_at,workspace_source_authority:J?.cacheability?.source_authority??O.workspace_source_authority}),route_fallback:Boolean(W?.target??D?.ssh_target),workspace_fallback:Boolean(J?.project_root??D?.workspace_home)},X=FB(P,N,I);if(D){let R=A;if(D.workspace_home===(J?.project_root??D.workspace_home??null)&&D.tailscale_dns===oW(D,W)&&D.ssh_target===(W?.target??D.ssh_target??null)&&q0(ME(D.capabilities_json))===q0(S)&&q0(lW(R))===q0(lW(X)))return D}let G={machine_id:U,hostname:D?.hostname??null,platform:D?.platform??null,user_label:D?.user_label??null,workspace_home:J?.project_root??D?.workspace_home??null,tailscale_dns:oW(D,W),tailscale_ips_json:JSON.stringify(RB(D?.tailscale_ips_json)),ssh_target:W?.target??D?.ssh_target??null,last_seen_at:I,capabilities_json:JSON.stringify(S),metadata_json:JSON.stringify({...N,source:"knowledge",sources:VB(P,N),resolver_evidence:X}),created_at:D?.created_at??I,updated_at:I};return LX(g,G),G}finally{g.close()}}function LX(_,$){_.query(` INSERT INTO knowledge_machines ( machine_id, hostname, platform, user_label, workspace_home, tailscale_dns, tailscale_ips_json, ssh_target, last_seen_at, capabilities_json, @@ -870,15 +871,15 @@ ${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config, capabilities_json = excluded.capabilities_json, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `).run(_.machine_id,_.hostname,_.platform,_.user_label,_.workspace_home,_.tailscale_dns,_.tailscale_ips_json,_.ssh_target,_.last_seen_at,_.capabilities_json,_.metadata_json,_.created_at,_.updated_at)}function yh($,_,J=D4()){for(let U of _.machines)$R($,wh(U,J));return _.machines.length}function Wq($){a($);let _=m($);try{return _.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{_.close()}}function fU($){a($.dbPath);let _=m($.dbPath),J=[],U=D4($.now),W=nV($.machineId),X=$.recordClocks!==!1;try{let G=cV(_,iV($.tables)),Q=_.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json + `).run($.machine_id,$.hostname,$.platform,$.user_label,$.workspace_home,$.tailscale_dns,$.tailscale_ips_json,$.ssh_target,$.last_seen_at,$.capabilities_json,$.metadata_json,$.created_at,$.updated_at)}function MB(_,$,g=u$()){for(let U of $.machines)LX(_,XB(U,g));return $.machines.length}function vE(_){h(_);let $=v(_);try{return $.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{$.close()}}function ig(_){h(_.dbPath);let $=v(_.dbPath),g=[],U=u$(_.now),D=_X(_.machineId),I=_.recordClocks!==!1;try{let j=$X($,gX(_.tables)),O=$.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all().map((H)=>{let V=Fh(H,$.storage.local_layout.directories.artifacts),K={...H,key:V};if($.includeArtifactContent!==!1&&V&&H.artifact_uri.startsWith("file://"))try{let E=uV(H.artifact_uri);if(_h(E))if(!Mh(H.content_type,V))J.push(`artifact_content_not_embedded_binary:${H.id}`);else{let F=Jh(E,"utf8"),w=j_(F);if(w!==F)J.push(`artifact_content_redacted:${H.id}`);K.content_base64=Buffer.from(w,"utf8").toString("base64"),K.hash=bU(w),K.size_bytes=Buffer.byteLength(w)}else J.push(`artifact_missing:${H.artifact_uri}`)}catch(E){J.push(`artifact_read_failed:${H.artifact_uri}:${E instanceof Error?E.message:String(E)}`)}else if($.includeArtifactContent!==!1&&H.artifact_uri.startsWith("s3://"))J.push(`artifact_content_not_embedded:${H.artifact_uri}`);return K=j_(K),K}),q=P1(Q),L=G.filter((H)=>!IU.has(H)).map((H)=>({table:H,primary_keys:kU[H],rows:lV(_,H).map((V)=>j_(V))})),N=L.map((H)=>jh(_,{table:H.table,machineId:W,highWaterHash:Y8(H.table,H.rows,q),rowCount:H.rows.length,record:X,now:U})),R=bU(dJ({source:{scope:$.scope,workspace_home:j_($.workspaceHome),sqlite_schema_version:b_(_),machine_id:W,artifact_root_uri:j_($.storage.artifact_store.uri_prefix)},tables:L.map((H)=>({table:H.table,primary_keys:H.primary_keys,rows:H.rows.map((V)=>({key:C1(H.table,V),hash:f1(V,q)})).sort((V,K)=>V.key.localeCompare(K.key))})),table_clocks:N.map((H)=>({table:H.table,machine_id:H.machine_id,logical_clock:H.logical_clock,high_water_hash:H.high_water_hash,row_count:H.row_count})),artifacts:Q.map((H)=>({identity:z8(H),fingerprint:A0(H)})).sort((H,V)=>H.identity.localeCompare(V.identity))})),B=`syncbundle_${R.replace("sha256:","").slice(0,32)}`;for(let H of N)Dh(_,H,B,X,U);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:w0,min_protocol_version:g0,bundle_id:B,content_hash:R,generated_at:U,source:{scope:$.scope,workspace_home:j_($.workspaceHome),sqlite_schema_version:b_(_),machine_id:W,artifact_root_uri:j_($.storage.artifact_store.uri_prefix)},table_clocks:N,tables:L,artifacts:Q,warnings:j_(J),message:`${L.reduce((H,V)=>H+V.rows.length,0)} row(s), ${Q.length} artifact(s) exported`}}finally{_.close()}}function hh($,_){let J=typeof $.protocol_version==="number"?$.protocol_version:null,U=typeof $.min_protocol_version==="number"?$.min_protocol_version:null;if(J===null||U===null||Jw0)throw Error(`Unsupported ${_} protocol. Expected knowledge sync protocol v${w0} with min v${g0}.`)}function mh($){if(!$||$.format!=="knowledge-sync-bundle"||$.version!==1)throw Error("Invalid knowledge sync bundle.");hh($,"knowledge sync bundle")}function Uq($,_){return $.tables.find((J)=>J.table===_)??null}function _R($){if(typeof $.content_hash==="string"&&$.content_hash.length>0)return $.content_hash;return bU(dJ({source:$.source,tables:$.tables.map((_)=>({table:_.table,rows:_.rows.map((J)=>({key:C1(_.table,J),hash:f1(J,P1($.artifacts))})).sort((J,U)=>J.key.localeCompare(U.key))})),artifacts:$.artifacts.map((_)=>({identity:z8(_),fingerprint:A0(_)})).sort((_,J)=>_.identity.localeCompare(J.identity))}))}function xh($){if(typeof $.bundle_id==="string"&&$.bundle_id.length>0)return $.bundle_id;return`syncbundle_${_R($).replace("sha256:","").slice(0,32)}`}function uh($,_){return new Map(_.map((J)=>[C1($,J),J]))}function dh($){return new Map($.artifacts.map((_)=>[z8(_),_]))}async function nh($){let _=dh($.targetBundle),J=new Map,U=[],W={source_artifacts:$.bundle.artifacts.length,target_artifacts:$.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let X of $.bundle.artifacts){let G=z8(X),Y=_.get(G);if(Y&&A0(Y)===A0(X)){if(Y.artifact_uri)J.set(X.artifact_uri,Y.artifact_uri);W.skipped+=1;continue}if(Y&&A0(Y)!==A0(X)){let H={entityKind:"storage_object",entityId:G,localMachineId:$.localMachineId,remoteMachineId:$.bundle.source.machine_id??"unknown",localHash:A0(Y),remoteHash:A0(X),metadata:{direction:$.direction,target_artifact_uri:Y.artifact_uri,source_artifact_uri:X.artifact_uri,local_artifact:wU(Y),remote_artifact:wU(X)}};if(eQ($.db,H)){W.skipped+=1;continue}W.conflicts+=1,U.push(H);continue}let Q=Boolean(X.key&&X.content_base64),q=Ah(X,$.targetStorage);if(!Q&&!q){W.missing_content+=1,$.warnings.push(`artifact_content_missing:${X.artifact_uri}`);continue}if($.dryRun){W.copied+=1;continue}let L=X.artifact_uri;if(Q&&X.key&&X.content_base64)L=(await $.targetStore.put({key:X.key,body:Buffer.from(X.content_base64,"base64"),content_type:X.content_type??void 0})).uri,J.set(X.artifact_uri,L);else if(q)J.set(X.artifact_uri,L);let N=Q8(X.metadata_json,{}),R=typeof N.artifact_modified_at==="string"?N.artifact_modified_at:void 0,B={uri:L,key:X.key??N.key??X.artifact_uri,kind:X.kind,content_type:X.content_type??void 0,hash:X.hash??void 0,size_bytes:X.size_bytes??void 0,modified_at:R,metadata:{...N,synced_from_artifact_uri:X.artifact_uri,synced_from_machine_id:$.bundle.source.machine_id??void 0}};u4($.db,[B]),W.copied+=1}return{result:W,uriMap:J,conflicts:U}}function aQ($,_){let J={...$};if(typeof J.artifact_uri==="string"&&_.has(J.artifact_uri))J.artifact_uri=_.get(J.artifact_uri);return J}function ch($,_){let J=D4();$.query(` + ORDER BY artifact_uri ASC`).all().map((P)=>{let S=JB(P,_.storage.local_layout.directories.artifacts),X={...P,key:S};if(_.includeArtifactContent!==!1&&S&&P.artifact_uri.startsWith("file://"))try{let G=aW(P.artifact_uri);if(iq(G))if(!zB(P.content_type,S))g.push(`artifact_content_not_embedded_binary:${P.id}`);else{let R=lq(G,"utf8"),K=q_(R);if(K!==R)g.push(`artifact_content_redacted:${P.id}`);X.content_base64=Buffer.from(K,"utf8").toString("base64"),X.hash=hg(K),X.size_bytes=Buffer.byteLength(K)}else g.push(`artifact_missing:${P.artifact_uri}`)}catch(G){g.push(`artifact_read_failed:${P.artifact_uri}:${G instanceof Error?G.message:String(G)}`)}else if(_.includeArtifactContent!==!1&&P.artifact_uri.startsWith("s3://"))g.push(`artifact_content_not_embedded:${P.artifact_uri}`);return X=q_(X),X}),A=O4(O),L=j.filter((P)=>!mg.has(P)).map((P)=>({table:P,primary_keys:dg[P],rows:DX($,P).map((S)=>q_(S))})),z=L.map((P)=>gB($,{table:P.table,machineId:D,highWaterHash:LI(P.table,P.rows,A),rowCount:P.rows.length,record:I,now:U})),W=hg(B0({source:{scope:_.scope,workspace_home:q_(_.workspaceHome),sqlite_schema_version:v_($),machine_id:D,artifact_root_uri:q_(_.storage.artifact_store.uri_prefix)},tables:L.map((P)=>({table:P.table,primary_keys:P.primary_keys,rows:P.rows.map((S)=>({key:E4(P.table,S),hash:N4(S,A)})).sort((S,X)=>S.key.localeCompare(X.key))})),table_clocks:z.map((P)=>({table:P.table,machine_id:P.machine_id,logical_clock:P.logical_clock,high_water_hash:P.high_water_hash,row_count:P.row_count})),artifacts:O.map((P)=>({identity:zI(P),fingerprint:B6(P)})).sort((P,S)=>P.identity.localeCompare(S.identity))})),J=`syncbundle_${W.replace("sha256:","").slice(0,32)}`;for(let P of z)DB($,P,J,I,U);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:V6,min_protocol_version:F6,bundle_id:J,content_hash:W,generated_at:U,source:{scope:_.scope,workspace_home:q_(_.workspaceHome),sqlite_schema_version:v_($),machine_id:D,artifact_root_uri:q_(_.storage.artifact_store.uri_prefix)},table_clocks:z,tables:L,artifacts:O,warnings:q_(g),message:`${L.reduce((P,S)=>P+S.rows.length,0)} row(s), ${O.length} artifact(s) exported`}}finally{$.close()}}function ZB(_,$){let g=typeof _.protocol_version==="number"?_.protocol_version:null,U=typeof _.min_protocol_version==="number"?_.min_protocol_version:null;if(g===null||U===null||gV6)throw Error(`Unsupported ${$} protocol. Expected knowledge sync protocol v${V6} with min v${F6}.`)}function bB(_){if(!_||_.format!=="knowledge-sync-bundle"||_.version!==1)throw Error("Invalid knowledge sync bundle.");ZB(_,"knowledge sync bundle")}function fE(_,$){return _.tables.find((g)=>g.table===$)??null}function JX(_){if(typeof _.content_hash==="string"&&_.content_hash.length>0)return _.content_hash;return hg(B0({source:_.source,tables:_.tables.map(($)=>({table:$.table,rows:$.rows.map((g)=>({key:E4($.table,g),hash:N4(g,O4(_.artifacts))})).sort((g,U)=>g.key.localeCompare(U.key))})),artifacts:_.artifacts.map(($)=>({identity:zI($),fingerprint:B6($)})).sort(($,g)=>$.identity.localeCompare(g.identity))}))}function HB(_){if(typeof _.bundle_id==="string"&&_.bundle_id.length>0)return _.bundle_id;return`syncbundle_${JX(_).replace("sha256:","").slice(0,32)}`}function kB(_,$){return new Map($.map((g)=>[E4(_,g),g]))}function CB(_){return new Map(_.artifacts.map(($)=>[zI($),$]))}async function rB(_){let $=CB(_.targetBundle),g=new Map,U=[],D={source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let I of _.bundle.artifacts){let j=zI(I),N=$.get(j);if(N&&B6(N)===B6(I)){if(N.artifact_uri)g.set(I.artifact_uri,N.artifact_uri);D.skipped+=1;continue}if(N&&B6(N)!==B6(I)){let P={entityKind:"storage_object",entityId:j,localMachineId:_.localMachineId,remoteMachineId:_.bundle.source.machine_id??"unknown",localHash:B6(N),remoteHash:B6(I),metadata:{direction:_.direction,target_artifact_uri:N.artifact_uri,source_artifact_uri:I.artifact_uri,local_artifact:cg(N),remote_artifact:cg(I)}};if(HE(_.db,P)){D.skipped+=1;continue}D.conflicts+=1,U.push(P);continue}let O=Boolean(I.key&&I.content_base64),A=SB(I,_.targetStorage);if(!O&&!A){D.missing_content+=1,_.warnings.push(`artifact_content_missing:${I.artifact_uri}`);continue}if(_.dryRun){D.copied+=1;continue}let L=I.artifact_uri;if(O&&I.key&&I.content_base64)L=(await _.targetStore.put({key:I.key,body:Buffer.from(I.content_base64,"base64"),content_type:I.content_type??void 0})).uri,g.set(I.artifact_uri,L);else if(A)g.set(I.artifact_uri,L);let z=JI(I.metadata_json,{}),W=typeof z.artifact_modified_at==="string"?z.artifact_modified_at:void 0,J={uri:L,key:I.key??z.key??I.artifact_uri,kind:I.kind,content_type:I.content_type??void 0,hash:I.hash??void 0,size_bytes:I.size_bytes??void 0,modified_at:W,metadata:{...z,synced_from_artifact_uri:I.artifact_uri,synced_from_machine_id:_.bundle.source.machine_id??void 0}};s$(_.db,[J]),D.copied+=1}return{result:D,uriMap:g,conflicts:U}}function ZE(_,$){let g={..._};if(typeof g.artifact_uri==="string"&&$.has(g.artifact_uri))g.artifact_uri=$.get(g.artifact_uri);return g}function vB(_,$){let g=u$();_.query(` INSERT INTO knowledge_sync_changes ( id, origin_machine_id, updated_by_machine_id, entity_kind, entity_id, operation, base_hash, next_hash, source_ref, source_revision_id, artifact_uri, logical_clock, bundle_id, metadata_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(_q("syncchg"),_.sourceMachineId,_.localMachineId,_.entityKind,_.entityId,_.direction,null,_.nextHash,typeof _.row?.source_ref==="string"?_.row.source_ref:typeof _.row?.source_uri==="string"?_.row.source_uri:null,typeof _.row?.source_revision_id==="string"?_.row.source_revision_id:null,typeof _.row?.artifact_uri==="string"?_.row.artifact_uri:null,_.logicalClock,_.bundleId,JSON.stringify({source_machine_id:_.sourceMachineId,bundle_id:_.bundleId}),J)}function eQ($,_){let J=_.localHash??"",U=_.remoteHash??"";if($.query(` + `).run(CE("syncchg"),$.sourceMachineId,$.localMachineId,$.entityKind,$.entityId,$.direction,null,$.nextHash,typeof $.row?.source_ref==="string"?$.row.source_ref:typeof $.row?.source_uri==="string"?$.row.source_uri:null,typeof $.row?.source_revision_id==="string"?$.row.source_revision_id:null,typeof $.row?.artifact_uri==="string"?$.row.artifact_uri:null,$.logicalClock,$.bundleId,JSON.stringify({source_machine_id:$.sourceMachineId,bundle_id:$.bundleId}),g)}function HE(_,$){let g=$.localHash??"",U=$.remoteHash??"";if(_.query(` SELECT id FROM knowledge_sync_conflicts WHERE entity_kind = ? AND entity_id = ? @@ -889,7 +890,7 @@ ${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config, AND status IN ('resolved', 'ignored') AND resolved_at IS NOT NULL LIMIT 1 - `).get(_.entityKind,_.entityId,_.localMachineId,_.remoteMachineId,J,U))return!0;let X=$.query(` + `).get($.entityKind,$.entityId,$.localMachineId,$.remoteMachineId,g,U))return!0;let I=_.query(` SELECT id FROM knowledge_sync_conflicts WHERE entity_kind = ? AND entity_id = ? @@ -900,7 +901,7 @@ ${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config, AND status IN ('resolved', 'ignored') AND resolved_at IS NOT NULL LIMIT 1 - `).get(_.entityKind,_.entityId,_.remoteMachineId,_.localMachineId,U,J);return Boolean(X)}function sQ($,_){if($.query(` + `).get($.entityKind,$.entityId,$.remoteMachineId,$.localMachineId,U,g);return Boolean(I)}function bE(_,$){if(_.query(` SELECT id FROM knowledge_sync_conflicts WHERE entity_kind = ? AND entity_id = ? @@ -911,13 +912,13 @@ ${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config, AND COALESCE(base_hash, '') = COALESCE(?, '') AND status = 'open' LIMIT 1 - `).get(_.entityKind,_.entityId,_.localMachineId,_.remoteMachineId,_.localHash??null,_.remoteHash??null,_.baseHash??null))return!1;let U=D4();return $.query(` + `).get($.entityKind,$.entityId,$.localMachineId,$.remoteMachineId,$.localHash??null,$.remoteHash??null,$.baseHash??null))return!1;let U=u$();return _.query(` INSERT INTO knowledge_sync_conflicts ( id, entity_kind, entity_id, local_machine_id, remote_machine_id, local_hash, remote_hash, base_hash, status, resolution_strategy, proposed_patch_uri, approved_by, resolved_at, metadata_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(_q("syncconf"),_.entityKind,_.entityId,_.localMachineId,_.remoteMachineId,_.localHash??null,_.remoteHash??null,_.baseHash??null,_.status??"open",_.resolutionStrategy??null,_.proposedPatchUri??null,_.approvedBy??null,_.resolvedAt??null,JSON.stringify(_.metadata??{}),U),!0}function ih($,_){return $.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get(_)??null}function lh($,_){let J=_.now??D4();$.query(` + `).run(CE("syncconf"),$.entityKind,$.entityId,$.localMachineId,$.remoteMachineId,$.localHash??null,$.remoteHash??null,$.baseHash??null,$.status??"open",$.resolutionStrategy??null,$.proposedPatchUri??null,$.approvedBy??null,$.resolvedAt??null,JSON.stringify($.metadata??{}),U),!0}function fB(_,$){return _.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get($)??null}function wB(_,$){let g=$.now??u$();_.query(` INSERT INTO knowledge_sync_imports ( bundle_id, source_machine_id, target_machine_id, direction, status, content_hash, table_clocks_json, tables_json, generated_at, applied_at, @@ -927,13 +928,13 @@ ${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config, status = excluded.status, applied_at = excluded.applied_at, metadata_json = excluded.metadata_json - `).run(_.bundleId,_.sourceMachineId,_.targetMachineId,_.direction,_.status,_.contentHash,JSON.stringify(_.bundle.table_clocks??[]),JSON.stringify(_.tableResults),_.bundle.generated_at,J,JSON.stringify({conflicts:_.conflicts,artifacts:_.artifacts,source_workspace_home:_.bundle.source.workspace_home}))}function rh($){return{ok:!0,protocol_version:w0,min_protocol_version:g0,dry_run:!1,direction:$.direction,source:$.bundle.source,target:{scope:$.targetScope,workspace_home:$.targetWorkspaceHome,sqlite_schema_version:$.targetBundle.source.sqlite_schema_version,artifact_root_uri:$.targetStorage.artifact_store.uri_prefix},tables:$.bundle.tables.filter((_)=>!IU.has(_.table)).map((_)=>({table:_.table,source_rows:_.rows.length,target_rows:Uq($.targetBundle,_.table)?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:_.rows.length,conflicts:0,stale_skipped:0})),artifacts:{source_artifacts:$.bundle.artifacts.length,target_artifacts:$.targetBundle.artifacts.length,copied:0,skipped:$.bundle.artifacts.length,conflicts:0,missing_content:0},conflicts_created:0,bundle_id:$.bundleId,replayed:!0,clocks:{advanced:0,stale_tables:0},warnings:[...$.warnings,`bundle_replay_skipped:${$.bundleId}`],message:`Skipped already-applied bundle ${$.bundleId}`}}function ph($,_){let J=P1($.artifacts),U=P1(_.artifacts);for(let W of $.tables){if(IU.has(W.table))continue;let X=Uq(_,W.table),Y=rV($,W.table)?.high_water_hash??Y8(W.table,W.rows,J);if(Y8(W.table,X?.rows??[],U)!==Y)return!1}return!0}async function j8($){mh($.bundle),a($.targetDbPath);let _=[...$.bundle.warnings],J=$.dryRun===!0,U=nV($.localMachineId),W=$.bundle.source.machine_id??"unknown",X=xh($.bundle),G=_R($.bundle),Y=$.targetBundle??fU({dbPath:$.targetDbPath,scope:$.targetScope,workspaceHome:$.targetWorkspaceHome,storage:$.targetStorage,machineId:U,includeArtifactContent:!1,recordClocks:!J}),Q=m($.targetDbPath);try{if(!J&&ih(Q,X)&&ph($.bundle,Y))return rh({bundle:$.bundle,targetBundle:Y,targetScope:$.targetScope,targetWorkspaceHome:$.targetWorkspaceHome,targetStorage:$.targetStorage,direction:$.direction,warnings:_,bundleId:X});let q=await nh({db:Q,bundle:$.bundle,targetBundle:Y,targetStorage:$.targetStorage,targetStore:$.targetStore,dryRun:J,direction:$.direction,localMachineId:U,warnings:_}),L=P1($.bundle.artifacts),N=P1(Y.artifacts),R=[],B=0,H=0,V=0;for(let F of $.bundle.tables){if(F.table==="storage_objects"||IU.has(F.table))continue;if(!N6(Q,F.table))continue;let w=rV($.bundle,F.table),A=gU(Q,F.table,W),g=Uq(Y,F.table),v=uh(F.table,g?.rows??[]),k=new Set(F.rows.map((z_)=>C1(F.table,z_))),u=Bh(Q,F.table,W),W_=[],c$={table:F.table,source_rows:F.rows.length,target_rows:g?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!w)_.push(`legacy_clock_missing:${F.table}`);else if(Oh(A,w)){V+=1,c$.skipped+=F.rows.length,c$.stale_skipped=F.rows.length,_.push(`stale_table_skipped:${F.table}:${W}:${w.logical_clock}`),R.push(c$);continue}for(let z_ of F.rows){let K_=C1(F.table,z_),E$=v.get(K_),A_=f1(z_,L);if(!E$){c$.inserted+=1,W_.push(aQ(z_,q.uriMap));continue}let D_=f1(E$,N);if(D_===A_){c$.skipped+=1;continue}let U_=u.get(K_);if(u.has(K_)&&U_===D_){c$.updated+=1,W_.push(aQ(z_,q.uriMap));continue}let F_={entityKind:F.table,entityId:K_,localMachineId:U,remoteMachineId:W,localHash:D_,remoteHash:A_,baseHash:A?.high_water_hash??null,metadata:{direction:$.direction,bundle_id:X,incoming_logical_clock:w?.logical_clock??null,current_logical_clock:A?.logical_clock??null,source_workspace_home:$.bundle.source.workspace_home,target_workspace_home:$.targetWorkspaceHome,local_row:AU(E$),remote_row:AU(z_)}};if(eQ(Q,F_)){c$.skipped+=1;continue}if(c$.conflicts+=1,!J&&sQ(Q,F_))B+=1}if(!J&&W_.length>0){let z_=W_.map((K_)=>aQ(K_,q.uriMap));Lh(Q,F.table,z_),Rh(Q,F.table,z_);for(let K_ of z_)ch(Q,{direction:$.direction,sourceMachineId:$.bundle.source.machine_id??"unknown",localMachineId:U,entityKind:F.table,entityId:C1(F.table,K_),nextHash:f1(K_,P1($.bundle.artifacts)),logicalClock:w?.logical_clock??0,bundleId:X,row:K_})}for(let[z_,K_]of u){if(k.has(z_))continue;let E$=v.get(z_);if(!E$)continue;let A_=f1(E$,N);if(K_&&A_!==K_){let D_={entityKind:F.table,entityId:z_,localMachineId:U,remoteMachineId:W,localHash:A_,remoteHash:null,baseHash:K_,metadata:{direction:$.direction,bundle_id:X,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:$.bundle.source.workspace_home,target_workspace_home:$.targetWorkspaceHome,local_row:AU(E$),remote_row:null}};if(eQ(Q,D_)){c$.skipped+=1;continue}if(c$.conflicts+=1,!J&&sQ(Q,D_))B+=1;continue}if(c$.deleted+=1,!J)Nh(Q,F.table,z_)}if(!J&&w)q8(Q,{table:F.table,machineId:W,logicalClock:w.logical_clock,highWaterHash:w.high_water_hash,highWaterBundleId:X,originMachineId:W,updatedByMachineId:U,lastAppliedAt:D4(),metadata:{source:"import",direction:$.direction,row_count:F.rows.length,inserted:c$.inserted,updated:c$.updated,deleted:c$.deleted,skipped:c$.skipped,conflicts:c$.conflicts}}),H+=1;R.push(c$)}for(let F of q.conflicts)if(!J){if(sQ(Q,{...F,baseHash:F.baseHash??null,metadata:{...F.metadata,bundle_id:X}}))B+=1}let K=R.reduce((F,w)=>F+w.inserted,0),E=R.reduce((F,w)=>F+w.conflicts,0)+q.result.conflicts;if(!J)lh(Q,{bundle:$.bundle,bundleId:X,contentHash:G,sourceMachineId:W,targetMachineId:U,direction:$.direction,status:E===0?"applied":"conflicted",tableResults:R,conflicts:E,artifacts:q.result});return{ok:E===0,protocol_version:w0,min_protocol_version:g0,dry_run:J,direction:$.direction,source:$.bundle.source,target:{scope:$.targetScope,workspace_home:$.targetWorkspaceHome,sqlite_schema_version:b_(Q),artifact_root_uri:$.targetStorage.artifact_store.uri_prefix},tables:R,artifacts:q.result,conflicts_created:B,bundle_id:X,replayed:!1,clocks:{advanced:H,stale_tables:V},warnings:_,message:`${$.dryRun?"Would import":"Imported"} ${K} row(s), copied ${q.result.copied} artifact(s), ${E} conflict(s)`}}finally{Q.close()}}function JR($){a($.dbPath);let _=m($.dbPath),J=D4($.now);try{let U=$.topology?yh(_,$.topology,J):0,W=tV(_),X=j_(bh(_)),G=$.machineId??$.topology?.local_machine_id??"unknown",Y=j_($.storage.artifact_store.uri_prefix),Q=j_($.workspaceHome),q=bU(dJ({machine_id:G,scope:$.scope,workspace_home:Q,sqlite_schema_version:b_(_),artifact_root_uri:Y,tables:W,artifacts:X})),L={id:_q("syncsnap"),machine_id:G,scope:$.scope,workspace_home:Q,sqlite_schema_version:b_(_),artifact_root_uri:Y,content_hash:q,tables_json:JSON.stringify(W),artifact_hashes_json:JSON.stringify(X),created_at:J};_.query(` + `).run($.bundleId,$.sourceMachineId,$.targetMachineId,$.direction,$.status,$.contentHash,JSON.stringify($.bundle.table_clocks??[]),JSON.stringify($.tableResults),$.bundle.generated_at,g,JSON.stringify({conflicts:$.conflicts,artifacts:$.artifacts,source_workspace_home:$.bundle.source.workspace_home}))}function uB(_){return{ok:!0,protocol_version:V6,min_protocol_version:F6,dry_run:!1,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:_.targetBundle.source.sqlite_schema_version,artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:_.bundle.tables.filter(($)=>!mg.has($.table)).map(($)=>({table:$.table,source_rows:$.rows.length,target_rows:fE(_.targetBundle,$.table)?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:$.rows.length,conflicts:0,stale_skipped:0})),artifacts:{source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:_.bundle.artifacts.length,conflicts:0,missing_content:0},conflicts_created:0,bundle_id:_.bundleId,replayed:!0,clocks:{advanced:0,stale_tables:0},warnings:[..._.warnings,`bundle_replay_skipped:${_.bundleId}`],message:`Skipped already-applied bundle ${_.bundleId}`}}function xB(_,$){let g=O4(_.artifacts),U=O4($.artifacts);for(let D of _.tables){if(mg.has(D.table))continue;let I=fE($,D.table),N=UX(_,D.table)?.high_water_hash??LI(D.table,D.rows,g);if(LI(D.table,I?.rows??[],U)!==N)return!1}return!0}async function SI(_){bB(_.bundle),h(_.targetDbPath);let $=[..._.bundle.warnings],g=_.dryRun===!0,U=_X(_.localMachineId),D=_.bundle.source.machine_id??"unknown",I=HB(_.bundle),j=JX(_.bundle),N=_.targetBundle??ig({dbPath:_.targetDbPath,scope:_.targetScope,workspaceHome:_.targetWorkspaceHome,storage:_.targetStorage,machineId:U,includeArtifactContent:!1,recordClocks:!g}),O=v(_.targetDbPath);try{if(!g&&fB(O,I)&&xB(_.bundle,N))return uB({bundle:_.bundle,targetBundle:N,targetScope:_.targetScope,targetWorkspaceHome:_.targetWorkspaceHome,targetStorage:_.targetStorage,direction:_.direction,warnings:$,bundleId:I});let A=await rB({db:O,bundle:_.bundle,targetBundle:N,targetStorage:_.targetStorage,targetStore:_.targetStore,dryRun:g,direction:_.direction,localMachineId:U,warnings:$}),L=O4(_.bundle.artifacts),z=O4(N.artifacts),W=[],J=0,P=0,S=0;for(let R of _.bundle.tables){if(R.table==="storage_objects"||mg.has(R.table))continue;if(!J$(O,R.table))continue;let K=UX(_.bundle,R.table),Q=ng(O,R.table,D),T=fE(N,R.table),q=kB(R.table,T?.rows??[]),V=new Set(R.rows.map((I_)=>E4(R.table,I_))),Z=jB(O,R.table,D),a=[],D_={table:R.table,source_rows:R.rows.length,target_rows:T?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!K)$.push(`legacy_clock_missing:${R.table}`);else if(UB(Q,K)){S+=1,D_.skipped+=R.rows.length,D_.stale_skipped=R.rows.length,$.push(`stale_table_skipped:${R.table}:${D}:${K.logical_clock}`),W.push(D_);continue}for(let I_ of R.rows){let J_=E4(R.table,I_),p=q.get(J_),r_=N4(I_,L);if(!p){D_.inserted+=1,a.push(ZE(I_,A.uriMap));continue}let K_=N4(p,z);if(K_===r_){D_.skipped+=1;continue}let G_=Z.get(J_);if(Z.has(J_)&&G_===K_){D_.updated+=1,a.push(ZE(I_,A.uriMap));continue}let H_={entityKind:R.table,entityId:J_,localMachineId:U,remoteMachineId:D,localHash:K_,remoteHash:r_,baseHash:Q?.high_water_hash??null,metadata:{direction:_.direction,bundle_id:I,incoming_logical_clock:K?.logical_clock??null,current_logical_clock:Q?.logical_clock??null,source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:yg(p),remote_row:yg(I_)}};if(HE(O,H_)){D_.skipped+=1;continue}if(D_.conflicts+=1,!g&&bE(O,H_))J+=1}if(!g&&a.length>0){let I_=a.map((J_)=>ZE(J_,A.uriMap));IB(O,R.table,I_),AB(O,R.table,I_);for(let J_ of I_)vB(O,{direction:_.direction,sourceMachineId:_.bundle.source.machine_id??"unknown",localMachineId:U,entityKind:R.table,entityId:E4(R.table,J_),nextHash:N4(J_,O4(_.bundle.artifacts)),logicalClock:K?.logical_clock??0,bundleId:I,row:J_})}for(let[I_,J_]of Z){if(V.has(I_))continue;let p=q.get(I_);if(!p)continue;let r_=N4(p,z);if(J_&&r_!==J_){let K_={entityKind:R.table,entityId:I_,localMachineId:U,remoteMachineId:D,localHash:r_,remoteHash:null,baseHash:J_,metadata:{direction:_.direction,bundle_id:I,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:yg(p),remote_row:null}};if(HE(O,K_)){D_.skipped+=1;continue}if(D_.conflicts+=1,!g&&bE(O,K_))J+=1;continue}if(D_.deleted+=1,!g)EB(O,R.table,I_)}if(!g&&K)PI(O,{table:R.table,machineId:D,logicalClock:K.logical_clock,highWaterHash:K.high_water_hash,highWaterBundleId:I,originMachineId:D,updatedByMachineId:U,lastAppliedAt:u$(),metadata:{source:"import",direction:_.direction,row_count:R.rows.length,inserted:D_.inserted,updated:D_.updated,deleted:D_.deleted,skipped:D_.skipped,conflicts:D_.conflicts}}),P+=1;W.push(D_)}for(let R of A.conflicts)if(!g){if(bE(O,{...R,baseHash:R.baseHash??null,metadata:{...R.metadata,bundle_id:I}}))J+=1}let X=W.reduce((R,K)=>R+K.inserted,0),G=W.reduce((R,K)=>R+K.conflicts,0)+A.result.conflicts;if(!g)wB(O,{bundle:_.bundle,bundleId:I,contentHash:j,sourceMachineId:D,targetMachineId:U,direction:_.direction,status:G===0?"applied":"conflicted",tableResults:W,conflicts:G,artifacts:A.result});return{ok:G===0,protocol_version:V6,min_protocol_version:F6,dry_run:g,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:v_(O),artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:W,artifacts:A.result,conflicts_created:J,bundle_id:I,replayed:!1,clocks:{advanced:P,stale_tables:S},warnings:$,message:`${_.dryRun?"Would import":"Imported"} ${X} row(s), copied ${A.result.copied} artifact(s), ${G} conflict(s)`}}finally{O.close()}}function PX(_){h(_.dbPath);let $=v(_.dbPath),g=u$(_.now);try{let U=_.topology?MB($,_.topology,g):0,D=NX($),I=q_(WB($)),j=_.machineId??_.topology?.local_machine_id??"unknown",N=q_(_.storage.artifact_store.uri_prefix),O=q_(_.workspaceHome),A=hg(B0({machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:v_($),artifact_root_uri:N,tables:D,artifacts:I})),L={id:CE("syncsnap"),machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:v_($),artifact_root_uri:N,content_hash:A,tables_json:JSON.stringify(D),artifact_hashes_json:JSON.stringify(I),created_at:g};$.query(` INSERT INTO knowledge_sync_snapshots ( id, machine_id, scope, workspace_home, sqlite_schema_version, artifact_root_uri, content_hash, tables_json, artifact_hashes_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(L.id,L.machine_id,L.scope,L.workspace_home,L.sqlite_schema_version,L.artifact_root_uri,L.content_hash,L.tables_json,L.artifact_hashes_json,L.created_at);let N=new Map;for(let R of cV(_,iV()).filter((B)=>!IU.has(B))){let B=lV(_,R).map((E)=>j_(E)),H=Y8(R,B,N),V=gU(_,R,G),K=V?.high_water_hash===H?V.logical_clock:(V?.logical_clock??0)+1;q8(_,{table:R,machineId:G,logicalClock:K,highWaterHash:H,highWaterBundleId:L.id,originMachineId:V?.origin_machine_id??G,updatedByMachineId:G,lastAppliedAt:J,metadata:{source:"snapshot",row_count:B.length},now:J})}return{ok:!0,snapshot:{...L,tables:W,artifact_hashes:X},machines_upserted:U,message:`Recorded sync snapshot ${L.id}`}}finally{_.close()}}function WR($){a($.dbPath);let _=m($.dbPath);try{let J=_.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(),U=_.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get()??null,W=_.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(),X=_.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(),G=zh(_),Y=_.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get()??null,Q=W.reduce((L,N)=>L+N.count,0),q=W.filter((L)=>L.status!=="resolved"&&L.status!=="ignored").reduce((L,N)=>L+N.count,0);return{ok:!0,scope:$.scope,workspace_home:j_($.workspaceHome),sqlite_schema_version:b_(_),local_machine_id:$.localMachineId??null,machines:{total:J.length,rows:j_(J)},snapshots:{total:U8(_,"knowledge_sync_snapshots"),latest:j_(U)},changes:{total:U8(_,"knowledge_sync_changes"),by_operation:X},clocks:{total:G.length,rows:G},imports:{total:U8(_,"knowledge_sync_imports"),latest:j_(Y)},conflicts:{total:Q,by_status:W,open:q},table_counts:tV(_),message:`${J.length} machine(s), ${q} open sync conflict(s)`}}finally{_.close()}}function Xq($){return{...$,metadata:Q8($.metadata_json,{})}}function D8($,_){a($);let J=m($);try{let U=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_);return U?Xq(U):null}finally{J.close()}}function UR($,_={}){a($);let J=m($),U=Math.max(1,Math.min(_.limit??50,200));try{return(_.status?J.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all(_.status,U):J.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(U)).map(Xq)}finally{J.close()}}function oh($){return G8.includes($)?$:null}function th($,_){let J=oh(_.entity_kind);if(!J||!N6($,J))return null;let U=pV(J,_.entity_id);if(!U)return null;let W=oV(J);return $.query(`SELECT * FROM ${Y6(J)} WHERE ${W} LIMIT 1`).get(...U)}function ah($,_){for(let J of _){let U=$[J];if(U&&typeof U==="object"&&!Array.isArray(U))return AU(U)}return null}function mV($,_){if(typeof _!=="string")return;let J=_.trim();if(!J)return;if(J.startsWith("open-files://")||J.startsWith("s3://")||J.startsWith("file://")||J.startsWith("https://")||J.startsWith("http://"))$.add(J)}function $q($,_=new Set,J=0){if(J>8||$===null||$===void 0)return _;if(typeof $==="string")return mV(_,$),_;if(Array.isArray($)){for(let U of $)$q(U,_,J+1);return _}if(typeof $==="object")for(let[U,W]of Object.entries($)){if(U==="source_ref"||U==="source_uri"||U==="artifact_uri"||U.endsWith("_uri"))mV(_,W);$q(W,_,J+1)}return _}function XR($){let _=[{id:"conflict",kind:"metadata",ref:`knowledge-sync-conflict://${$.conflict.id}`,hash:$.conflict.base_hash,quote:`Conflict on ${$.conflict.entity_kind}:${$.conflict.entity_id}`}];if($.localRow)_.push({id:"local-row",kind:"row",ref:`${$.conflict.entity_kind}:${$.conflict.entity_id}:local`,hash:$.conflict.local_hash,quote:JSON.stringify($.localRow).slice(0,300)});if($.remoteRow)_.push({id:"remote-row",kind:"row",ref:`${$.conflict.entity_kind}:${$.conflict.entity_id}:remote`,hash:$.conflict.remote_hash,quote:JSON.stringify($.remoteRow).slice(0,300)});return $.sourceRefs.slice(0,10).forEach((J,U)=>{_.push({id:`source-${U+1}`,kind:J.startsWith("file://")||J.startsWith("s3://")?"artifact":"source_ref",ref:J,hash:null,quote:null})}),_}function GR($,_){let J=D8($,_);if(!J)throw Error(`Sync conflict not found: ${_}`);a($);let U=m($);try{let W=AU(th(U,J)),X=ah(J.metadata,["remote_row","source_row","incoming_row"]),Y=[...$q({conflict:{entity_kind:J.entity_kind,entity_id:J.entity_id,metadata:J.metadata},local_row:W,remote_row:X})].slice(0,25),Q=[{name:"knowledge_sync_conflict_get",input:{id:_},output_summary:`${J.entity_kind}:${J.entity_id} status=${J.status}`},{name:"knowledge_catalog_row_get",input:{table:J.entity_kind,key:J.entity_id},output_summary:W?"local row found":"local row unavailable"},{name:"knowledge_source_ref_extract",input:{id:_},output_summary:`${Y.length} source/artifact ref(s) found`}];return{conflict:J,local_row:W,remote_row:X,source_refs:Y,citations:XR({conflict:J,localRow:W,remoteRow:X,sourceRefs:Y}),read_only_tools:Q}}finally{U.close()}}function CU($,_){let J=D8($,_);if(!J)throw Error(`Sync conflict not found: ${_}`);let U=J.entity_kind==="wiki_pages"?"manual-merge":"review-and-select",W=[`Conflict ${J.id} affects ${J.entity_kind}:${J.entity_id}.`,`Local machine ${J.local_machine_id} has ${J.local_hash??"unknown hash"}.`,`Remote machine ${J.remote_machine_id} has ${J.remote_hash??"unknown hash"}.`].join(" "),X=["Review this knowledge sync conflict before any durable write.",`Entity: ${J.entity_kind}:${J.entity_id}`,`Local machine/hash: ${J.local_machine_id} / ${J.local_hash??"unknown"}`,`Remote machine/hash: ${J.remote_machine_id} / ${J.remote_hash??"unknown"}`,`Base hash: ${J.base_hash??"unknown"}`,`Metadata: ${JSON.stringify(J.metadata)}`,"Return a concise merge recommendation with citations to the competing records. Do not write changes without approval."].join(` -`);return{ok:!0,conflict:J,requires_approval:!0,mode:"deterministic",proposed_strategy:U,summary:W,merge_prompt:X,proposed_patch:null,citations:XR({conflict:J,localRow:null,remoteRow:null,sourceRefs:[]}),confidence:null,agent:null,warnings:J.status==="resolved"?["conflict_already_resolved"]:[],message:`Prepared approval-gated merge proposal for ${J.id}`}}function YR($,_){a($);let J=m($),U=D4();try{let W=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_.id);if(!W)throw Error(`Sync conflict not found: ${_.id}`);J.query(` + `).run(L.id,L.machine_id,L.scope,L.workspace_home,L.sqlite_schema_version,L.artifact_root_uri,L.content_hash,L.tables_json,L.artifact_hashes_json,L.created_at);let z=new Map;for(let W of $X($,gX()).filter((J)=>!mg.has(J))){let J=DX($,W).map((G)=>q_(G)),P=LI(W,J,z),S=ng($,W,j),X=S?.high_water_hash===P?S.logical_clock:(S?.logical_clock??0)+1;PI($,{table:W,machineId:j,logicalClock:X,highWaterHash:P,highWaterBundleId:L.id,originMachineId:S?.origin_machine_id??j,updatedByMachineId:j,lastAppliedAt:g,metadata:{source:"snapshot",row_count:J.length},now:g})}return{ok:!0,snapshot:{...L,tables:D,artifact_hashes:I},machines_upserted:U,message:`Recorded sync snapshot ${L.id}`}}finally{$.close()}}function zX(_){h(_.dbPath);let $=v(_.dbPath);try{let g=$.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(),U=$.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get()??null,D=$.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(),I=$.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(),j=$B($),N=$.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get()??null,O=D.reduce((L,z)=>L+z.count,0),A=D.filter((L)=>L.status!=="resolved"&&L.status!=="ignored").reduce((L,z)=>L+z.count,0);return{ok:!0,scope:_.scope,workspace_home:q_(_.workspaceHome),sqlite_schema_version:v_($),local_machine_id:_.localMachineId??null,machines:{total:g.length,rows:q_(g)},snapshots:{total:EI($,"knowledge_sync_snapshots"),latest:q_(U)},changes:{total:EI($,"knowledge_sync_changes"),by_operation:I},clocks:{total:j.length,rows:j},imports:{total:EI($,"knowledge_sync_imports"),latest:q_(N)},conflicts:{total:O,by_status:D,open:A},table_counts:NX($),message:`${g.length} machine(s), ${A} open sync conflict(s)`}}finally{$.close()}}function wE(_){return{..._,metadata:JI(_.metadata_json,{})}}function WI(_,$){h(_);let g=v(_);try{let U=g.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($);return U?wE(U):null}finally{g.close()}}function SX(_,$={}){h(_);let g=v(_),U=Math.max(1,Math.min($.limit??50,200));try{return($.status?g.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all($.status,U):g.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(U)).map(wE)}finally{g.close()}}function yB(_){return AI.includes(_)?_:null}function hB(_,$){let g=yB($.entity_kind);if(!g||!J$(_,g))return null;let U=IX(g,$.entity_id);if(!U)return null;let D=jX(g);return _.query(`SELECT * FROM ${j$(g)} WHERE ${D} LIMIT 1`).get(...U)}function cB(_,$){for(let g of $){let U=_[g];if(U&&typeof U==="object"&&!Array.isArray(U))return yg(U)}return null}function pW(_,$){if(typeof $!=="string")return;let g=$.trim();if(!g)return;if(g.startsWith("open-files://")||g.startsWith("s3://")||g.startsWith("file://")||g.startsWith("https://")||g.startsWith("http://"))_.add(g)}function kE(_,$=new Set,g=0){if(g>8||_===null||_===void 0)return $;if(typeof _==="string")return pW($,_),$;if(Array.isArray(_)){for(let U of _)kE(U,$,g+1);return $}if(typeof _==="object")for(let[U,D]of Object.entries(_)){if(U==="source_ref"||U==="source_uri"||U==="artifact_uri"||U.endsWith("_uri"))pW($,D);kE(D,$,g+1)}return $}function WX(_){let $=[{id:"conflict",kind:"metadata",ref:`knowledge-sync-conflict://${_.conflict.id}`,hash:_.conflict.base_hash,quote:`Conflict on ${_.conflict.entity_kind}:${_.conflict.entity_id}`}];if(_.localRow)$.push({id:"local-row",kind:"row",ref:`${_.conflict.entity_kind}:${_.conflict.entity_id}:local`,hash:_.conflict.local_hash,quote:JSON.stringify(_.localRow).slice(0,300)});if(_.remoteRow)$.push({id:"remote-row",kind:"row",ref:`${_.conflict.entity_kind}:${_.conflict.entity_id}:remote`,hash:_.conflict.remote_hash,quote:JSON.stringify(_.remoteRow).slice(0,300)});return _.sourceRefs.slice(0,10).forEach((g,U)=>{$.push({id:`source-${U+1}`,kind:g.startsWith("file://")||g.startsWith("s3://")?"artifact":"source_ref",ref:g,hash:null,quote:null})}),$}function XX(_,$){let g=WI(_,$);if(!g)throw Error(`Sync conflict not found: ${$}`);h(_);let U=v(_);try{let D=yg(hB(U,g)),I=cB(g.metadata,["remote_row","source_row","incoming_row"]),N=[...kE({conflict:{entity_kind:g.entity_kind,entity_id:g.entity_id,metadata:g.metadata},local_row:D,remote_row:I})].slice(0,25),O=[{name:"knowledge_sync_conflict_get",input:{id:$},output_summary:`${g.entity_kind}:${g.entity_id} status=${g.status}`},{name:"knowledge_catalog_row_get",input:{table:g.entity_kind,key:g.entity_id},output_summary:D?"local row found":"local row unavailable"},{name:"knowledge_source_ref_extract",input:{id:$},output_summary:`${N.length} source/artifact ref(s) found`}];return{conflict:g,local_row:D,remote_row:I,source_refs:N,citations:WX({conflict:g,localRow:D,remoteRow:I,sourceRefs:N}),read_only_tools:O}}finally{U.close()}}function lg(_,$){let g=WI(_,$);if(!g)throw Error(`Sync conflict not found: ${$}`);let U=g.entity_kind==="wiki_pages"?"manual-merge":"review-and-select",D=[`Conflict ${g.id} affects ${g.entity_kind}:${g.entity_id}.`,`Local machine ${g.local_machine_id} has ${g.local_hash??"unknown hash"}.`,`Remote machine ${g.remote_machine_id} has ${g.remote_hash??"unknown hash"}.`].join(" "),I=["Review this knowledge sync conflict before any durable write.",`Entity: ${g.entity_kind}:${g.entity_id}`,`Local machine/hash: ${g.local_machine_id} / ${g.local_hash??"unknown"}`,`Remote machine/hash: ${g.remote_machine_id} / ${g.remote_hash??"unknown"}`,`Base hash: ${g.base_hash??"unknown"}`,`Metadata: ${JSON.stringify(g.metadata)}`,"Return a concise merge recommendation with citations to the competing records. Do not write changes without approval."].join(` +`);return{ok:!0,conflict:g,requires_approval:!0,mode:"deterministic",proposed_strategy:U,summary:D,merge_prompt:I,proposed_patch:null,citations:WX({conflict:g,localRow:null,remoteRow:null,sourceRefs:[]}),confidence:null,agent:null,warnings:g.status==="resolved"?["conflict_already_resolved"]:[],message:`Prepared approval-gated merge proposal for ${g.id}`}}function RX(_,$){h(_);let g=v(_),U=u$();try{let D=g.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!D)throw Error(`Sync conflict not found: ${$.id}`);g.query(` UPDATE knowledge_sync_conflicts SET status = 'resolved', resolution_strategy = ?, @@ -941,27 +942,27 @@ ${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config, approved_by = ?, resolved_at = ? WHERE id = ? - `).run(_.strategy,_.proposedPatchUri??W.proposed_patch_uri,_.approvedBy,U,_.id);let X=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_.id);if(!X)throw Error(`Sync conflict not found after resolve: ${_.id}`);return Xq(X)}finally{J.close()}}function VL($){let J=(typeof $==="string"?$:JSON.stringify($)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(J*1.25))}function mu($){let _=m($.dbPath);try{_.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.runId,"sync-conflict-proposal",$.prompt,$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.now])}finally{_.close()}}function WF($){let _=m($.dbPath);try{_.run(`UPDATE runs + `).run($.strategy,$.proposedPatchUri??D.proposed_patch_uri,$.approvedBy,U,$.id);let I=g.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!I)throw Error(`Sync conflict not found after resolve: ${$.id}`);return wE(I)}finally{g.close()}}function pP(_){let g=(typeof _==="string"?_:JSON.stringify(_)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(g*1.25))}function bF(_){let $=v(_.dbPath);try{$.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[_.runId,"sync-conflict-proposal",_.prompt,_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.now])}finally{$.close()}}function zR(_){let $=v(_.dbPath);try{$.run(`UPDATE runs SET status = ?, provider = ?, model = ?, cost_tokens = ?, cost_usd = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`,[$.status,$.provider,$.model,$.usage.input_tokens+$.usage.output_tokens,$.usage.cost_usd,JSON.stringify($.metadata),$.now,$.runId])}finally{_.close()}}function RL($){let _=m($.dbPath);try{_.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`event_${UF()}`,$.runId,$.level,$.event,JSON.stringify($.metadata),$.now])}finally{_.close()}}function xu($,_,J,U){let W=m($);try{TJ(W,{...J,run_id:_,created_at:U})}finally{W.close()}}function uu($){return["Build an approval-gated merge proposal for this knowledge sync conflict.","Use only the supplied JSON evidence. Do not claim to inspect external files or write changes.","Return a patch recommendation that a human can review before approval.","",`Deterministic proposal: -${JSON.stringify({proposed_strategy:$.deterministic.proposed_strategy,summary:$.deterministic.summary,warnings:$.deterministic.warnings},null,2)}`,"",`Conflict evidence: -${JSON.stringify($.evidence,null,2)}`].join(` -`)}function du($){let _=typeof $==="number"&&Number.isFinite($)?$:0.5;return Math.max(0,Math.min(1,_))}function nu($,_){let J=$.kind==="choose_local"||$.kind==="choose_remote"||$.kind==="no_op"||$.kind==="custom"||$.kind==="manual_merge"?$.kind:"manual_merge";return{kind:J,target:typeof $.target==="string"&&$.target?$.target:_,strategy:typeof $.strategy==="string"&&$.strategy?$.strategy:J.replace("_","-"),summary:typeof $.summary==="string"&&$.summary?$.summary:"Review both sides before applying a merge.",diff:typeof $.diff==="string"&&$.diff?$.diff:null,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:{}}}function cu($){let _=`${$.conflict.entity_kind}:${$.conflict.entity_id}`,J=Boolean($.local_row&&$.remote_row);return{kind:J?"manual_merge":"custom",target:_,strategy:J?"manual-merge":"review-and-select",summary:J?`Fake AI proposal: compare local and remote ${_} row snapshots, then apply a reviewed manual merge.`:`Fake AI proposal: inspect ${_} with available conflict metadata before selecting a side.`,diff:J?[`--- ${_} local`,`+++ ${_} remote`,"@@ review-required @@",JSON.stringify({local:$.local_row,remote:$.remote_row},null,2).slice(0,1200)].join(` -`):null,metadata:{fake:!0,local_hash:$.conflict.local_hash,remote_hash:$.conflict.remote_hash,source_refs:$.source_refs}}}async function XF($){let _=($.now??new Date).toISOString();a($.dbPath);let J=CU($.dbPath,$.id),U=GR($.dbPath,$.id),W=y6($.modelRef??"default",$.config),X=w_(W),G=`run_${UF()}`,Y=uu({deterministic:J,evidence:U});mu({dbPath:$.dbPath,runId:G,prompt:Y,provider:X.provider,model:X.model,status:$.fake?"dry_run":"running",metadata:{conflict_id:$.id,mode:"ai",fake:$.fake===!0,read_only_tools:U.read_only_tools.map((R)=>R.name)},now:_}),RL({dbPath:$.dbPath,runId:G,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:U.citations.length,source_refs:U.source_refs.length,read_only_tools:U.read_only_tools},now:_});let Q,q,L=0.5,N={input_tokens:VL(Y),output_tokens:0,cost_usd:0};if($.fake)Q=cu(U),q=Q.summary,N.output_tokens=VL(q)+VL(Q.diff??"");else try{let{generateObject:R}=await import("ai"),{z:B}=await Promise.resolve().then(() => (JF(),_F)),H=await EU(W,{config:$.config,env:$.env}),V=B.object({summary:B.string(),confidence:B.number().min(0).max(1),proposed_patch:B.object({kind:B.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:B.string(),strategy:B.string(),summary:B.string(),diff:B.string().nullable(),metadata:B.record(B.string(),B.unknown()).default({})})}),K=await R({model:H,schema:V,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:Y});q=K.object.summary,L=du(K.object.confidence),Q=nu(K.object.proposed_patch,`${U.conflict.entity_kind}:${U.conflict.entity_id}`);let E=g1({provider:X.provider,model:X.model,usage:K.usage,providerMetadata:K.providerMetadata});N={input_tokens:E.input_tokens,output_tokens:E.output_tokens,cost_usd:E.cost_usd},xu($.dbPath,G,E,_)}catch(R){throw RL({dbPath:$.dbPath,runId:G,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:R instanceof Error?R.message:String(R)},now:_}),WF({dbPath:$.dbPath,runId:G,status:"failed",provider:X.provider,model:X.model,usage:N,metadata:{conflict_id:$.id,mode:"ai",error:R instanceof Error?R.message:String(R)},now:_}),R}return WF({dbPath:$.dbPath,runId:G,status:$.fake?"dry_run":"completed",provider:X.provider,model:X.model,usage:N,metadata:{conflict_id:$.id,mode:"ai",fake:$.fake===!0,confidence:L,proposed_strategy:Q.strategy,citation_count:U.citations.length},now:_}),RL({dbPath:$.dbPath,runId:G,level:"info",event:$.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:Q.strategy,confidence:L,patch_kind:Q.kind},now:_}),{...J,mode:"ai",proposed_strategy:Q.strategy,summary:q,proposed_patch:Q,citations:U.citations,confidence:L,agent:{generated:!0,provider:X.provider,model:X.model,run_id:G,read_only_tools:U.read_only_tools,usage:N},warnings:[...J.warnings,...U.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${$.id}`}}import{createHash as iu,randomUUID as lu}from"crypto";import{existsSync as ru,readFileSync as pu}from"fs";import{basename as ou}from"path";function bG($,_){return`${$}_${iu("sha256").update(_).digest("hex").slice(0,20)}`}function BW($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function s$($){return typeof $==="string"&&$.length>0?$:void 0}function tu($){let _=s$($.source_ref)??s$($.source_uri)??s$($.uri);if(_)return _;let J=s$($.file_id);if(J){let X=s$($.revision_id)??s$($.revision),G=`open-files://file/${encodeURIComponent(J)}`;return X?`${G}/revision/${encodeURIComponent(X)}`:G}let U=s$($.source_id),W=s$($.path);if(U&&W)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(W)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function au($,_){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function su($){return s$($.hash)??s$($.checksum)??s$($.sha256)??null}function eu($,_,J){return s$($.revision_id)??s$($.revision)??s$($.version_id)??(_.kind==="open-files"?_.revision_id:void 0)??J??null}function $d($){return s$($.previous_revision_id)??s$($.previous_revision)??s$($.previous_version_id)??null}function _d($){return(s$($.event_type)??s$($.event)??s$($.type)??s$($.action)??s$($.change_type)??"changed").toLowerCase()}function Jd($){let _=s$($.path);return s$($.title)??s$($.name)??(_?ou(_):null)}function Wd($,_){let J=tu($),U=B6(J),W=su($);return{raw:$,eventType:_d($),sourceRef:J,sourceUri:au(J,U),kind:U.kind,title:Jd($),revision:eu($,U,W),previousRevision:$d($),hash:W,status:s$($.status)?.toLowerCase()??null,updatedAt:s$($.updated_at)??_,acl:$.permissions??$.acl??void 0}}function Ud($){let _=$.trim();if(!_)return[];if(_.startsWith("[")){let J=JSON.parse(_);if(!Array.isArray(J))throw Error("Outbox array parse failed.");return J.map((U)=>{let W=BW(U);if(!W)throw Error("Outbox array entries must be objects.");return W})}if(_.startsWith("{"))try{let J=JSON.parse(_),U=BW(J);if(!U)throw Error("Outbox object parse failed.");if(Array.isArray(U.events))return U.events.map((W)=>{let X=BW(W);if(!X)throw Error("Outbox events entries must be objects.");return X});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(J){let U=_.split(/\r?\n/).filter((W)=>W.trim().length>0);if(U.length<=1)throw J;return U.map((W)=>{let X=BW(JSON.parse(W));if(!X)throw Error("Outbox JSONL entries must be objects.");return X})}return _.split(/\r?\n/).filter((J)=>J.trim().length>0).map((J)=>{let U=BW(JSON.parse(J));if(!U)throw Error("Outbox JSONL entries must be objects.");return U})}async function Xd($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 outbox URI: ${$}`);if(J)M0($,J);let[{S3Client:G,GetObjectCommand:Y},{fromIni:Q}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Q({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Y({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function Gd($,_,J){if($.startsWith("s3://"))return Xd($,_,J);if(!ru($))throw Error(`Outbox not found: ${$}`);return pu($,"utf8")}function GF($,_){let J={};if($)try{J=BW(JSON.parse($))??{}}catch{J={}}return JSON.stringify({...J,..._})}function Yd($,_,J){let U=bG("src",_.sourceUri);$.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) + WHERE id = ?`,[_.status,_.provider,_.model,_.usage.input_tokens+_.usage.output_tokens,_.usage.cost_usd,JSON.stringify(_.metadata),_.now,_.runId])}finally{$.close()}}function eP(_){let $=v(_.dbPath);try{$.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`event_${SR()}`,_.runId,_.level,_.event,JSON.stringify(_.metadata),_.now])}finally{$.close()}}function HF(_,$,g,U){let D=v(_);try{S0(D,{...g,run_id:$,created_at:U})}finally{D.close()}}function kF(_){return["Build an approval-gated merge proposal for this knowledge sync conflict.","Use only the supplied JSON evidence. Do not claim to inspect external files or write changes.","Return a patch recommendation that a human can review before approval.","",`Deterministic proposal: +${JSON.stringify({proposed_strategy:_.deterministic.proposed_strategy,summary:_.deterministic.summary,warnings:_.deterministic.warnings},null,2)}`,"",`Conflict evidence: +${JSON.stringify(_.evidence,null,2)}`].join(` +`)}function CF(_){let $=typeof _==="number"&&Number.isFinite(_)?_:0.5;return Math.max(0,Math.min(1,$))}function rF(_,$){let g=_.kind==="choose_local"||_.kind==="choose_remote"||_.kind==="no_op"||_.kind==="custom"||_.kind==="manual_merge"?_.kind:"manual_merge";return{kind:g,target:typeof _.target==="string"&&_.target?_.target:$,strategy:typeof _.strategy==="string"&&_.strategy?_.strategy:g.replace("_","-"),summary:typeof _.summary==="string"&&_.summary?_.summary:"Review both sides before applying a merge.",diff:typeof _.diff==="string"&&_.diff?_.diff:null,metadata:_.metadata&&typeof _.metadata==="object"&&!Array.isArray(_.metadata)?_.metadata:{}}}function vF(_){let $=`${_.conflict.entity_kind}:${_.conflict.entity_id}`,g=Boolean(_.local_row&&_.remote_row);return{kind:g?"manual_merge":"custom",target:$,strategy:g?"manual-merge":"review-and-select",summary:g?`Fake AI proposal: compare local and remote ${$} row snapshots, then apply a reviewed manual merge.`:`Fake AI proposal: inspect ${$} with available conflict metadata before selecting a side.`,diff:g?[`--- ${$} local`,`+++ ${$} remote`,"@@ review-required @@",JSON.stringify({local:_.local_row,remote:_.remote_row},null,2).slice(0,1200)].join(` +`):null,metadata:{fake:!0,local_hash:_.conflict.local_hash,remote_hash:_.conflict.remote_hash,source_refs:_.source_refs}}}async function WR(_){let $=(_.now??new Date).toISOString();h(_.dbPath);let g=lg(_.dbPath,_.id),U=XX(_.dbPath,_.id),D=G$(_.modelRef??"default",_.config),I=f_(D),j=`run_${SR()}`,N=kF({deterministic:g,evidence:U});bF({dbPath:_.dbPath,runId:j,prompt:N,provider:I.provider,model:I.model,status:_.fake?"dry_run":"running",metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,read_only_tools:U.read_only_tools.map((W)=>W.name)},now:$}),eP({dbPath:_.dbPath,runId:j,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:U.citations.length,source_refs:U.source_refs.length,read_only_tools:U.read_only_tools},now:$});let O,A,L=0.5,z={input_tokens:pP(N),output_tokens:0,cost_usd:0};if(_.fake)O=vF(U),A=O.summary,z.output_tokens=pP(A)+pP(O.diff??"");else try{let{generateObject:W}=await import("ai"),{z:J}=await Promise.resolve().then(() => (PR(),JR)),P=await ug(D,{config:_.config,env:_.env}),S=J.object({summary:J.string(),confidence:J.number().min(0).max(1),proposed_patch:J.object({kind:J.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:J.string(),strategy:J.string(),summary:J.string(),diff:J.string().nullable(),metadata:J.record(J.string(),J.unknown()).default({})})}),X=await W({model:P,schema:S,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:N});A=X.object.summary,L=CF(X.object.confidence),O=rF(X.object.proposed_patch,`${U.conflict.entity_kind}:${U.conflict.entity_id}`);let G=U4({provider:I.provider,model:I.model,usage:X.usage,providerMetadata:X.providerMetadata});z={input_tokens:G.input_tokens,output_tokens:G.output_tokens,cost_usd:G.cost_usd},HF(_.dbPath,j,G,$)}catch(W){throw eP({dbPath:_.dbPath,runId:j,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:W instanceof Error?W.message:String(W)},now:$}),zR({dbPath:_.dbPath,runId:j,status:"failed",provider:I.provider,model:I.model,usage:z,metadata:{conflict_id:_.id,mode:"ai",error:W instanceof Error?W.message:String(W)},now:$}),W}return zR({dbPath:_.dbPath,runId:j,status:_.fake?"dry_run":"completed",provider:I.provider,model:I.model,usage:z,metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,confidence:L,proposed_strategy:O.strategy,citation_count:U.citations.length},now:$}),eP({dbPath:_.dbPath,runId:j,level:"info",event:_.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:O.strategy,confidence:L,patch_kind:O.kind},now:$}),{...g,mode:"ai",proposed_strategy:O.strategy,summary:A,proposed_patch:O,citations:U.citations,confidence:L,agent:{generated:!0,provider:I.provider,model:I.model,run_id:j,read_only_tools:U.read_only_tools,usage:z},warnings:[...g.warnings,...U.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${_.id}`}}import{createHash as fF,randomUUID as wF}from"crypto";import{existsSync as uF,readFileSync as xF}from"fs";import{basename as yF}from"path";function Zj(_,$){return`${_}_${fF("sha256").update($).digest("hex").slice(0,20)}`}function e0(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function S_(_){return typeof _==="string"&&_.length>0?_:void 0}function hF(_){let $=S_(_.source_ref)??S_(_.source_uri)??S_(_.uri);if($)return $;let g=S_(_.file_id);if(g){let I=S_(_.revision_id)??S_(_.revision),j=`open-files://file/${encodeURIComponent(g)}`;return I?`${j}/revision/${encodeURIComponent(I)}`:j}let U=S_(_.source_id),D=S_(_.path);if(U&&D)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(D)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function cF(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function nF(_){return S_(_.hash)??S_(_.checksum)??S_(_.sha256)??null}function dF(_,$,g){return S_(_.revision_id)??S_(_.revision)??S_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??g??null}function mF(_){return S_(_.previous_revision_id)??S_(_.previous_revision)??S_(_.previous_version_id)??null}function iF(_){return(S_(_.event_type)??S_(_.event)??S_(_.type)??S_(_.action)??S_(_.change_type)??"changed").toLowerCase()}function lF(_){let $=S_(_.path);return S_(_.title)??S_(_.name)??($?yF($):null)}function tF(_,$){let g=hF(_),U=A$(g),D=nF(_);return{raw:_,eventType:iF(_),sourceRef:g,sourceUri:cF(g,U),kind:U.kind,title:lF(_),revision:dF(_,U,D),previousRevision:mF(_),hash:D,status:S_(_.status)?.toLowerCase()??null,updatedAt:S_(_.updated_at)??$,acl:_.permissions??_.acl??void 0}}function oF(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let g=JSON.parse($);if(!Array.isArray(g))throw Error("Outbox array parse failed.");return g.map((U)=>{let D=e0(U);if(!D)throw Error("Outbox array entries must be objects.");return D})}if($.startsWith("{"))try{let g=JSON.parse($),U=e0(g);if(!U)throw Error("Outbox object parse failed.");if(Array.isArray(U.events))return U.events.map((D)=>{let I=e0(D);if(!I)throw Error("Outbox events entries must be objects.");return I});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(g){let U=$.split(/\r?\n/).filter((D)=>D.trim().length>0);if(U.length<=1)throw g;return U.map((D)=>{let I=e0(JSON.parse(D));if(!I)throw Error("Outbox JSONL entries must be objects.");return I})}return $.split(/\r?\n/).filter((g)=>g.trim().length>0).map((g)=>{let U=e0(JSON.parse(g));if(!U)throw Error("Outbox JSONL entries must be objects.");return U})}async function pF(_,$,g){let U=new URL(_),D=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!D||!I)throw Error(`Invalid S3 outbox URI: ${_}`);if(g)q6(_,g);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===D?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:D,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function eF(_,$,g){if(_.startsWith("s3://"))return pF(_,$,g);if(!uF(_))throw Error(`Outbox not found: ${_}`);return xF(_,"utf8")}function XR(_,$){let g={};if(_)try{g=e0(JSON.parse(_))??{}}catch{g={}}return JSON.stringify({...g,...$})}function aF(_,$,g){let U=Zj("src",$.sourceUri);_.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(uri) DO UPDATE SET kind = excluded.kind, title = COALESCE(excluded.title, sources.title), - updated_at = excluded.updated_at`,[U,_.sourceUri,_.kind,_.title,JSON.stringify({source_ref:_.sourceRef,source_uri:_.sourceUri,status:_.status,last_outbox_event:_.eventType}),JSON.stringify(_.acl??{}),J,_.updatedAt]);let W=$.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get(_.sourceUri);if(!W)throw Error(`Failed to upsert source for outbox event: ${_.sourceUri}`);let X={source_ref:_.sourceRef,source_uri:_.sourceUri,last_outbox_event:_.eventType,last_outbox_at:_.updatedAt};if(_.status)X.status=_.status;if(s$(_.raw.path))X.path=_.raw.path;return $.run("UPDATE sources SET metadata_json = ?, acl_json = CASE WHEN ? IS NULL THEN acl_json ELSE ? END, updated_at = ? WHERE id = ?",[GF(W.metadata_json,X),_.acl===void 0?null:JSON.stringify(_.acl),_.acl===void 0?null:JSON.stringify(_.acl),_.updatedAt,W.id]),W.id}function Qd($,_,J,U){if(!J.revision)return null;let W=bG("rev",`${_}\x00${J.revision}`),X={source_ref:J.sourceRef,source_uri:J.sourceUri,status:J.status,last_outbox_event:J.eventType,reindex_required:!0};return $.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) + updated_at = excluded.updated_at`,[U,$.sourceUri,$.kind,$.title,JSON.stringify({source_ref:$.sourceRef,source_uri:$.sourceUri,status:$.status,last_outbox_event:$.eventType}),JSON.stringify($.acl??{}),g,$.updatedAt]);let D=_.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get($.sourceUri);if(!D)throw Error(`Failed to upsert source for outbox event: ${$.sourceUri}`);let I={source_ref:$.sourceRef,source_uri:$.sourceUri,last_outbox_event:$.eventType,last_outbox_at:$.updatedAt};if($.status)I.status=$.status;if(S_($.raw.path))I.path=$.raw.path;return _.run("UPDATE sources SET metadata_json = ?, acl_json = CASE WHEN ? IS NULL THEN acl_json ELSE ? END, updated_at = ? WHERE id = ?",[XR(D.metadata_json,I),$.acl===void 0?null:JSON.stringify($.acl),$.acl===void 0?null:JSON.stringify($.acl),$.updatedAt,D.id]),D.id}function sF(_,$,g,U){if(!g.revision)return null;let D=Zj("rev",`${$}\x00${g.revision}`),I={source_ref:g.sourceRef,source_uri:g.sourceUri,status:g.status,last_outbox_event:g.eventType,reindex_required:!0};return _.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(source_id, revision) DO UPDATE SET hash = COALESCE(excluded.hash, source_revisions.hash), - metadata_json = excluded.metadata_json`,[W,_,J.revision,J.hash,s$(J.raw.extracted_text_ref)??null,JSON.stringify(X),U]),$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(_,J.revision)?.id??null}function qd($,_,J){if(J.previousRevision){let U=$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(_,J.previousRevision).map((W)=>W.id);if(U.length>0)return U}if(J.revision)return $.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(_,J.revision).map((U)=>U.id);if(J.hash)return $.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all(_,J.hash).map((U)=>U.id);return $.query("SELECT id FROM source_revisions WHERE source_id = ?").all(_).map((U)=>U.id)}function zd($,_){let J=$.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(_),U=0,W=0;for(let G of J){let Y=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(G.id);U+=Y?.n??0;let Q=$.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(G.id);W+=Q?.n??0,$.run("DELETE FROM vector_index_entries WHERE chunk_id = ?",[G.id]),$.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?",[G.id]),$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[G.id])}$.run("DELETE FROM chunks WHERE source_revision_id = ?",[_]);let X=$.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get(_);return $.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?",[GF(X?.metadata_json,{reindex_required:!0,invalidated_at:new Date().toISOString()}),_]),{chunksDeleted:J.length,embeddingsDeleted:U,vectorEntriesDeleted:W}}function jd($,_){return _==="deleted"||["delete","deleted","remove","removed"].includes($)}function Dd($){return["move","moved","rename","renamed","path_changed","canonical_key_changed"].includes($)}function Od($){return["permission","permissions","permission_changed","acl_changed","acl_revoked"].includes($)}async function YF($){let _=($.now??new Date).toISOString();if($.safetyPolicy)d4($.dbPath,$.safetyPolicy);a($.dbPath);let J=await Gd($.input,$.config,$.safetyPolicy),U=Ud(J),W=m($.dbPath),X=`run_${lu()}`;try{return W.transaction(()=>{W.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[X,"open-files-outbox",$.input,"completed","local","open-files-outbox",JSON.stringify({path:$.input,events:U.length}),_,_]);let G=new Set,Y=new Set,Q=0,q=0,L=0,N=0,R=0,B=0,H=0;return __(W,{event_type:"source_read",action:$.input.startsWith("s3://")?"s3_outbox_read":"local_outbox_read",target_uri:$.input,decision:"allow",metadata:{events:U.length,read_only:!0},created_at:_}),U.forEach((V,K)=>{let E=Wd(V,_),F=Yd(W,E,_);G.add(F);let w=Qd(W,F,E,_);if(w)Y.add(w);let A=qd(W,F,E);for(let g of A){Y.add(g);let v=zd(W,g);Q+=v.chunksDeleted,q+=v.embeddingsDeleted,L+=v.vectorEntriesDeleted,N+=1}if(jd(E.eventType,E.status))R+=1;if(Dd(E.eventType))B+=1;if(Od(E.eventType)||E.acl!==void 0)H+=1;W.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[bG("evt",`${X}\x00${K}\x00${E.sourceRef}\x00${E.eventType}`),X,"info",E.eventType,JSON.stringify({source_ref:E.sourceRef,source_uri:E.sourceUri,revision:E.revision,hash:E.hash,status:E.status,affected_revisions:A.length}),E.updatedAt])}),W.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[bG("usage",X),X,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),_]),__(W,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:$.dbPath,decision:"allow",metadata:{run_id:X,events:U.length,sources:G.size,revisions:Y.size,chunks_deleted:Q,embeddings_deleted:q,vector_entries_deleted:L},created_at:_}),{path:$.input,db_path:$.dbPath,run_id:X,events_seen:U.length,sources_touched:G.size,revisions_touched:Y.size,chunks_deleted:Q,embeddings_deleted:q,vector_entries_deleted:L,stale_revisions:N,deleted_sources:R,moved_sources:B,permission_updates:H}})()}finally{W.close()}}import{spawnSync as zF}from"child_process";import{hostname as Y2,platform as jF,userInfo as Ld}from"os";var Bd=1,Hd="@hasna/machines",Nd="@hasna/machines/consumer";function Y$($){return typeof $==="string"&&$.length>0?$:null}function x0($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function v_($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function CG($){return typeof $==="boolean"?$:null}function Vd($){return typeof $==="number"&&Number.isFinite($)?$:null}function PG($=jF()){let _=$.toLowerCase();if(_==="darwin"||_==="macos")return"macos";if(_==="win32"||_==="windows")return"windows";if(_==="linux")return"linux";return $}function uX($){let _=zF("bash",["-c",$],{encoding:"utf8",env:process.env});return{stdout:_.stdout||"",stderr:_.stderr||"",exitCode:_.status??1}}async function HW($,_){return await $(_)}async function dX($,_){return(await HW(_,`command -v ${$} >/dev/null 2>&1`)).exitCode===0}function Rd($){try{let _=JSON.parse($);if(!_||typeof _!=="object")return null;return _}catch{return null}}function QF($){if(!$)return null;return $.HostName??$.DNSName?.split(".")[0]??null}async function Kd($,_){let J=new Map;if(!await dX("tailscale",$))return _.push("tailscale_not_available"),{peers:J,selfKey:null};let U=await HW($,"tailscale status --json");if(U.exitCode!==0)return _.push(`tailscale_status_failed:${U.stderr.trim()||U.exitCode}`),{peers:J,selfKey:null};let W=Rd(U.stdout);if(!W)return _.push("tailscale_status_invalid_json"),{peers:J,selfKey:null};let X=(G)=>{let Y=QF(G);if(Y&&G)J.set(Y,G)};X(W.Self);for(let G of Object.values(W.Peer??{}))X(G);return{peers:J,selfKey:QF(W.Self)}}function Fd($){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??$??Y2()}function Ed($){let _=$.machineId===$.localMachineId||$.machineId===Y2(),J=$.peer?.DNSName?.replace(/\.$/,"")??null,U=J??$.peer?.TailscaleIPs?.[0]??null,W=[];if(_)W.push({kind:"local",target:"localhost",reachable:!0});if(U)W.push({kind:"tailscale",target:U,reachable:$.peer?.Online??null});let X=W.find((G)=>G.kind==="local")??W.find((G)=>G.kind==="tailscale")??null;return{machine_id:$.machineId,hostname:$.peer?.HostName??(_?Y2():$.machineId),local:_,platform:$.peer?.OS?PG($.peer.OS):_?PG():null,os:$.peer?.OS??(_?jF():null),user:_?Ld().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:J,ips:$.peer?.TailscaleIPs??[],online:$.peer?.Online??null,active:$.peer?.Active??null,last_seen:$.peer?.LastSeen??null},ssh:{address:null,route:X?.kind==="local"?"local":X?.kind==="tailscale"?"tailscale":"unknown",command_target:X?.target??null},route_hints:W,tags:[],metadata:{},source:"local"}}function Md($){if(!Array.isArray($))return[];return $.map((_)=>{let J=v_(_),U=Y$(J.kind)??"unknown";return{kind:U==="local"||U==="lan"||U==="tailscale"||U==="ssh"?U:"unknown",target:Y$(J.target)??"",reachable:CG(J.reachable)}}).filter((_)=>_.target.length>0)}function Ad($,_){let J=Y$($.machine_id)??Y$($.hostname)??"unknown",U=v_($.tailscale),W=v_($.ssh),X=Y$($.heartbeat_status),G=Y$(W.route);return{machine_id:J,hostname:Y$($.hostname),local:J===_,platform:Y$($.platform),os:Y$($.os),user:Y$($.user),workspace_path:Y$($.workspace_path),manifest_declared:$.manifest_declared===!0,heartbeat_status:X==="online"||X==="offline"?X:"unknown",last_heartbeat_at:Y$($.last_heartbeat_at),tailscale:{dns_name:Y$(U.dns_name),ips:x0(U.ips),online:CG(U.online),active:CG(U.active),last_seen:Y$(U.last_seen)},ssh:{address:Y$(W.address),route:G==="local"||G==="lan"||G==="tailscale"?G:"unknown",command_target:Y$(W.command_target)},route_hints:Md($.route_hints),tags:x0($.tags),metadata:v_($.metadata),source:"open-machines"}}function bd($,_){return`${_} machine${_===1?"":"s"} discovered via ${$}`}function q6($){let _=$ instanceof Error?$.message:String($);return _.includes("Cannot find module '@hasna/machines'")||_.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":_}function nX($){return $.adapterMode??"auto"}function DF($){let _=$?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof _==="number")return _;let J=$?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof J==="number"?J:null}function TG($){return typeof $.schema_version==="number"?$.schema_version:null}function cX($){return typeof $==="number"&&$>Bd?$:null}function SG($){return{package:Hd,entrypoint:Nd,mode:$.mode,implementation:$.implementation,contract_version:$.contractVersion??null,available:$.available,error:$.error??null}}function u$($,_="adapter_disabled"){return SG({mode:$,implementation:"disabled",available:!1,error:_})}function ZG($,_){let J=cX(DF(_));if(!J)return null;return SG({mode:$,implementation:"disabled",available:!1,error:`unsupported_contract_version:${J}`,contractVersion:J})}function vG($){return SG({mode:$,implementation:"cli",available:!0})}function yG($,_){return SG({mode:$,implementation:"sdk",available:!0,contractVersion:DF(_)})}function hG($){try{return JSON.parse($)}catch{return null}}function Q2($){return`'${$.replace(/'/g,"'\\''")}'`}function mG($){return["machines",...$].map(Q2).join(" ")}function xG($){return $==="local"||$==="localhost"||$===Y2()||$===process.env.HASNA_MACHINE_ID||$===process.env.OPEN_MACHINES_MACHINE_ID||$===process.env.MACHINE_ID}function wd($,_){let J=xG($),U=J?_:`ssh ${Q2($)} ${Q2(_)}`,W=zF("bash",["-c",U],{encoding:"utf8",env:process.env});return{stdout:W.stdout||"",stderr:W.stderr||"",exitCode:W.status??1,source:J?"local":"ssh"}}async function OF($,_,J){return await $(_,J)}function X2($,_){if(_)return"ok";return $===!1?"warn":"fail"}function G2($){return $.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function gd($){if($==="@hasna/knowledge")return"knowledge";if($==="@hasna/machines")return"machines";return $.split("/").pop()??$}function kd($){return $.trim().split(/\r?\n/).find(Boolean)??""}function LF($){return $.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function BF($){let _={};for(let J of $.split(/\r?\n/)){let U=J.indexOf("=");if(U<=0)continue;_[J.slice(0,U)]=J.slice(U+1)}return _}function s4($){return{id:$.id,kind:$.kind,status:$.status,target:$.target,expected:$.expected??null,actual:$.actual??null,detail:$.detail,source:$.source}}async function HF($,_,J){let U=[`cmd=${Q2(_.command)}`,'path="$(command -v "$cmd" 2>/dev/null || true)"','printf "path=%s\\n" "$path"',`if [ -n "$path" ]; then version="$("$cmd" ${_.versionArgs??"--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi`].join("; "),W=await OF(J,$,U),X=BF(W.stdout);return{path:X.path||null,version:X.version?kd(X.version):null,stderr:W.stderr,source:W.source??(xG($)?"local":"ssh")}}function qF($){let _=$==="name"?String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`:String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`;return[`if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${$} ?? '')" "$pkg" 2>/dev/null`,`elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${$} || '')" "$pkg" 2>/dev/null`,`else sed -n '${_}' "$pkg" | head -n 1`,"fi"].join("; ")}async function Id($,_,J){let U=[`path=${Q2(_.path)}`,'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"','pkg="$path/package.json"','printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"',`if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${qF("name")})"; printf "version=%s\\n" "$(${qF("version")})"; fi`].join("; "),W=await OF(J,$,U),X=BF(W.stdout);return{exists:X.exists==="yes",packageJson:X.package_json==="yes",packageName:X.package_name||null,version:X.version||null,stderr:W.stderr,source:W.source??(xG($)?"local":"ssh")}}async function fd($,_,J){let U=await HF($,_,J),W=Boolean(U.path),X=[s4({id:`command:${G2(_.command)}:path`,kind:"command",status:X2(_.required,W),target:_.command,expected:"available",actual:U.path??"missing",detail:W?`found at ${U.path}`:U.stderr||"command missing",source:U.source})];if(_.expectedVersion){let G=LF(U.version??"");X.push(s4({id:`command:${G2(_.command)}:version`,kind:"command",status:G===_.expectedVersion?"ok":X2(_.required,!1),target:_.command,expected:_.expectedVersion,actual:G??U.version??"missing",detail:G?`version output: ${U.version}`:"version unavailable",source:U.source}))}return X}async function Cd($,_,J){let U=_.command??gd(_.name),W=await HF($,{command:U,expectedVersion:_.expectedVersion,required:_.required},J),X=Boolean(W.path),G=[s4({id:`package:${G2(_.name)}:command`,kind:"package",status:X2(_.required,X),target:_.name,expected:U,actual:W.path??"missing",detail:X?`${U} found at ${W.path}`:`${U} command missing`,source:W.source})];if(_.expectedVersion){let Y=LF(W.version??"");G.push(s4({id:`package:${G2(_.name)}:version`,kind:"package",status:Y===_.expectedVersion?"ok":X2(_.required,!1),target:_.name,expected:_.expectedVersion,actual:Y??W.version??"missing",detail:Y?`version output: ${W.version}`:"version unavailable",source:W.source}))}return G}async function Pd($,_,J){let U=await Id($,_,J),W=_.label??_.path,X=[s4({id:`workspace:${G2(W)}:path`,kind:"workspace",status:X2(_.required,U.exists),target:W,expected:_.path,actual:U.exists?"exists":"missing",detail:U.exists?`workspace exists at ${_.path}`:U.stderr||`workspace missing at ${_.path}`,source:U.source})];if(_.expectedPackageName)X.push(s4({id:`workspace:${G2(W)}:package-name`,kind:"workspace",status:U.packageName===_.expectedPackageName?"ok":X2(_.required,!1),target:W,expected:_.expectedPackageName,actual:U.packageName??(U.packageJson?"missing-name":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));if(_.expectedVersion)X.push(s4({id:`workspace:${G2(W)}:version`,kind:"workspace",status:U.version===_.expectedVersion?"ok":X2(_.required,!1),target:W,expected:_.expectedVersion,actual:U.version??(U.packageJson?"missing-version":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));return X}function NF($,_){return{...$,knowledge:{scope:_.knowledge?.scope??"global",app_path:K4,workspace_home:_.knowledge?.workspace_home??null},message:bd($.source,$.machines.length)}}async function uG(){try{return await import("@hasna/machines/consumer")}catch($){if(q6($)!=="module_not_found")throw $;return await import("@hasna/machines")}}function VF($,_,J){let U=v_($);if(cX(TG(U)))return null;let W=Array.isArray(U.machines)?U.machines:null,X=Y$(U.local_machine_id);if(!W||!X)return null;let G={ok:!0,source:"open-machines",generated_at:Y$(U.generated_at)??(_.now??new Date).toISOString(),local_machine_id:X,local_hostname:Y$(U.local_hostname)??Y2(),current_platform:Y$(U.current_platform)??PG(),machines:W.map((Y)=>Ad(Y,X)),warnings:x0(U.warnings),adapter:J};return NF(G,_)}function wG($){return $==="local"||$==="lan"||$==="tailscale"||$==="ssh"||$==="unknown"?$:null}function RF($){let _=v_($),J=Y$(_.observed_at),U=Y$(_.source_authority);if(!J||!U)return null;return{observed_at:J,verified_at:Y$(_.verified_at),expires_at:Y$(_.expires_at),ttl_ms:Vd(_.ttl_ms),source_authority:U,confidence:Y$(_.confidence),cacheable:_.cacheable===!0,stale:_.stale===!0,reasons:x0(_.reasons)}}function KF($,_){let J=v_($);if(cX(TG(J)))return null;let U=Y$(J.target)??Y$(J.command_target);if(J.ok!==!0||!U)return null;let W=typeof J.evidence==="object"&&J.evidence!==null?J.evidence:null,X=typeof W?.selected_hint==="object"&&W.selected_hint!==null?W.selected_hint:null;return{target:U,route:wG(J.route),targetKind:wG(X?.kind)??wG(J.source)??wG(J.route),confidence:Y$(J.confidence),source:"open-machines",adapter:_,evidence:W,cacheability:RF(J.cacheability),warnings:x0(J.warnings)}}function KL($){let _=v_($);return{path:Y$(_.path),source:Y$(_.source)??"unresolved"}}function Td($){if(!Array.isArray($))return[];return $.flatMap((_)=>{let J=v_(_),U=Y$(J.id),W=Y$(J.status),X=Y$(J.severity),G=Y$(J.message);if(!U||!W||!X||!G)return[];return[{id:U,status:W,severity:X,message:G,path:Y$(J.path),source:Y$(J.source)??"unknown",path_exists:CG(J.path_exists)}]})}function Sd($){if(!Array.isArray($))return[];return $.flatMap((_)=>{let J=v_(_),U=Y$(J.id),W=Y$(J.reason),X=x0(J.command),G=Y$(J.shell_command),Y=x0(J.apply_command),Q=Y$(J.apply_shell_command);if(!U||!W||!X.length||!G||!Y.length||!Q)return[];return[{id:U,reason:W,command:X,shell_command:G,apply_command:Y,apply_shell_command:Q}]})}function Zd($){if(!($.projectRootSource==="inferred"||$.openFilesRootSource==="inferred"||$.trustStatus==="untrusted"||$.authStatus==="unknown"||$.warnings.some((W)=>W.includes("inferred")||W.includes("untrusted")||W.includes("unknown_auth")||W.includes("missing"))))return[];let J=["machines","workspace","repair","--machine",$.requestedMachineId,"--project",$.projectId,"--repo",$.repoName,"--open-files-repo",$.openFilesRepoName??"open-files","--json"],U=[...J,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:J,shell_command:J.map(Q2).join(" "),apply_command:U,apply_shell_command:U.map(Q2).join(" ")}]}function FF($,_,J){let U=v_($);if(cX(TG(U)))return null;let W=v_(U.paths),X=v_(U.project),G=v_(U.machine),Y=KL(W.project_root),Q=KL(W.workspace_root),q=KL(W.open_files_root);if(U.ok!==!0||!Y.path)return null;let L=typeof U.evidence==="object"&&U.evidence!==null?U.evidence:null,N=Y$(U.requested_machine_id)??_.machineId,R=Y$(X.project_id)??_.projectId??"open-knowledge",B=Y$(X.repo_name)??_.repoName??_.projectId??"open-knowledge",H=Y$(G.trust_status)??"unknown",V=Y$(G.auth_status)??"unknown",K=x0(U.warnings),E=Td(U.diagnostics),F=Sd(U.repair_hints);return{ok:!0,source:"open-machines",adapter:J,requested_machine_id:N,machine_id:Y$(U.machine_id),project_id:R,repo_name:B,project_root:Y.path,project_root_source:Y.source,workspace_root:Q.path,workspace_root_source:Q.source,open_files_root:q.path,open_files_root_source:q.source,trust_status:H,auth_status:V,current:G.current===!0,primary:G.primary===!0,diagnostics:E,repair_hints:F.length?F:Zd({requestedMachineId:N,projectId:R,repoName:B,openFilesRepoName:_.openFilesRepoName,warnings:K,projectRootSource:Y.source,openFilesRootSource:q.source,trustStatus:H,authStatus:V}),evidence:L,cacheability:RF(U.cacheability),warnings:K}}async function gG($,_){let J=$.runner??uX;if(!await dX("machines",J))return null;let U=["topology","--json"];if($.includeTailscale===!1)U.push("--no-tailscale");let W=await HW(J,mG(U));if(W.exitCode!==0)return null;return VF(hG(W.stdout),$,_)}async function p4($,_){let J=[];if(_.error)J.push(`open_machines_unavailable:${_.error}`);let U=$.runner??uX,W=$.includeTailscale===!1?{peers:new Map,selfKey:null}:await Kd(U,J),X=Fd(W.selfKey),Y=[...new Set([X,...W.peers.keys()])].sort().map((Q)=>Ed({machineId:Q,localMachineId:X,peer:W.peers.get(Q)}));return NF({ok:!0,source:"local",generated_at:($.now??new Date).toISOString(),local_machine_id:X,local_hostname:Y2(),current_platform:PG(),machines:Y,warnings:J,adapter:_},$)}async function EF($={}){let _=nX($);if(_==="disabled")return await p4($,u$(_));let J=vG(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??uG)(),X=ZG(_,W);if(X)return await p4($,X);let G=yG(_,W);if(W?.discoverMachineTopology){let Y=W.discoverMachineTopology({includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),Q=VF(Y,$,G);if(Q)return Q;if(_==="sdk")return await p4($,u$(_,"invalid_topology_shape"));return await gG($,J)??await p4($,u$(_,"invalid_topology_shape"))}if(_==="sdk")return await p4($,u$(_,"missing_discoverMachineTopology"));return await gG($,J)??await p4($,u$(_,"missing_discoverMachineTopology"))}return await gG($,J)??await p4($,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return await p4($,u$(_,q6(U)));return await gG($,J)??await p4($,u$(_,q6(U)))}}async function kG($,_){let J=$.runner??uX;if(!await dX("machines",J))return null;let U=["route","--machine",$.machineId,"--json"];if($.includeTailscale===!1)U.push("--no-tailscale");let W=await HW(J,mG(U));if(W.exitCode!==0)return null;return KF(hG(W.stdout),_)}function o4($,_){return{target:$,route:null,targetKind:null,confidence:null,source:"raw",adapter:_,evidence:null,cacheability:null,warnings:[]}}async function FL($){let _=nX($);if(_==="disabled")return o4($.machineId,u$(_));let J=vG(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??uG)(),X=ZG(_,W);if(X)return o4($.machineId,X);let G=yG(_,W);if(W?.resolveMachineRoute){let Y=KF(W.resolveMachineRoute($.machineId,{includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),G);if(Y)return Y;if(_==="sdk")return o4($.machineId,u$(_,"invalid_route_shape"));return await kG($,J)??o4($.machineId,u$(_,"invalid_route_shape"))}if(_==="sdk")return o4($.machineId,u$(_,"missing_resolveMachineRoute"));return await kG($,J)??o4($.machineId,u$(_,"missing_resolveMachineRoute"))}return await kG($,J)??o4($.machineId,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return{...o4($.machineId,u$(_,q6(U))),warnings:[q6(U)]};return await kG($,J)??{...o4($.machineId,u$(_,q6(U))),warnings:[q6(U)]}}}async function IG($,_){let J=$.runner??uX;if(!await dX("machines",J))return null;let U=$.projectId??"open-knowledge",W=$.repoName??"open-knowledge",X=["workspace","resolve","--machine",$.machineId,"--project",U,"--repo",W,"--open-files-repo",$.openFilesRepoName??"open-files","--json"];if($.includeTailscale===!1)X.push("--no-tailscale");let G=await HW(J,mG(X));if(G.exitCode!==0)return null;return FF(hG(G.stdout),$,_)}function vd($){let _=$.peerWorkspace?.trim();if(!_)return null;return{ok:!0,source:"argument",adapter:u$(nX($),"argument_override"),requested_machine_id:$.machineId,machine_id:$.machineId,project_id:$.projectId??"open-knowledge",repo_name:$.repoName??"open-knowledge",project_root:_,project_root_source:"argument",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:[]}}function t4($,_,J){return{ok:!1,source:"raw",adapter:J,requested_machine_id:$.machineId,machine_id:null,project_id:$.projectId??"open-knowledge",repo_name:$.repoName??"open-knowledge",project_root:null,project_root_source:"unresolved",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:_}}async function dG($){let _=vd($);if(_)return _;let J=nX($);if(J==="disabled")return t4($,["adapter_disabled"],u$(J));let U=vG(J);try{if(J!=="cli"){let X=await($.loadOpenMachines??uG)(),G=ZG(J,X);if(G)return t4($,[`unsupported_contract_version:${G.contract_version}`],G);let Y=yG(J,X);if(X?.resolveMachineWorkspace){let Q=FF(X.resolveMachineWorkspace({machineId:$.machineId,projectId:$.projectId??"open-knowledge",repoName:$.repoName??"open-knowledge",openFilesRepoName:$.openFilesRepoName??"open-files",includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),$,Y);if(Q)return Q;if(J==="sdk")return t4($,["invalid_workspace_shape"],u$(J,"invalid_workspace_shape"));return await IG($,U)??t4($,["invalid_workspace_shape"],u$(J,"invalid_workspace_shape"))}if(J==="sdk")return t4($,["missing_resolveMachineWorkspace"],u$(J,"missing_resolveMachineWorkspace"));return await IG($,U)??t4($,["missing_resolveMachineWorkspace"],u$(J,"missing_resolveMachineWorkspace"))}return await IG($,U)??t4($,["machines_cli_unavailable"],u$(J,"machines_cli_unavailable"))}catch(W){if(J==="sdk")return t4($,[q6(W)],u$(J,q6(W)));return await IG($,U)??t4($,[q6(W)],u$(J,q6(W)))}}function MF($,_){return{...$,knowledge:{scope:_.knowledge?.scope??"global",app_path:K4,workspace_home:_.knowledge?.workspace_home??null},message:$.ok?`Machine ${$.machine_id} passed knowledge preflight`:`Machine ${$.machine_id} failed knowledge preflight: ${$.summary.fail} failing check(s)`}}function AF($,_,J){let U=v_($);if(cX(TG(U)))return null;let W=Array.isArray(U.checks)?U.checks:null,X=Y$(U.machine_id)??Y$(U.machineId);if(!W||!X)return null;let G=W.map((Q)=>{let q=v_(Q),L=Y$(q.status),N=Y$(q.kind),R=Y$(q.source);return s4({id:Y$(q.id)??"unknown",kind:N==="command"||N==="package"||N==="workspace"?N:"command",status:L==="ok"||L==="warn"||L==="fail"?L:"fail",target:Y$(q.target)??"unknown",expected:Y$(q.expected),actual:Y$(q.actual),detail:Y$(q.detail)??"",source:R==="local"||R==="ssh"||R==="open-machines"?R:"open-machines"})}),Y={ok:G.filter((Q)=>Q.status==="ok").length,warn:G.filter((Q)=>Q.status==="warn").length,fail:G.filter((Q)=>Q.status==="fail").length};return MF({ok:Y.fail===0,source:"open-machines",machine_id:X,generated_at:Y$(U.generated_at)??(_.now??new Date).toISOString(),checks:G,summary:Y,adapter:J},_)}function yd($){if(!$.runner)return uX;return async(_)=>{let J=await $.runner?.("local",_);return{stdout:J?.stdout??"",stderr:J?.stderr??"",exitCode:J?.exitCode??1}}}function hd($){return[$.name,$.command,$.expectedVersion].filter((_)=>Boolean(_)).join(":")}function md($){let _=[$.expectedPackageName,$.expectedVersion].filter((U)=>Boolean(U)).join(":"),J=_?`${$.path}:${_}`:$.path;return $.label?`${$.label}=${J}`:J}async function fG($,_){let J=yd($);if(!await dX("machines",J))return null;let U=["compatibility","--json","--machine",$.machineId??"local"];for(let X of $.commands??[])U.push("--command",X.expectedVersion?`${X.command}:${X.expectedVersion}`:X.command);for(let X of $.packages??[])U.push("--package",hd(X));for(let X of $.workspaces??[])U.push("--workspace",md(X));let W=await HW(J,mG(U));if(W.exitCode!==0)return null;return AF(hG(W.stdout),$,_)}async function a4($,_){let J=$.machineId??Y2(),U=$.runner??wd,W=$.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],X=$.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],G=$.workspaces??[],Y=[];for(let q of W)Y.push(...await fd(J,q,U));for(let q of X)Y.push(...await Cd(J,q,U));for(let q of G)Y.push(...await Pd(J,q,U));if(_.error)Y.push(s4({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:_.error,detail:"Using knowledge local/ssh compatibility fallback",source:xG(J)?"local":"ssh"}));let Q={ok:Y.filter((q)=>q.status==="ok").length,warn:Y.filter((q)=>q.status==="warn").length,fail:Y.filter((q)=>q.status==="fail").length};return MF({ok:Q.fail===0,source:"local",machine_id:J,generated_at:($.now??new Date).toISOString(),checks:Y,summary:Q,adapter:_},$)}async function bF($={}){let _=nX($);if(_==="disabled")return await a4($,u$(_));let J=vG(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??uG)(),X=ZG(_,W);if(X)return await a4($,X);let G=yG(_,W);if(W?.checkMachineCompatibility){let Y=W.checkMachineCompatibility({machineId:$.machineId,commands:$.commands,packages:$.packages,workspaces:$.workspaces,runner:$.runner,now:$.now}),Q=AF(Y,$,G);if(Q)return Q;if(_==="sdk")return await a4($,u$(_,"invalid_compatibility_shape"));return await fG($,J)??await a4($,u$(_,"invalid_compatibility_shape"))}if(_==="sdk")return await a4($,u$(_,"missing_checkMachineCompatibility"));return await fG($,J)??await a4($,u$(_,"missing_checkMachineCompatibility"))}return await fG($,J)??await a4($,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return await a4($,u$(_,q6(U)));return await fG($,J)??await a4($,u$(_,q6(U)))}}import{createHash as wF}from"crypto";function ML($,_,J=24){return`${$}_${wF("sha256").update(_).digest("hex").slice(0,J)}`}function NW($){return $.normalize("NFKC").trim().replace(/\s+/g," ")}function xd($){return NW($).toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")}function n6($,_){try{return JSON.parse($)}catch{return _}}function u0($){return{...$,record_kind:$.record_kind,source_kind:$.source_kind,status:$.status,source_refs:n6($.source_refs_json,[]),evidence_refs:n6($.evidence_refs_json,[]),requires_approval:$.requires_approval===1,checks:n6($.checks_json,gF()),metadata:n6($.metadata_json,{})}}function AL($){return{...$,record_kind:$.record_kind,source_refs:n6($.source_refs_json,[]),evidence_refs:n6($.evidence_refs_json,[]),metadata:n6($.metadata_json,{})}}function gF(){return{citations:{provided:0,valid:0,invalid:0,entries:[]},invalid_source_refs:[],stale_refs:[],duplicate_record_ids:[],duplicate_candidate_ids:[],conflicting_record_ids:[],conflicting_candidate_ids:[],approval_reasons:[]}}function ud($){let _=typeof $==="string"?{ref:$}:$;return{ref:NW(_.ref),citation_id:_.citation_id??null,chunk_id:_.chunk_id??null,revision:_.revision??null,hash:_.hash??null,observed_at:_.observed_at??null,expires_at:_.expires_at??null,status:_.status??null}}function kF($){try{let _=new URL($);return _.protocol.length>1&&(_.hostname.length>0||_.pathname.length>0)}catch{return/^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test($)}}function nG($){return["deleted","stale","invalidated","reindex_required","expired","superseded"].includes(($??"").toLowerCase())}function EL($){if(!$)return null;let _=n6($,{});if(_.stale===!0)return"stale";return typeof _.status==="string"?_.status:null}function dd($){if($.citation_id)return $.citation_id;return $.ref.match(/^(?:cite|citation):(.+)$/)?.[1]??null}function nd($){if($.chunk_id)return $.chunk_id;return $.ref.match(/^chunk:(.+)$/)?.[1]??null}function cd($,_,J){let U=nG(_.status)||Boolean(_.expires_at&&_.expires_at<=J);if(!_.ref||!kF(_.ref))return{ref:_.ref,valid:!1,resolved_by:"none",stale:U,reason:"invalid_reference"};let W=dd(_),X=$.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + metadata_json = excluded.metadata_json`,[D,$,g.revision,g.hash,S_(g.raw.extracted_text_ref)??null,JSON.stringify(I),U]),_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get($,g.revision)?.id??null}function _M(_,$,g){if(g.previousRevision){let U=_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,g.previousRevision).map((D)=>D.id);if(U.length>0)return U}if(g.revision)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,g.revision).map((U)=>U.id);if(g.hash)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all($,g.hash).map((U)=>U.id);return _.query("SELECT id FROM source_revisions WHERE source_id = ?").all($).map((U)=>U.id)}function $M(_,$){let g=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($),U=0,D=0;for(let j of g){let N=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(j.id);U+=N?.n??0;let O=_.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(j.id);D+=O?.n??0,_.run("DELETE FROM vector_index_entries WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[j.id])}_.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]);let I=_.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get($);return _.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?",[XR(I?.metadata_json,{reindex_required:!0,invalidated_at:new Date().toISOString()}),$]),{chunksDeleted:g.length,embeddingsDeleted:U,vectorEntriesDeleted:D}}function gM(_,$){return $==="deleted"||["delete","deleted","remove","removed"].includes(_)}function DM(_){return["move","moved","rename","renamed","path_changed","canonical_key_changed"].includes(_)}function UM(_){return["permission","permissions","permission_changed","acl_changed","acl_revoked"].includes(_)}async function RR(_){let $=(_.now??new Date).toISOString();if(_.safetyPolicy)_6(_.dbPath,_.safetyPolicy);h(_.dbPath);let g=await eF(_.input,_.config,_.safetyPolicy),U=oF(g),D=v(_.dbPath),I=`run_${wF()}`;try{return D.transaction(()=>{D.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,"open-files-outbox",_.input,"completed","local","open-files-outbox",JSON.stringify({path:_.input,events:U.length}),$,$]);let j=new Set,N=new Set,O=0,A=0,L=0,z=0,W=0,J=0,P=0;return X_(D,{event_type:"source_read",action:_.input.startsWith("s3://")?"s3_outbox_read":"local_outbox_read",target_uri:_.input,decision:"allow",metadata:{events:U.length,read_only:!0},created_at:$}),U.forEach((S,X)=>{let G=tF(S,$),R=aF(D,G,$);j.add(R);let K=sF(D,R,G,$);if(K)N.add(K);let Q=_M(D,R,G);for(let T of Q){N.add(T);let q=$M(D,T);O+=q.chunksDeleted,A+=q.embeddingsDeleted,L+=q.vectorEntriesDeleted,z+=1}if(gM(G.eventType,G.status))W+=1;if(DM(G.eventType))J+=1;if(UM(G.eventType)||G.acl!==void 0)P+=1;D.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[Zj("evt",`${I}\x00${X}\x00${G.sourceRef}\x00${G.eventType}`),I,"info",G.eventType,JSON.stringify({source_ref:G.sourceRef,source_uri:G.sourceUri,revision:G.revision,hash:G.hash,status:G.status,affected_revisions:Q.length}),G.updatedAt])}),D.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[Zj("usage",I),I,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),$]),X_(D,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:_.dbPath,decision:"allow",metadata:{run_id:I,events:U.length,sources:j.size,revisions:N.size,chunks_deleted:O,embeddings_deleted:A,vector_entries_deleted:L},created_at:$}),{path:_.input,db_path:_.dbPath,run_id:I,events_seen:U.length,sources_touched:j.size,revisions_touched:N.size,chunks_deleted:O,embeddings_deleted:A,vector_entries_deleted:L,stale_revisions:z,deleted_sources:W,moved_sources:J,permission_updates:P}})()}finally{D.close()}}import{spawnSync as QR}from"child_process";import{hostname as u4,platform as TR,userInfo as IM}from"os";var jM=1,NM="@hasna/machines",EM="@hasna/machines/consumer";function d(_){return typeof _==="string"&&_.length>0?_:null}function y6(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function n_(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function vj(_){return typeof _==="boolean"?_:null}function OM(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function fj(_=TR()){let $=_.toLowerCase();if($==="darwin"||$==="macos")return"macos";if($==="win32"||$==="windows")return"windows";if($==="linux")return"linux";return _}function DU(_){let $=QR("bash",["-c",_],{encoding:"utf8",env:process.env});return{stdout:$.stdout||"",stderr:$.stderr||"",exitCode:$.status??1}}async function a0(_,$){return await _($)}async function UU(_,$){return(await a0($,`command -v ${_} >/dev/null 2>&1`)).exitCode===0}function AM(_){try{let $=JSON.parse(_);if(!$||typeof $!=="object")return null;return $}catch{return null}}function GR(_){if(!_)return null;return _.HostName??_.DNSName?.split(".")[0]??null}async function LM(_,$){let g=new Map;if(!await UU("tailscale",_))return $.push("tailscale_not_available"),{peers:g,selfKey:null};let U=await a0(_,"tailscale status --json");if(U.exitCode!==0)return $.push(`tailscale_status_failed:${U.stderr.trim()||U.exitCode}`),{peers:g,selfKey:null};let D=AM(U.stdout);if(!D)return $.push("tailscale_status_invalid_json"),{peers:g,selfKey:null};let I=(j)=>{let N=GR(j);if(N&&j)g.set(N,j)};I(D.Self);for(let j of Object.values(D.Peer??{}))I(j);return{peers:g,selfKey:GR(D.Self)}}function JM(_){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??_??u4()}function PM(_){let $=_.machineId===_.localMachineId||_.machineId===u4(),g=_.peer?.DNSName?.replace(/\.$/,"")??null,U=g??_.peer?.TailscaleIPs?.[0]??null,D=[];if($)D.push({kind:"local",target:"localhost",reachable:!0});if(U)D.push({kind:"tailscale",target:U,reachable:_.peer?.Online??null});let I=D.find((j)=>j.kind==="local")??D.find((j)=>j.kind==="tailscale")??null;return{machine_id:_.machineId,hostname:_.peer?.HostName??($?u4():_.machineId),local:$,platform:_.peer?.OS?fj(_.peer.OS):$?fj():null,os:_.peer?.OS??($?TR():null),user:$?IM().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:g,ips:_.peer?.TailscaleIPs??[],online:_.peer?.Online??null,active:_.peer?.Active??null,last_seen:_.peer?.LastSeen??null},ssh:{address:null,route:I?.kind==="local"?"local":I?.kind==="tailscale"?"tailscale":"unknown",command_target:I?.target??null},route_hints:D,tags:[],metadata:{},source:"local"}}function zM(_){if(!Array.isArray(_))return[];return _.map(($)=>{let g=n_($),U=d(g.kind)??"unknown";return{kind:U==="local"||U==="lan"||U==="tailscale"||U==="ssh"?U:"unknown",target:d(g.target)??"",reachable:vj(g.reachable)}}).filter(($)=>$.target.length>0)}function SM(_,$){let g=d(_.machine_id)??d(_.hostname)??"unknown",U=n_(_.tailscale),D=n_(_.ssh),I=d(_.heartbeat_status),j=d(D.route);return{machine_id:g,hostname:d(_.hostname),local:g===$,platform:d(_.platform),os:d(_.os),user:d(_.user),workspace_path:d(_.workspace_path),manifest_declared:_.manifest_declared===!0,heartbeat_status:I==="online"||I==="offline"?I:"unknown",last_heartbeat_at:d(_.last_heartbeat_at),tailscale:{dns_name:d(U.dns_name),ips:y6(U.ips),online:vj(U.online),active:vj(U.active),last_seen:d(U.last_seen)},ssh:{address:d(D.address),route:j==="local"||j==="lan"||j==="tailscale"?j:"unknown",command_target:d(D.command_target)},route_hints:zM(_.route_hints),tags:y6(_.tags),metadata:n_(_.metadata),source:"open-machines"}}function WM(_,$){return`${$} machine${$===1?"":"s"} discovered via ${_}`}function E$(_){let $=_ instanceof Error?_.message:String(_);return $.includes("Cannot find module '@hasna/machines'")||$.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":$}function IU(_){return _.adapterMode??"auto"}function qR(_){let $=_?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof $==="number")return $;let g=_?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof g==="number"?g:null}function wj(_){return typeof _.schema_version==="number"?_.schema_version:null}function jU(_){return typeof _==="number"&&_>jM?_:null}function uj(_){return{package:NM,entrypoint:EM,mode:_.mode,implementation:_.implementation,contract_version:_.contractVersion??null,available:_.available,error:_.error??null}}function j_(_,$="adapter_disabled"){return uj({mode:_,implementation:"disabled",available:!1,error:$})}function xj(_,$){let g=jU(qR($));if(!g)return null;return uj({mode:_,implementation:"disabled",available:!1,error:`unsupported_contract_version:${g}`,contractVersion:g})}function yj(_){return uj({mode:_,implementation:"cli",available:!0})}function hj(_,$){return uj({mode:_,implementation:"sdk",available:!0,contractVersion:qR($)})}function cj(_){try{return JSON.parse(_)}catch{return null}}function x4(_){return`'${_.replace(/'/g,"'\\''")}'`}function nj(_){return["machines",..._].map(x4).join(" ")}function dj(_){return _==="local"||_==="localhost"||_===u4()||_===process.env.HASNA_MACHINE_ID||_===process.env.OPEN_MACHINES_MACHINE_ID||_===process.env.MACHINE_ID}function XM(_,$){let g=dj(_),U=g?$:`ssh ${x4(_)} ${x4($)}`,D=QR("bash",["-c",U],{encoding:"utf8",env:process.env});return{stdout:D.stdout||"",stderr:D.stderr||"",exitCode:D.status??1,source:g?"local":"ssh"}}async function BR(_,$,g){return await _($,g)}function f4(_,$){if($)return"ok";return _===!1?"warn":"fail"}function w4(_){return _.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function RM(_){if(_==="@hasna/knowledge")return"knowledge";if(_==="@hasna/machines")return"machines";return _.split("/").pop()??_}function GM(_){return _.trim().split(/\r?\n/).find(Boolean)??""}function KR(_){return _.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function VR(_){let $={};for(let g of _.split(/\r?\n/)){let U=g.indexOf("=");if(U<=0)continue;$[g.slice(0,U)]=g.slice(U+1)}return $}function A6(_){return{id:_.id,kind:_.kind,status:_.status,target:_.target,expected:_.expected??null,actual:_.actual??null,detail:_.detail,source:_.source}}async function FR(_,$,g){let U=[`cmd=${x4($.command)}`,'path="$(command -v "$cmd" 2>/dev/null || true)"','printf "path=%s\\n" "$path"',`if [ -n "$path" ]; then version="$("$cmd" ${$.versionArgs??"--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi`].join("; "),D=await BR(g,_,U),I=VR(D.stdout);return{path:I.path||null,version:I.version?GM(I.version):null,stderr:D.stderr,source:D.source??(dj(_)?"local":"ssh")}}function YR(_){let $=_==="name"?String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`:String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`;return[`if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${_} ?? '')" "$pkg" 2>/dev/null`,`elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${_} || '')" "$pkg" 2>/dev/null`,`else sed -n '${$}' "$pkg" | head -n 1`,"fi"].join("; ")}async function YM(_,$,g){let U=[`path=${x4($.path)}`,'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"','pkg="$path/package.json"','printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"',`if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${YR("name")})"; printf "version=%s\\n" "$(${YR("version")})"; fi`].join("; "),D=await BR(g,_,U),I=VR(D.stdout);return{exists:I.exists==="yes",packageJson:I.package_json==="yes",packageName:I.package_name||null,version:I.version||null,stderr:D.stderr,source:D.source??(dj(_)?"local":"ssh")}}async function QM(_,$,g){let U=await FR(_,$,g),D=Boolean(U.path),I=[A6({id:`command:${w4($.command)}:path`,kind:"command",status:f4($.required,D),target:$.command,expected:"available",actual:U.path??"missing",detail:D?`found at ${U.path}`:U.stderr||"command missing",source:U.source})];if($.expectedVersion){let j=KR(U.version??"");I.push(A6({id:`command:${w4($.command)}:version`,kind:"command",status:j===$.expectedVersion?"ok":f4($.required,!1),target:$.command,expected:$.expectedVersion,actual:j??U.version??"missing",detail:j?`version output: ${U.version}`:"version unavailable",source:U.source}))}return I}async function TM(_,$,g){let U=$.command??RM($.name),D=await FR(_,{command:U,expectedVersion:$.expectedVersion,required:$.required},g),I=Boolean(D.path),j=[A6({id:`package:${w4($.name)}:command`,kind:"package",status:f4($.required,I),target:$.name,expected:U,actual:D.path??"missing",detail:I?`${U} found at ${D.path}`:`${U} command missing`,source:D.source})];if($.expectedVersion){let N=KR(D.version??"");j.push(A6({id:`package:${w4($.name)}:version`,kind:"package",status:N===$.expectedVersion?"ok":f4($.required,!1),target:$.name,expected:$.expectedVersion,actual:N??D.version??"missing",detail:N?`version output: ${D.version}`:"version unavailable",source:D.source}))}return j}async function qM(_,$,g){let U=await YM(_,$,g),D=$.label??$.path,I=[A6({id:`workspace:${w4(D)}:path`,kind:"workspace",status:f4($.required,U.exists),target:D,expected:$.path,actual:U.exists?"exists":"missing",detail:U.exists?`workspace exists at ${$.path}`:U.stderr||`workspace missing at ${$.path}`,source:U.source})];if($.expectedPackageName)I.push(A6({id:`workspace:${w4(D)}:package-name`,kind:"workspace",status:U.packageName===$.expectedPackageName?"ok":f4($.required,!1),target:D,expected:$.expectedPackageName,actual:U.packageName??(U.packageJson?"missing-name":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));if($.expectedVersion)I.push(A6({id:`workspace:${w4(D)}:version`,kind:"workspace",status:U.version===$.expectedVersion?"ok":f4($.required,!1),target:D,expected:$.expectedVersion,actual:U.version??(U.packageJson?"missing-version":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));return I}function MR(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:l$,workspace_home:$.knowledge?.workspace_home??null},message:WM(_.source,_.machines.length)}}async function mj(){try{return await import("@hasna/machines/consumer")}catch(_){if(E$(_)!=="module_not_found")throw _;return await import("@hasna/machines")}}function ZR(_,$,g){let U=n_(_);if(jU(wj(U)))return null;let D=Array.isArray(U.machines)?U.machines:null,I=d(U.local_machine_id);if(!D||!I)return null;let j={ok:!0,source:"open-machines",generated_at:d(U.generated_at)??($.now??new Date).toISOString(),local_machine_id:I,local_hostname:d(U.local_hostname)??u4(),current_platform:d(U.current_platform)??fj(),machines:D.map((N)=>SM(N,I)),warnings:y6(U.warnings),adapter:g};return MR(j,$)}function bj(_){return _==="local"||_==="lan"||_==="tailscale"||_==="ssh"||_==="unknown"?_:null}function bR(_){let $=n_(_),g=d($.observed_at),U=d($.source_authority);if(!g||!U)return null;return{observed_at:g,verified_at:d($.verified_at),expires_at:d($.expires_at),ttl_ms:OM($.ttl_ms),source_authority:U,confidence:d($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:y6($.reasons)}}function HR(_,$){let g=n_(_);if(jU(wj(g)))return null;let U=d(g.target)??d(g.command_target);if(g.ok!==!0||!U)return null;let D=typeof g.evidence==="object"&&g.evidence!==null?g.evidence:null,I=typeof D?.selected_hint==="object"&&D.selected_hint!==null?D.selected_hint:null;return{target:U,route:bj(g.route),targetKind:bj(I?.kind)??bj(g.source)??bj(g.route),confidence:d(g.confidence),source:"open-machines",adapter:$,evidence:D,cacheability:bR(g.cacheability),warnings:y6(g.warnings)}}function aP(_){let $=n_(_);return{path:d($.path),source:d($.source)??"unresolved"}}function BM(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let g=n_($),U=d(g.id),D=d(g.status),I=d(g.severity),j=d(g.message);if(!U||!D||!I||!j)return[];return[{id:U,status:D,severity:I,message:j,path:d(g.path),source:d(g.source)??"unknown",path_exists:vj(g.path_exists)}]})}function KM(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let g=n_($),U=d(g.id),D=d(g.reason),I=y6(g.command),j=d(g.shell_command),N=y6(g.apply_command),O=d(g.apply_shell_command);if(!U||!D||!I.length||!j||!N.length||!O)return[];return[{id:U,reason:D,command:I,shell_command:j,apply_command:N,apply_shell_command:O}]})}function VM(_){if(!(_.projectRootSource==="inferred"||_.openFilesRootSource==="inferred"||_.trustStatus==="untrusted"||_.authStatus==="unknown"||_.warnings.some((D)=>D.includes("inferred")||D.includes("untrusted")||D.includes("unknown_auth")||D.includes("missing"))))return[];let g=["machines","workspace","repair","--machine",_.requestedMachineId,"--project",_.projectId,"--repo",_.repoName,"--open-files-repo",_.openFilesRepoName??"open-files","--json"],U=[...g,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:g,shell_command:g.map(x4).join(" "),apply_command:U,apply_shell_command:U.map(x4).join(" ")}]}function kR(_,$,g){let U=n_(_);if(jU(wj(U)))return null;let D=n_(U.paths),I=n_(U.project),j=n_(U.machine),N=aP(D.project_root),O=aP(D.workspace_root),A=aP(D.open_files_root);if(U.ok!==!0||!N.path)return null;let L=typeof U.evidence==="object"&&U.evidence!==null?U.evidence:null,z=d(U.requested_machine_id)??$.machineId,W=d(I.project_id)??$.projectId??"open-knowledge",J=d(I.repo_name)??$.repoName??$.projectId??"open-knowledge",P=d(j.trust_status)??"unknown",S=d(j.auth_status)??"unknown",X=y6(U.warnings),G=BM(U.diagnostics),R=KM(U.repair_hints);return{ok:!0,source:"open-machines",adapter:g,requested_machine_id:z,machine_id:d(U.machine_id),project_id:W,repo_name:J,project_root:N.path,project_root_source:N.source,workspace_root:O.path,workspace_root_source:O.source,open_files_root:A.path,open_files_root_source:A.source,trust_status:P,auth_status:S,current:j.current===!0,primary:j.primary===!0,diagnostics:G,repair_hints:R.length?R:VM({requestedMachineId:z,projectId:W,repoName:J,openFilesRepoName:$.openFilesRepoName,warnings:X,projectRootSource:N.source,openFilesRootSource:A.source,trustStatus:P,authStatus:S}),evidence:L,cacheability:bR(U.cacheability),warnings:X}}async function Hj(_,$){let g=_.runner??DU;if(!await UU("machines",g))return null;let U=["topology","--json"];if(_.includeTailscale===!1)U.push("--no-tailscale");let D=await a0(g,nj(U));if(D.exitCode!==0)return null;return ZR(cj(D.stdout),_,$)}async function j6(_,$){let g=[];if($.error)g.push(`open_machines_unavailable:${$.error}`);let U=_.runner??DU,D=_.includeTailscale===!1?{peers:new Map,selfKey:null}:await LM(U,g),I=JM(D.selfKey),N=[...new Set([I,...D.peers.keys()])].sort().map((O)=>PM({machineId:O,localMachineId:I,peer:D.peers.get(O)}));return MR({ok:!0,source:"local",generated_at:(_.now??new Date).toISOString(),local_machine_id:I,local_hostname:u4(),current_platform:fj(),machines:N,warnings:g,adapter:$},_)}async function CR(_={}){let $=IU(_);if($==="disabled")return await j6(_,j_($));let g=yj($);try{if($!=="cli"){let D=await(_.loadOpenMachines??mj)(),I=xj($,D);if(I)return await j6(_,I);let j=hj($,D);if(D?.discoverMachineTopology){let N=D.discoverMachineTopology({includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),O=ZR(N,_,j);if(O)return O;if($==="sdk")return await j6(_,j_($,"invalid_topology_shape"));return await Hj(_,g)??await j6(_,j_($,"invalid_topology_shape"))}if($==="sdk")return await j6(_,j_($,"missing_discoverMachineTopology"));return await Hj(_,g)??await j6(_,j_($,"missing_discoverMachineTopology"))}return await Hj(_,g)??await j6(_,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return await j6(_,j_($,E$(U)));return await Hj(_,g)??await j6(_,j_($,E$(U)))}}async function kj(_,$){let g=_.runner??DU;if(!await UU("machines",g))return null;let U=["route","--machine",_.machineId,"--json"];if(_.includeTailscale===!1)U.push("--no-tailscale");let D=await a0(g,nj(U));if(D.exitCode!==0)return null;return HR(cj(D.stdout),$)}function N6(_,$){return{target:_,route:null,targetKind:null,confidence:null,source:"raw",adapter:$,evidence:null,cacheability:null,warnings:[]}}async function sP(_){let $=IU(_);if($==="disabled")return N6(_.machineId,j_($));let g=yj($);try{if($!=="cli"){let D=await(_.loadOpenMachines??mj)(),I=xj($,D);if(I)return N6(_.machineId,I);let j=hj($,D);if(D?.resolveMachineRoute){let N=HR(D.resolveMachineRoute(_.machineId,{includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),j);if(N)return N;if($==="sdk")return N6(_.machineId,j_($,"invalid_route_shape"));return await kj(_,g)??N6(_.machineId,j_($,"invalid_route_shape"))}if($==="sdk")return N6(_.machineId,j_($,"missing_resolveMachineRoute"));return await kj(_,g)??N6(_.machineId,j_($,"missing_resolveMachineRoute"))}return await kj(_,g)??N6(_.machineId,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return{...N6(_.machineId,j_($,E$(U))),warnings:[E$(U)]};return await kj(_,g)??{...N6(_.machineId,j_($,E$(U))),warnings:[E$(U)]}}}async function Cj(_,$){let g=_.runner??DU;if(!await UU("machines",g))return null;let U=_.projectId??"open-knowledge",D=_.repoName??"open-knowledge",I=["workspace","resolve","--machine",_.machineId,"--project",U,"--repo",D,"--open-files-repo",_.openFilesRepoName??"open-files","--json"];if(_.includeTailscale===!1)I.push("--no-tailscale");let j=await a0(g,nj(I));if(j.exitCode!==0)return null;return kR(cj(j.stdout),_,$)}function FM(_){let $=_.peerWorkspace?.trim();if(!$)return null;return{ok:!0,source:"argument",adapter:j_(IU(_),"argument_override"),requested_machine_id:_.machineId,machine_id:_.machineId,project_id:_.projectId??"open-knowledge",repo_name:_.repoName??"open-knowledge",project_root:$,project_root_source:"argument",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:[]}}function E6(_,$,g){return{ok:!1,source:"raw",adapter:g,requested_machine_id:_.machineId,machine_id:null,project_id:_.projectId??"open-knowledge",repo_name:_.repoName??"open-knowledge",project_root:null,project_root_source:"unresolved",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:$}}async function ij(_){let $=FM(_);if($)return $;let g=IU(_);if(g==="disabled")return E6(_,["adapter_disabled"],j_(g));let U=yj(g);try{if(g!=="cli"){let I=await(_.loadOpenMachines??mj)(),j=xj(g,I);if(j)return E6(_,[`unsupported_contract_version:${j.contract_version}`],j);let N=hj(g,I);if(I?.resolveMachineWorkspace){let O=kR(I.resolveMachineWorkspace({machineId:_.machineId,projectId:_.projectId??"open-knowledge",repoName:_.repoName??"open-knowledge",openFilesRepoName:_.openFilesRepoName??"open-files",includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),_,N);if(O)return O;if(g==="sdk")return E6(_,["invalid_workspace_shape"],j_(g,"invalid_workspace_shape"));return await Cj(_,U)??E6(_,["invalid_workspace_shape"],j_(g,"invalid_workspace_shape"))}if(g==="sdk")return E6(_,["missing_resolveMachineWorkspace"],j_(g,"missing_resolveMachineWorkspace"));return await Cj(_,U)??E6(_,["missing_resolveMachineWorkspace"],j_(g,"missing_resolveMachineWorkspace"))}return await Cj(_,U)??E6(_,["machines_cli_unavailable"],j_(g,"machines_cli_unavailable"))}catch(D){if(g==="sdk")return E6(_,[E$(D)],j_(g,E$(D)));return await Cj(_,U)??E6(_,[E$(D)],j_(g,E$(D)))}}function rR(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:l$,workspace_home:$.knowledge?.workspace_home??null},message:_.ok?`Machine ${_.machine_id} passed knowledge preflight`:`Machine ${_.machine_id} failed knowledge preflight: ${_.summary.fail} failing check(s)`}}function vR(_,$,g){let U=n_(_);if(jU(wj(U)))return null;let D=Array.isArray(U.checks)?U.checks:null,I=d(U.machine_id)??d(U.machineId);if(!D||!I)return null;let j=D.map((O)=>{let A=n_(O),L=d(A.status),z=d(A.kind),W=d(A.source);return A6({id:d(A.id)??"unknown",kind:z==="command"||z==="package"||z==="workspace"?z:"command",status:L==="ok"||L==="warn"||L==="fail"?L:"fail",target:d(A.target)??"unknown",expected:d(A.expected),actual:d(A.actual),detail:d(A.detail)??"",source:W==="local"||W==="ssh"||W==="open-machines"?W:"open-machines"})}),N={ok:j.filter((O)=>O.status==="ok").length,warn:j.filter((O)=>O.status==="warn").length,fail:j.filter((O)=>O.status==="fail").length};return rR({ok:N.fail===0,source:"open-machines",machine_id:I,generated_at:d(U.generated_at)??($.now??new Date).toISOString(),checks:j,summary:N,adapter:g},$)}function MM(_){if(!_.runner)return DU;return async($)=>{let g=await _.runner?.("local",$);return{stdout:g?.stdout??"",stderr:g?.stderr??"",exitCode:g?.exitCode??1}}}function ZM(_){return[_.name,_.command,_.expectedVersion].filter(($)=>Boolean($)).join(":")}function bM(_){let $=[_.expectedPackageName,_.expectedVersion].filter((U)=>Boolean(U)).join(":"),g=$?`${_.path}:${$}`:_.path;return _.label?`${_.label}=${g}`:g}async function rj(_,$){let g=MM(_);if(!await UU("machines",g))return null;let U=["compatibility","--json","--machine",_.machineId??"local"];for(let I of _.commands??[])U.push("--command",I.expectedVersion?`${I.command}:${I.expectedVersion}`:I.command);for(let I of _.packages??[])U.push("--package",ZM(I));for(let I of _.workspaces??[])U.push("--workspace",bM(I));let D=await a0(g,nj(U));if(D.exitCode!==0)return null;return vR(cj(D.stdout),_,$)}async function O6(_,$){let g=_.machineId??u4(),U=_.runner??XM,D=_.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],I=_.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],j=_.workspaces??[],N=[];for(let A of D)N.push(...await QM(g,A,U));for(let A of I)N.push(...await TM(g,A,U));for(let A of j)N.push(...await qM(g,A,U));if($.error)N.push(A6({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:$.error,detail:"Using knowledge local/ssh compatibility fallback",source:dj(g)?"local":"ssh"}));let O={ok:N.filter((A)=>A.status==="ok").length,warn:N.filter((A)=>A.status==="warn").length,fail:N.filter((A)=>A.status==="fail").length};return rR({ok:O.fail===0,source:"local",machine_id:g,generated_at:(_.now??new Date).toISOString(),checks:N,summary:O,adapter:$},_)}async function fR(_={}){let $=IU(_);if($==="disabled")return await O6(_,j_($));let g=yj($);try{if($!=="cli"){let D=await(_.loadOpenMachines??mj)(),I=xj($,D);if(I)return await O6(_,I);let j=hj($,D);if(D?.checkMachineCompatibility){let N=D.checkMachineCompatibility({machineId:_.machineId,commands:_.commands,packages:_.packages,workspaces:_.workspaces,runner:_.runner,now:_.now}),O=vR(N,_,j);if(O)return O;if($==="sdk")return await O6(_,j_($,"invalid_compatibility_shape"));return await rj(_,g)??await O6(_,j_($,"invalid_compatibility_shape"))}if($==="sdk")return await O6(_,j_($,"missing_checkMachineCompatibility"));return await rj(_,g)??await O6(_,j_($,"missing_checkMachineCompatibility"))}return await rj(_,g)??await O6(_,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return await O6(_,j_($,E$(U)));return await rj(_,g)??await O6(_,j_($,E$(U)))}}import{createHash as wR}from"crypto";function $3(_,$,g=24){return`${_}_${wR("sha256").update($).digest("hex").slice(0,g)}`}function s0(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function HM(_){return s0(_).toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")}function K$(_,$){try{return JSON.parse(_)}catch{return $}}function h6(_){return{..._,record_kind:_.record_kind,source_kind:_.source_kind,status:_.status,source_refs:K$(_.source_refs_json,[]),evidence_refs:K$(_.evidence_refs_json,[]),requires_approval:_.requires_approval===1,checks:K$(_.checks_json,uR()),metadata:K$(_.metadata_json,{})}}function g3(_){return{..._,record_kind:_.record_kind,source_refs:K$(_.source_refs_json,[]),evidence_refs:K$(_.evidence_refs_json,[]),metadata:K$(_.metadata_json,{})}}function uR(){return{citations:{provided:0,valid:0,invalid:0,entries:[]},invalid_source_refs:[],stale_refs:[],duplicate_record_ids:[],duplicate_candidate_ids:[],conflicting_record_ids:[],conflicting_candidate_ids:[],approval_reasons:[]}}function kM(_){let $=typeof _==="string"?{ref:_}:_;return{ref:s0($.ref),citation_id:$.citation_id??null,chunk_id:$.chunk_id??null,revision:$.revision??null,hash:$.hash??null,observed_at:$.observed_at??null,expires_at:$.expires_at??null,status:$.status??null}}function xR(_){try{let $=new URL(_);return $.protocol.length>1&&($.hostname.length>0||$.pathname.length>0)}catch{return/^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(_)}}function lj(_){return["deleted","stale","invalidated","reindex_required","expired","superseded"].includes((_??"").toLowerCase())}function _3(_){if(!_)return null;let $=K$(_,{});if($.stale===!0)return"stale";return typeof $.status==="string"?$.status:null}function CM(_){if(_.citation_id)return _.citation_id;return _.ref.match(/^(?:cite|citation):(.+)$/)?.[1]??null}function rM(_){if(_.chunk_id)return _.chunk_id;return _.ref.match(/^chunk:(.+)$/)?.[1]??null}function vM(_,$,g){let U=lj($.status)||Boolean($.expires_at&&$.expires_at<=g);if(!$.ref||!xR($.ref))return{ref:$.ref,valid:!1,resolved_by:"none",stale:U,reason:"invalid_reference"};let D=CM($),I=_.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, sr.source_id, sr.created_at AS revision_created_at, (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at @@ -970,46 +971,46 @@ ${JSON.stringify($.evidence,null,2)}`].join(` LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id WHERE c.id = ? OR c.source_uri = ? ORDER BY c.created_at DESC - LIMIT 1`).get(W,_.ref);if(X){let q=Boolean(_.hash&&X.revision_hash&&_.hash!==X.revision_hash),L=Boolean(_.revision&&X.revision&&_.revision!==X.revision),N=Boolean(X.revision_created_at&&X.latest_revision_at&&X.revision_created_at!kF(N)),G.citations.entries=U.map((N)=>cd($,N,J)),G.citations.provided=U.length,G.citations.valid=G.citations.entries.filter((N)=>N.valid).length,G.citations.invalid=G.citations.entries.length-G.citations.valid,G.stale_refs=G.citations.entries.filter((N)=>N.stale).map((N)=>N.ref),G.duplicate_record_ids=$.query(`SELECT id FROM durable_knowledge_records + WHERE ch.id = ?`).get(j);if(!A)return{ref:$.ref,valid:!1,resolved_by:"none",stale:U,reason:"chunk_not_found"};let L=Boolean($.hash&&A.hash&&$.hash!==A.hash||$.revision&&A.revision&&$.revision!==A.revision),z=U||lj(_3(A.metadata_json))||L;return{ref:$.ref,valid:!0,resolved_by:"chunk",stale:z,reason:L?"source_version_mismatch":z?"stale_chunk":null}}let N=_.query("SELECT metadata_json FROM sources WHERE uri = ? LIMIT 1").get($.ref);if(N){let A=U||lj(_3(N.metadata_json));return{ref:$.ref,valid:!0,resolved_by:"source",stale:A,reason:A?"stale_source":null}}let O=$.ref.match(/^knowledge:\/\/project\/runs\/([^/?#]+)/);if(O){if(!_.query("SELECT id FROM runs WHERE id = ?").get(decodeURIComponent(O[1])))return{ref:$.ref,valid:!1,resolved_by:"none",stale:U,reason:"run_not_found"};return{ref:$.ref,valid:!0,resolved_by:"run",stale:U,reason:U?"expired_evidence":null}}return{ref:$.ref,valid:!0,resolved_by:"external_uri",stale:U,reason:U?"expired_evidence":null}}function c6(_,$){return _.query("SELECT * FROM knowledge_promotion_candidates WHERE id = ?").get($)??null}function D3(_,$,g){let U=K$($.evidence_refs_json,[]),D=K$($.source_refs_json,[]),I=K$($.metadata_json,{}),j=uR();j.invalid_source_refs=D.filter((z)=>!xR(z)),j.citations.entries=U.map((z)=>vM(_,z,g)),j.citations.provided=U.length,j.citations.valid=j.citations.entries.filter((z)=>z.valid).length,j.citations.invalid=j.citations.entries.length-j.citations.valid,j.stale_refs=j.citations.entries.filter((z)=>z.stale).map((z)=>z.ref),j.duplicate_record_ids=_.query(`SELECT id FROM durable_knowledge_records WHERE record_kind = ? AND content_hash = ? AND status IN ('active', 'conflicted') - ORDER BY created_at`).all(_.record_kind,_.content_hash).map((N)=>N.id),G.duplicate_candidate_ids=$.query(`SELECT id FROM knowledge_promotion_candidates + ORDER BY created_at`).all($.record_kind,$.content_hash).map((z)=>z.id),j.duplicate_candidate_ids=_.query(`SELECT id FROM knowledge_promotion_candidates WHERE id <> ? AND record_kind = ? AND content_hash = ? AND status NOT IN ('rejected') - ORDER BY created_at`).all(_.id,_.record_kind,_.content_hash).map((N)=>N.id),G.conflicting_record_ids=$.query(`SELECT id FROM durable_knowledge_records + ORDER BY created_at`).all($.id,$.record_kind,$.content_hash).map((z)=>z.id),j.conflicting_record_ids=_.query(`SELECT id FROM durable_knowledge_records WHERE record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('active', 'conflicted') - ORDER BY created_at`).all(_.record_kind,_.canonical_key,_.content_hash).map((N)=>N.id),G.conflicting_candidate_ids=$.query(`SELECT id FROM knowledge_promotion_candidates + ORDER BY created_at`).all($.record_kind,$.canonical_key,$.content_hash).map((z)=>z.id),j.conflicting_candidate_ids=_.query(`SELECT id FROM knowledge_promotion_candidates WHERE id <> ? AND record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('ready', 'needs_approval', 'promoted') - ORDER BY created_at`).all(_.id,_.record_kind,_.canonical_key,_.content_hash).map((N)=>N.id);let Y=G.duplicate_record_ids[0]??G.duplicate_candidate_ids[0]??null,Q=W.length===0||U.length===0||G.invalid_source_refs.length>0||G.citations.invalid>0;if(_.record_kind==="decision"||_.record_kind==="claim")G.approval_reasons.push(`${_.record_kind}_requires_review`);if(X.requested_approval===!0)G.approval_reasons.push("explicit_approval_request");if(G.stale_refs.length>0)G.approval_reasons.push("stale_evidence");if(G.conflicting_record_ids.length>0||G.conflicting_candidate_ids.length>0)G.approval_reasons.push("conflicting_knowledge");let q=G.approval_reasons.length>0,L=Y?"duplicate":Q?"blocked":q?"needs_approval":"ready";return $.run(`UPDATE knowledge_promotion_candidates + ORDER BY created_at`).all($.id,$.record_kind,$.canonical_key,$.content_hash).map((z)=>z.id);let N=j.duplicate_record_ids[0]??j.duplicate_candidate_ids[0]??null,O=D.length===0||U.length===0||j.invalid_source_refs.length>0||j.citations.invalid>0;if($.record_kind==="decision"||$.record_kind==="claim")j.approval_reasons.push(`${$.record_kind}_requires_review`);if(I.requested_approval===!0)j.approval_reasons.push("explicit_approval_request");if(j.stale_refs.length>0)j.approval_reasons.push("stale_evidence");if(j.conflicting_record_ids.length>0||j.conflicting_candidate_ids.length>0)j.approval_reasons.push("conflicting_knowledge");let A=j.approval_reasons.length>0,L=N?"duplicate":O?"blocked":A?"needs_approval":"ready";return _.run(`UPDATE knowledge_promotion_candidates SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? - WHERE id = ?`,[L,q?1:0,JSON.stringify(G),Y,J,J,_.id]),u0(d0($,_.id))}function IF($,_){let J=["lesson","decision","claim"],U=["memento","session","report"];if(!J.includes(_.kind))throw Error("Promotion kind must be lesson, decision, or claim.");if(!U.includes(_.sourceKind))throw Error("Promotion source kind must be memento, session, or report.");let W=k_(NW(_.title)),X=k_(NW(_.content));if(!W.text)throw Error("Promotion title is required.");if(!X.text)throw Error("Promotion content is required.");let G=Array.from(new Set(_.sourceRefs.map(NW).filter(Boolean))).sort(),Y=_.evidenceRefs.map(ud).filter((V)=>V.ref.length>0).sort((V,K)=>V.ref.localeCompare(K.ref)),Q=xd(_.canonicalKey??W.text);if(!Q)throw Error("Promotion canonical key is empty after normalization.");let q=`sha256:${wF("sha256").update(`${_.kind}\x00${NW(X.text).toLowerCase()}`).digest("hex")}`,L=ML("promote",[_.sourceKind,_.kind,Q,q,...G].join("\x00")),N=ML("promotion",L),R=(_.now??new Date).toISOString(),B={..._.metadata??{},requested_approval:_.requiresApproval===!0,confidence:_.confidence??null,valid_from:_.validFrom??R,valid_to:_.validTo??null,redactions:W.findings.length+X.findings.length};a($);let H=m($);try{let V=H.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(L);if(V)return{created:!1,candidate:u0(V)};H.run(`INSERT INTO knowledge_promotion_candidates ( + WHERE id = ?`,[L,A?1:0,JSON.stringify(j),N,g,g,$.id]),h6(c6(_,$.id))}function yR(_,$){let g=["lesson","decision","claim"],U=["memento","session","report"];if(!g.includes($.kind))throw Error("Promotion kind must be lesson, decision, or claim.");if(!U.includes($.sourceKind))throw Error("Promotion source kind must be memento, session, or report.");let D=u_(s0($.title)),I=u_(s0($.content));if(!D.text)throw Error("Promotion title is required.");if(!I.text)throw Error("Promotion content is required.");let j=Array.from(new Set($.sourceRefs.map(s0).filter(Boolean))).sort(),N=$.evidenceRefs.map(kM).filter((S)=>S.ref.length>0).sort((S,X)=>S.ref.localeCompare(X.ref)),O=HM($.canonicalKey??D.text);if(!O)throw Error("Promotion canonical key is empty after normalization.");let A=`sha256:${wR("sha256").update(`${$.kind}\x00${s0(I.text).toLowerCase()}`).digest("hex")}`,L=$3("promote",[$.sourceKind,$.kind,O,A,...j].join("\x00")),z=$3("promotion",L),W=($.now??new Date).toISOString(),J={...$.metadata??{},requested_approval:$.requiresApproval===!0,confidence:$.confidence??null,valid_from:$.validFrom??W,valid_to:$.validTo??null,redactions:D.findings.length+I.findings.length};h(_);let P=v(_);try{let S=P.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(L);if(S)return{created:!1,candidate:h6(S)};P.run(`INSERT INTO knowledge_promotion_candidates ( id, record_kind, title, content, canonical_key, content_hash, source_kind, source_refs_json, evidence_refs_json, status, requires_approval, checks_json, idempotency_key, metadata_json, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`,[N,_.kind,W.text,X.text,Q,q,_.sourceKind,JSON.stringify(G),JSON.stringify(Y),L,JSON.stringify(B),R,R]);let K=[...W.findings,...X.findings];if(K.length>0)CJ(H,{source_uri:G[0]??`knowledge://promotion/${N}`,findings:K,metadata:{promotion_candidate_id:N},created_at:R});return __(H,{event_type:"knowledge_promotion",action:"enqueue_promotion",target_uri:`knowledge://promotion/${N}`,decision:"info",metadata:{record_kind:_.kind,source_kind:_.sourceKind,source_refs:G},created_at:R}),{created:!0,candidate:bL(H,d0(H,N),R)}}finally{H.close()}}function fF($,_){a($);let J=m($);try{let U=d0(J,_);return U?u0(U):null}finally{J.close()}}function CF($,_={}){a($);let J=Math.max(1,Math.min(_.limit??50,200)),U=[],W=[];if(_.status==="inbox"||!_.status)U.push("status IN ('ready', 'needs_approval', 'blocked')");else U.push("status = ?"),W.push(_.status);if(_.kind)U.push("record_kind = ?"),W.push(_.kind);let X=m($);try{return X.query(`SELECT * FROM knowledge_promotion_candidates + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`,[z,$.kind,D.text,I.text,O,A,$.sourceKind,JSON.stringify(j),JSON.stringify(N),L,JSON.stringify(J),W,W]);let X=[...D.findings,...I.findings];if(X.length>0)P0(P,{source_uri:j[0]??`knowledge://promotion/${z}`,findings:X,metadata:{promotion_candidate_id:z},created_at:W});return X_(P,{event_type:"knowledge_promotion",action:"enqueue_promotion",target_uri:`knowledge://promotion/${z}`,decision:"info",metadata:{record_kind:$.kind,source_kind:$.sourceKind,source_refs:j},created_at:W}),{created:!0,candidate:D3(P,c6(P,z),W)}}finally{P.close()}}function hR(_,$){h(_);let g=v(_);try{let U=c6(g,$);return U?h6(U):null}finally{g.close()}}function cR(_,$={}){h(_);let g=Math.max(1,Math.min($.limit??50,200)),U=[],D=[];if($.status==="inbox"||!$.status)U.push("status IN ('ready', 'needs_approval', 'blocked')");else U.push("status = ?"),D.push($.status);if($.kind)U.push("record_kind = ?"),D.push($.kind);let I=v(_);try{return I.query(`SELECT * FROM knowledge_promotion_candidates WHERE ${U.join(" AND ")} ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(...W,J).map(u0)}finally{X.close()}}function PF($,_,J=new Date){a($);let U=m($);try{let W=d0(U,_);if(!W)throw Error(`Promotion candidate not found: ${_}`);if(W.status==="promoted"||W.status==="rejected")return u0(W);return bL(U,W,J.toISOString())}finally{U.close()}}function TF($,_,J={}){a($);let U=m($),W=(J.now??new Date).toISOString();try{let X=d0(U,_);if(!X)throw Error(`Promotion candidate not found: ${_}`);if(X.status==="promoted"&&X.promoted_record_id){let B=U.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(X.promoted_record_id);return{ok:!0,promoted:!1,requires_approval:X.requires_approval===1,candidate:u0(X),record:B?AL(B):null,approval_id:null,reason:"already_promoted"}}if(X.status==="rejected")throw Error(`Promotion candidate ${_} was rejected.`);let G=bL(U,X,W);if(G.status==="duplicate")return{ok:!0,promoted:!1,requires_approval:!1,candidate:G,record:null,approval_id:null,reason:"duplicate"};if(G.status==="blocked")return{ok:!1,promoted:!1,requires_approval:!1,candidate:G,record:null,approval_id:null,reason:"citation_check_failed"};if(G.requires_approval&&!J.approveWrite)return{ok:!1,promoted:!1,requires_approval:!0,candidate:G,record:null,approval_id:null,reason:"approval_required"};if(G.requires_approval&&!J.approvedBy?.trim())throw Error("Promotion approval requires --approved-by .");let Y=G.requires_approval?J.approvedBy.trim():null,Q=null;if(G.requires_approval)Q=u9(U,{action:"promote_durable_knowledge",target_uri:`knowledge://promotion/${G.id}`,reason:G.checks.approval_reasons.join(", "),approved_by:Y,metadata:{promotion_candidate_id:G.id,checks:G.checks},created_at:W}).id;let q=ML("durable",G.id),L={...G.metadata,promotion_candidate_id:G.id,source_kind:G.source_kind,checks:G.checks,approval_id:Q,provenance:X6({generated_from:`knowledge://promotion/${G.id}`,artifact_key:`durable/${G.record_kind}/${G.canonical_key}`,source_refs:G.source_refs,citation_required:!0})};U.run(`INSERT INTO durable_knowledge_records ( + LIMIT ?`).all(...D,g).map(h6)}finally{I.close()}}function nR(_,$,g=new Date){h(_);let U=v(_);try{let D=c6(U,$);if(!D)throw Error(`Promotion candidate not found: ${$}`);if(D.status==="promoted"||D.status==="rejected")return h6(D);return D3(U,D,g.toISOString())}finally{U.close()}}function dR(_,$,g={}){h(_);let U=v(_),D=(g.now??new Date).toISOString();try{let I=c6(U,$);if(!I)throw Error(`Promotion candidate not found: ${$}`);if(I.status==="promoted"&&I.promoted_record_id){let J=U.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(I.promoted_record_id);return{ok:!0,promoted:!1,requires_approval:I.requires_approval===1,candidate:h6(I),record:J?g3(J):null,approval_id:null,reason:"already_promoted"}}if(I.status==="rejected")throw Error(`Promotion candidate ${$} was rejected.`);let j=D3(U,I,D);if(j.status==="duplicate")return{ok:!0,promoted:!1,requires_approval:!1,candidate:j,record:null,approval_id:null,reason:"duplicate"};if(j.status==="blocked")return{ok:!1,promoted:!1,requires_approval:!1,candidate:j,record:null,approval_id:null,reason:"citation_check_failed"};if(j.requires_approval&&!g.approveWrite)return{ok:!1,promoted:!1,requires_approval:!0,candidate:j,record:null,approval_id:null,reason:"approval_required"};if(j.requires_approval&&!g.approvedBy?.trim())throw Error("Promotion approval requires --approved-by .");let N=j.requires_approval?g.approvedBy.trim():null,O=null;if(j.requires_approval)O=mU(U,{action:"promote_durable_knowledge",target_uri:`knowledge://promotion/${j.id}`,reason:j.checks.approval_reasons.join(", "),approved_by:N,metadata:{promotion_candidate_id:j.id,checks:j.checks},created_at:D}).id;let A=$3("durable",j.id),L={...j.metadata,promotion_candidate_id:j.id,source_kind:j.source_kind,checks:j.checks,approval_id:O,provenance:U$({generated_from:`knowledge://promotion/${j.id}`,artifact_key:`durable/${j.record_kind}/${j.canonical_key}`,source_refs:j.source_refs,citation_required:!0})};U.run(`INSERT INTO durable_knowledge_records ( id, record_kind, title, content, canonical_key, content_hash, status, source_refs_json, evidence_refs_json, confidence, valid_from, valid_to, promoted_from_candidate_id, approved_by, metadata_json, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[q,G.record_kind,G.title,G.content,G.canonical_key,G.content_hash,G.checks.conflicting_record_ids.length>0?"conflicted":"active",JSON.stringify(G.source_refs),JSON.stringify(G.evidence_refs),typeof G.metadata.confidence==="number"?G.metadata.confidence:null,typeof G.metadata.valid_from==="string"?G.metadata.valid_from:W,typeof G.metadata.valid_to==="string"?G.metadata.valid_to:null,G.id,Y,JSON.stringify(L),W,W]),U.run(`UPDATE knowledge_promotion_candidates + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[A,j.record_kind,j.title,j.content,j.canonical_key,j.content_hash,j.checks.conflicting_record_ids.length>0?"conflicted":"active",JSON.stringify(j.source_refs),JSON.stringify(j.evidence_refs),typeof j.metadata.confidence==="number"?j.metadata.confidence:null,typeof j.metadata.valid_from==="string"?j.metadata.valid_from:D,typeof j.metadata.valid_to==="string"?j.metadata.valid_to:null,j.id,N,JSON.stringify(L),D,D]),U.run(`UPDATE knowledge_promotion_candidates SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? - WHERE id = ?`,[Y,q,W,W,G.id]),__(U,{event_type:"knowledge_promotion",action:"promote_durable_knowledge",target_uri:`knowledge://durable/${q}`,decision:"allow",metadata:{promotion_candidate_id:G.id,approval_id:Q,source_refs:G.source_refs},created_at:W});let N=u0(d0(U,G.id)),R=U.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(q);return{ok:!0,promoted:!0,requires_approval:G.requires_approval,candidate:N,record:AL(R),approval_id:Q,reason:null}}finally{U.close()}}function SF($,_,J={}){a($);let U=m($),W=(J.now??new Date).toISOString();try{let X=d0(U,_);if(!X)throw Error(`Promotion candidate not found: ${_}`);if(X.status==="promoted")throw Error(`Promotion candidate ${_} is already promoted.`);return U.run(`UPDATE knowledge_promotion_candidates + WHERE id = ?`,[N,A,D,D,j.id]),X_(U,{event_type:"knowledge_promotion",action:"promote_durable_knowledge",target_uri:`knowledge://durable/${A}`,decision:"allow",metadata:{promotion_candidate_id:j.id,approval_id:O,source_refs:j.source_refs},created_at:D});let z=h6(c6(U,j.id)),W=U.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(A);return{ok:!0,promoted:!0,requires_approval:j.requires_approval,candidate:z,record:g3(W),approval_id:O,reason:null}}finally{U.close()}}function mR(_,$,g={}){h(_);let U=v(_),D=(g.now??new Date).toISOString();try{let I=c6(U,$);if(!I)throw Error(`Promotion candidate not found: ${$}`);if(I.status==="promoted")throw Error(`Promotion candidate ${$} is already promoted.`);return U.run(`UPDATE knowledge_promotion_candidates SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? - WHERE id = ?`,[J.rejectedBy?.trim()||null,W,W,_]),__(U,{event_type:"knowledge_promotion",action:"reject_promotion",target_uri:`knowledge://promotion/${_}`,decision:"deny",metadata:{rejected_by:J.rejectedBy??null},created_at:W}),u0(d0(U,_))}finally{U.close()}}function ZF($,_={}){a($);let J=[],U=[];if(_.kind)J.push("record_kind = ?"),U.push(_.kind);if(_.status)J.push("status = ?"),U.push(_.status);let W=Math.max(1,Math.min(_.limit??50,200)),X=m($);try{return X.query(`SELECT * FROM durable_knowledge_records - ${J.length?`WHERE ${J.join(" AND ")}`:""} + WHERE id = ?`,[g.rejectedBy?.trim()||null,D,D,$]),X_(U,{event_type:"knowledge_promotion",action:"reject_promotion",target_uri:`knowledge://promotion/${$}`,decision:"deny",metadata:{rejected_by:g.rejectedBy??null},created_at:D}),h6(c6(U,$))}finally{U.close()}}function iR(_,$={}){h(_);let g=[],U=[];if($.kind)g.push("record_kind = ?"),U.push($.kind);if($.status)g.push("status = ?"),U.push($.status);let D=Math.max(1,Math.min($.limit??50,200)),I=v(_);try{return I.query(`SELECT * FROM durable_knowledge_records + ${g.length?`WHERE ${g.join(" AND ")}`:""} ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(...U,W).map(AL)}finally{X.close()}}import{createHash as id,randomUUID as vF}from"crypto";function ld($,_){return`${$}_${id("sha256").update(_).digest("hex").slice(0,20)}`}function rd($){let _=m($);try{let J=_.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(J.map((U)=>[U.status,U.n]))}finally{_.close()}}function yF($,_){let J=k1(_.modelRef,_.config),U=w_(J),W=m($);try{return W.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri + LIMIT ?`).all(...U,D).map(g3)}finally{I.close()}}import{createHash as fM,randomUUID as lR}from"crypto";function wM(_,$){return`${_}_${fM("sha256").update($).digest("hex").slice(0,20)}`}function uM(_){let $=v(_);try{let g=$.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(g.map((U)=>[U.status,U.n]))}finally{$.close()}}function tR(_,$){let g=I4($.modelRef,$.config),U=f_(g),D=v(_);try{return D.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri FROM chunks c LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id LEFT JOIN sources s ON s.id = sr.source_id LEFT JOIN vector_index_entries v ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? WHERE v.id IS NULL - ORDER BY c.created_at ASC, c.ordinal ASC`).all(U.provider,U.model)}finally{W.close()}}function hF($){a($.dbPath);let _=m($.dbPath);try{let J=_.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0,U=_.query("SELECT COUNT(*) AS n FROM chunks").get()?.n??0,W=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,X=yF($.dbPath,$).length,G=_.query(`SELECT COUNT(*) AS n FROM source_revisions - WHERE metadata_json LIKE '%"reindex_required":true%' OR metadata_json LIKE '%"status":"stale"%'`).get()?.n??0;return{schema_version:J,chunks:U,vector_entries:W,missing_embeddings:X,queued:rd($.dbPath),stale_revisions:G}}finally{_.close()}}function wL($){a($.dbPath);let _=($.now??new Date).toISOString(),J=$.reason??"missing_embedding",U=yF($.dbPath,$),W=m($.dbPath),X=0,G=0;try{W.transaction(()=>{for(let Q of U){let q=ld("rq",`embedding\x00${Q.chunk_id}\x00${J}`);if(W.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding",Q.chunk_id,J)){G+=1;continue}W.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[q,"embedding",Q.chunk_id,Q.source_uri,J,"pending",JSON.stringify({source_revision_id:Q.source_revision_id}),_,_]),X+=1}})()}finally{W.close()}return{enqueued:X,already_queued:G,reason:J}}function pd($){let _=m($);try{let J=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0;return _.run("DELETE FROM vector_index_entries"),_.run("DELETE FROM chunk_embeddings"),{embeddings:J,vectorEntries:U}}finally{_.close()}}function od($,_,J){let U=k1(_.modelRef,_.config),W=w_(U),X=m($);try{return X.run(`UPDATE reindex_queue + ORDER BY c.created_at ASC, c.ordinal ASC`).all(U.provider,U.model)}finally{D.close()}}function oR(_){h(_.dbPath);let $=v(_.dbPath);try{let g=$.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0,U=$.query("SELECT COUNT(*) AS n FROM chunks").get()?.n??0,D=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,I=tR(_.dbPath,_).length,j=$.query(`SELECT COUNT(*) AS n FROM source_revisions + WHERE metadata_json LIKE '%"reindex_required":true%' OR metadata_json LIKE '%"status":"stale"%'`).get()?.n??0;return{schema_version:g,chunks:U,vector_entries:D,missing_embeddings:I,queued:uM(_.dbPath),stale_revisions:j}}finally{$.close()}}function U3(_){h(_.dbPath);let $=(_.now??new Date).toISOString(),g=_.reason??"missing_embedding",U=tR(_.dbPath,_),D=v(_.dbPath),I=0,j=0;try{D.transaction(()=>{for(let O of U){let A=wM("rq",`embedding\x00${O.chunk_id}\x00${g}`);if(D.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding",O.chunk_id,g)){j+=1;continue}D.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[A,"embedding",O.chunk_id,O.source_uri,g,"pending",JSON.stringify({source_revision_id:O.source_revision_id}),$,$]),I+=1}})()}finally{D.close()}return{enqueued:I,already_queued:j,reason:g}}function xM(_){let $=v(_);try{let g=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0;return $.run("DELETE FROM vector_index_entries"),$.run("DELETE FROM chunk_embeddings"),{embeddings:g,vectorEntries:U}}finally{$.close()}}function yM(_,$,g){let U=I4($.modelRef,$.config),D=f_(U),I=v(_);try{return I.run(`UPDATE reindex_queue SET status = ?, updated_at = ? WHERE kind = ? AND status = ? @@ -1018,13 +1019,13 @@ ${JSON.stringify($.evidence,null,2)}`].join(` WHERE v.chunk_id = reindex_queue.target_id AND v.provider = ? AND v.model = ? - )`,["completed",J,"embedding","pending",W.provider,W.model]).changes}finally{X.close()}}async function mF($){a($.dbPath);let _=($.now??new Date).toISOString(),J=`run_${vF()}`,U=$.full?pd($.dbPath):{embeddings:0,vectorEntries:0},W=wL({...$,reason:$.full?"full_embedding_rebuild":"missing_embedding"}),X=m($.dbPath);try{X.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[J,"embedding-refresh",$.full?"full":"incremental","running","local",k1($.modelRef,$.config),JSON.stringify({full:$.full===!0,queued:W}),_,_])}finally{X.close()}let G=await o9({dbPath:$.dbPath,config:$.config,env:$.env,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake,limit:$.limit,now:$.now}),Y=od($.dbPath,$,_),Q=m($.dbPath);try{Q.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({full:$.full===!0,queued:W,indexed:G,completed_queue_items:Y}),_,J]),Q.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${vF()}`,J,"info","embedding_refresh_completed",JSON.stringify({queued:W,indexed:G,completed_queue_items:Y}),_])}finally{Q.close()}return{run_id:J,full:$.full===!0,deleted_embeddings:U.embeddings,deleted_vector_entries:U.vectorEntries,queued:W,indexed:G,completed_queue_items:Y}}import{createHash as dF}from"crypto";import{existsSync as nF,lstatSync as td,readdirSync as ad,readFileSync as sd,statSync as ed}from"fs";import{basename as VW,extname as $n,join as _n,relative as Jn,resolve as fL,sep as Wn}from"path";import{pathToFileURL as xF}from"url";var Un=100,Xn=25,Gn=262144,Yn=5,Qn=new Set([".md",".mdx",".txt",".json",".jsonc",".toml",".yaml",".yml"]),gL=new Set(["CODEWITH.md","AGENTS.md","CLAUDE.md","RULES.md","INSTRUCTIONS.md"]),qn=new Set([".git","node_modules","dist","build",".codewith-worktrees",".connect",".secrets",".tmp","tmp","auth_profiles","profiles","preserved","backup","backups","cache","logs","runs"]),zn=/(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i,cG=/(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i;function kL($){return`sha256:${dF("sha256").update($).digest("hex")}`}function jn($){return`sha256:${dF("sha256").update($).digest("hex")}`}function iX($){return $.split(Wn).join("/")}function IL($,_){let J=Jn($,_);return J?iX(J):VW(_)}function n0($){return Qn.has($n($).toLowerCase())}function uF($){return iX($).split("/").some((_)=>zn.test(_))}function cF($,_=220){let J=$.normalize("NFKC").trim().replace(/\s+/g," ");if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-1)).trim()}...`}function iF($){if(!$)return 0;return $.split(/\r\n|\n|\r/).length}function lF($){return{source_ref:$.sourceRef,source_path:$.sourcePath,line_start:$.lineCount>0?1:0,line_end:$.lineCount,content_hash:$.contentHash}}function Dn(){return[{base:".",maxDepth:0,spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:10,label:"root-rule-doc"},tags:["global-rules","rule-doc"],include:($)=>gL.has($)}},{base:".codewith",spec:{family:"codewith",owner:"codewith",scope:"global",precedence:{rank:20,label:"codewith"},tags:["global-rules","codewith","agent-instructions"],include:($)=>{let _=iX($),J=VW(_);if(gL.has(J)||_==="config.toml")return!0;if(_.endsWith("/SKILL.md"))return!0;if(/^(rules|instructions|prompts|plans)\//.test(_)&&n0(_))return!0;return!1}}},{base:".claude",spec:{family:"claude",owner:"claude",scope:"global",precedence:{rank:30,label:"claude-rules"},tags:["global-rules","claude","agent-instructions"],include:($)=>{let _=iX($);return _==="CLAUDE.md"||/^rules\//.test(_)&&n0(_)}}},{base:".codex",spec:{family:"codex",owner:"codex",scope:"global",precedence:{rank:40,label:"codex"},tags:["global-rules","codex","agent-instructions"],include:($)=>{let _=iX($),J=VW(_);if(gL.has(J)||J==="config.toml")return!0;return/^(rules|instructions|prompts)\//.test(_)&&n0(_)}}},{base:".opencode",spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode"},tags:["global-rules","opencode","agent-instructions"],include:($)=>cG.test($)&&n0($)}},{base:".",maxDepth:0,spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode-config"},tags:["global-rules","opencode","config"],include:($)=>["opencode.json","opencode.jsonc","opencode.toml","opencode.yaml","opencode.yml"].includes($)}},{base:".hasna/prompts",spec:{family:"prompt",owner:"hasna",scope:"global",precedence:{rank:60,label:"selected-prompts"},tags:["global-rules","prompt"],include:($)=>cG.test($)&&n0($)}},{base:".hasna/plans",spec:{family:"plan",owner:"hasna",scope:"global",precedence:{rank:65,label:"selected-plans"},tags:["global-rules","plan"],include:($)=>cG.test($)&&n0($)}},{base:"docs",spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:70,label:"rule-docs"},tags:["global-rules","rule-doc"],include:($)=>cG.test($)&&n0($)}}]}function On($,_){let J=new Map;for(let U of Dn()){let W=fL($,U.base);if(!nF(W))continue;if(ed(W).isFile()){let G=VW(W);if(U.spec.include(G))J.set(W,{...U.spec,absPath:W});continue}rF({basePath:W,depth:0,maxDepth:U.maxDepth??Yn,spec:U.spec,candidates:J,skipped:_})}return[...J.values()].sort((U,W)=>{if(U.precedence.rank!==W.precedence.rank)return U.precedence.rank-W.precedence.rank;return U.absPath.localeCompare(W.absPath)})}function rF($){let _=$.rootBasePath??$.basePath;if($.depth>$.maxDepth)return;for(let J of ad($.basePath,{withFileTypes:!0})){let U=_n($.basePath,J.name),W=IL(_,U);if(J.isSymbolicLink())continue;if(J.isDirectory()){if(qn.has(J.name))continue;if(uF(W)){$.skipped.push({source_family:$.spec.family,source_path:U,reason:"sensitive_path"});continue}rF({...$,rootBasePath:_,basePath:U,depth:$.depth+1});continue}if(!J.isFile())continue;let X=IL(fL(_),U);if(uF(X)){$.skipped.push({source_family:$.spec.family,source_path:U,reason:"sensitive_path"});continue}if(!$.spec.include(X))continue;if(!n0(U))continue;$.candidates.set(U,{...$.spec,absPath:U})}}function Ln($){if(($.tags??[]).map((U)=>U.toLowerCase()).some((U)=>["rule","rules","agent","instructions","global-rules","global-agent-rules"].includes(U)))return!0;let J=`${$.title} -${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(J)}function pF($,_){let J={source_path:$.source_path,source_path_ref:$.source_path_ref,source_ref:$.source_ref,owner:$.owner,scope:$.scope,precedence:$.precedence,source_hash:$.source_hash,content_hash:$.content_hash,discovered_at:$.discovered_at,tags:$.tags,redaction_status:$.redaction_status,citations:$.citations};return{source_ref:$.source_ref,name:$.title,mime:"text/markdown",size:Buffer.byteLength(_),hash:$.content_hash,revision:$.content_hash,status:"active",updated_at:$.discovered_at,permissions:{mode:"read_only",allowed_purposes:["knowledge_index","knowledge_answer","agent_context"]},rule_provenance:J,source_family:$.source_family,source_path_ref:$.source_path_ref,owner:$.owner,scope:$.scope,precedence:$.precedence,tags:$.tags,redaction_status:$.redaction_status,legacy_json_id:$.legacy_json_id??null,extracted_text:_}}function Bn($){let _=td($.candidate.absPath),J=$.candidate.absPath,U=IL($.root,J);if(_.size>$.maxBytesPerFile){let B=xF(J).href;return{evidence:{source_family:$.candidate.family,title:VW(J),source_path:J,source_path_ref:U,source_ref:B,owner:$.candidate.owner,scope:$.candidate.scope,precedence:$.candidate.precedence,source_hash:"sha256:skipped-too-large",content_hash:"sha256:skipped-too-large",discovered_at:$.discoveredAt,tags:[...$.candidate.tags,"skipped"],redaction_status:"refused",redactions:[],citations:[],bytes:_.size,line_count:0,importable:!1,skipped_reason:"max_bytes_exceeded",preview:null},text:"",manifest:null}}let W=sd(J),X=W.toString("utf8"),G=k_(X,$.safetyPolicy),Q=G.findings.some((B)=>B.severity==="high")?"refused":G.findings.length>0?"redacted":"clean",q=kL(G.text),L=xF(J).href,N=iF(G.text),R={source_family:$.candidate.family,title:VW(J),source_path:J,source_path_ref:U,source_ref:L,owner:$.candidate.owner,scope:$.candidate.scope,precedence:$.candidate.precedence,source_hash:jn(W),content_hash:q,discovered_at:$.discoveredAt,tags:[...$.candidate.tags],redaction_status:Q,redactions:G.findings.map((B)=>({type:B.type,severity:B.severity})),citations:[lF({sourceRef:L,sourcePath:J,lineCount:N,contentHash:q})],bytes:W.byteLength,line_count:N,importable:Q!=="refused",skipped_reason:Q==="refused"?"secret_refused":null,preview:Q==="refused"?null:cF(G.text)};return{evidence:R,text:G.text,manifest:R.importable?pF(R,G.text):null}}function Hn($){let _=k_($.item.content,$.safetyPolicy),U=_.findings.some((q)=>q.severity==="high")?"refused":_.findings.length>0?"redacted":"clean",W=`open-files://source/legacy-json/path/${encodeURIComponent($.item.id)}`,X=kL(_.text),G=kL($.item.content),Y=iF(_.text),Q={source_family:"legacy_json",title:$.item.title,source_path:$.legacyStorePath,source_path_ref:`legacy-json:${$.item.id}`,source_ref:W,owner:"legacy-json",scope:$.scope,precedence:{rank:90,label:"legacy-json-note"},source_hash:G,content_hash:X,discovered_at:$.discoveredAt,tags:[...new Set(["global-rules","legacy-json",...$.item.tags??[]])],redaction_status:U,redactions:_.findings.map((q)=>({type:q.type,severity:q.severity})),citations:[lF({sourceRef:W,sourcePath:$.legacyStorePath,lineCount:Y,contentHash:X})],bytes:Buffer.byteLength($.item.content),line_count:Y,importable:U!=="refused",skipped_reason:U==="refused"?"secret_refused":null,preview:U==="refused"?null:cF(_.text),legacy_json_id:$.item.id};return{evidence:Q,text:_.text,manifest:Q.importable?pF(Q,_.text):null}}function Nn($){if(!$.legacyStorePath||!nF($.legacyStorePath))return 0;let _=new Map($.records.filter((J)=>J.legacy_json_id&&J.importable).map((J)=>[J.legacy_json_id,J]));if(_.size===0)return 0;return $4($.legacyStorePath,()=>{let J=g2($.legacyStorePath);if(!J.exists)return 0;let U=0;for(let W of J.items){let X=_.get(W.id);if(!X)continue;let G=W.metadata??{};W.archived=!0,W.metadata={...G,knowledge_rules_import:{status:"deprecated_after_source_backed_promotion",deprecated_at:$.now,source_ref:X.source_ref,source_hash:X.source_hash,content_hash:X.content_hash,data_loss:!1}},W.tags=[...new Set([...W.tags??[],"deprecated:knowledge-rules-import"])],W.updated_at=$.now,U+=1}if(U>0)F4($.legacyStorePath,{items:J.items});return U})}async function oF($={}){let _=fL($.root??process.cwd()),J=$.scope??"global",U=$.owner??"global-agent-rules-standard",W=$.dryRun!==!1,X=($.now??new Date).toISOString(),G=Math.max(1,Math.min($.maxItems??Un,1000)),Y=Math.max(1,Math.min($.limit??Xn,100)),Q=Math.max(1024,Math.min($.maxBytesPerFile??Gn,2097152)),q=[],N=On(_,q).slice(0,G).map((u)=>Bn({root:_,candidate:{...u,owner:u.owner==="repository"?U:u.owner,scope:J},discoveredAt:X,maxBytesPerFile:Q,safetyPolicy:$.safetyPolicy})),B=($.includeLegacy===!1||!$.legacyStorePath?{exists:!1,items:[]}:g2($.legacyStorePath)).items.filter((u)=>u.archived!==!0&&Ln(u)).slice(0,G),H=B.map((u)=>Hn({item:u,legacyStorePath:$.legacyStorePath,discoveredAt:X,scope:J,safetyPolicy:$.safetyPolicy})),V=[...N,...H].slice(0,G),K=V.map((u)=>u.evidence),F=V.filter((u)=>u.manifest).map((u)=>u.manifest),w=K.filter((u)=>u.redaction_status==="refused").length,A=K.slice(0,Y),g=q.slice(0,Y),v=null,k=0;if(!W){if(!$.dbPath)throw Error("rules provenance apply mode requires dbPath.");if(F.length>0)v=await A1({dbPath:$.dbPath,items:F,sourceLabel:"knowledge://rules-provenance/global-agent-rules",readAction:"rules_provenance_import",allowFileSourceRefs:!0,safetyPolicy:$.safetyPolicy,now:$.now,maxItems:G});if($.deprecateLegacy!==!1)k=Nn({legacyStorePath:$.legacyStorePath,records:K,now:X})}return{ok:w===0||F.length>0||W,workflow:"global-rules-provenance-import",dry_run:W,writes_performed:!W,root:_,scope:J,owner:U,discovered_at:X,max_items:G,evidence_limit:Y,records_seen:K.length,records_importable:F.length,records_refused:w,records_skipped:q.length,evidence_truncated:K.length>A.length,skipped_truncated:q.length>g.length,evidence:A,skipped:g,import_result:v,legacy:{store_path:$.legacyStorePath??null,candidates:B.length,promoted:H.filter((u)=>u.manifest).length,deprecated:k,data_loss:!1},message:W?`Discovered ${K.length} rule source(s); ${F.length} importable, ${w} refused`:`Imported ${v?.items_seen??0} rule source(s); ${k} legacy note(s) deprecated`}}import{createHash as Vn,randomUUID as tF}from"crypto";function Rn($){return`sha256:${Vn("sha256").update($).digest("hex")}`}function aF($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function sF($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function c0($){return typeof $==="string"&&$.length>0?$:null}function Kn($){let _=sF($),J=c0(_.url)??c0(_.uri)??c0(_.sourceUrl);if(!J)return null;return{url:J,title:c0(_.title)??c0(_.name),snippet:c0(_.snippet)??c0(_.text)??c0(_.description),provider_metadata:_}}function iG($,_){if(Array.isArray($)){for(let W of $)iG(W,_);return}let J=Kn($);if(J)_.set(J.url,J);let U=sF($);for(let W of["sources","results","citations","annotations","output"])if(U[W])iG(U[W],_)}function Fn($,_){return Array.from({length:Math.min(_,3)},(J,U)=>({url:`https://example.com/knowledge-web-${U+1}`,title:`Fake web source ${U+1}`,snippet:`Deterministic web-search fixture for "${$}"`,provider_metadata:{fake:!0,rank:U+1}}))}async function En($){let{generateText:_}=await import("ai"),{createOpenAI:J}=await import("@ai-sdk/openai"),U=n4($.config,"openai"),W=J({apiKey:$.env[U.api_key_env],baseURL:U.base_url}),X=W.tools?.webSearch;if(!X)throw Error("OpenAI provider does not expose tools.webSearch.");return _({model:W($.model),prompt:$.query,tools:{web_search:X({externalWebAccess:!0,searchContextSize:"medium",...$.domains.length>0?{allowedDomains:$.domains}:{}})},toolChoice:{type:"tool",toolName:"web_search"}})}async function Mn($){let{generateText:_}=await import("ai"),{createAnthropic:J}=await import("@ai-sdk/anthropic"),U=n4($.config,"anthropic"),W=J({apiKey:$.env[U.api_key_env],baseURL:U.base_url}),X=W.tools?.webSearch_20250305??W.tools?.webSearch;if(!X)throw Error("Anthropic provider does not expose a web search tool.");return _({model:W($.model),prompt:$.query,tools:{web_search:X({maxUses:$.maxUses,...$.domains.length>0?{allowedDomains:$.domains}:{}})}})}async function An($,_,J){if(!$.fileResults||_.length===0)return 0;let U=_.map((X)=>{let G=[X.title,X.snippet,X.url].filter(Boolean).join(` -`),Y=Rn(G);return{source_ref:X.url,name:X.title??X.url,url:X.url,mime:"text/plain",hash:Y,revision:Y,status:"active",updated_at:J,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:X.url,content_source:"provider_web_search",provider_metadata:X.provider_metadata},extracted_text:G}});return(await A1({dbPath:$.dbPath,items:U,sourceLabel:`web-search:${$.query}`,readAction:"provider_web_search_file_results",safetyPolicy:$.safetyPolicy,now:new Date(J)})).sources_upserted}async function eF($){let _=$.query.trim();if(!_)throw Error("Web search query is required.");let J=$.env??process.env,U=($.now??new Date).toISOString(),W=Math.max(1,Math.min($.limit??5,20)),X=Math.max(1,Math.min($.maxUses??3,10)),G=$.domains??[],Y=y6($.modelRef??($.provider?`${$.provider}:${n4($.config,$.provider).default_model}`:"default"),$.config),Q=w_(Y),q=$.provider??Q.provider,L=Q.provider===q?Q.model:n4($.config,q).default_model,N=`run_${tF()}`;if(!$.fake&&$.safetyPolicy)fJ($.safetyPolicy);if(!$.fake&&q!=="openai"&&q!=="anthropic")throw Error(`Provider ${q} does not expose native web search yet.`);if(!$.fake)w1(q,$.config,J);a($.dbPath);let R=m($.dbPath);try{R.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,"provider-web-search",_,"running",q,L,JSON.stringify({domains:G,max_uses:X,fake:$.fake===!0}),U,U]),__(R,{event_type:"source_read",action:$.fake?"fake_provider_web_search":"provider_web_search",target_uri:_,decision:"allow",metadata:{provider:q,model:L,domains:G,max_uses:X},created_at:U})}finally{R.close()}let B="",H=[],V={input_tokens:aF(_),output_tokens:0,cost_usd:0},K=[];if($.fake)H=Fn(_,W),B=`Fake web search answer for: ${_}`,V.output_tokens=aF(B);else{let w=q==="openai"?await En({query:_,model:L,config:$.config,env:J,maxUses:X,domains:G}):await Mn({query:_,model:L,config:$.config,env:J,maxUses:X,domains:G});B=w.text;let A=new Map;iG(w.sources,A),iG(w.toolResults,A),H=Array.from(A.values()).slice(0,W);let g=g1({provider:q,model:L,usage:w.usage,providerMetadata:w.providerMetadata});V={input_tokens:g.input_tokens,output_tokens:g.output_tokens,cost_usd:g.cost_usd}}let E=await An($,H,U),F=m($.dbPath);try{F.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({domains:G,max_uses:X,sources:H.length,filed_sources:E,fake:$.fake===!0}),U,N]),F.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${tF()}`,N,"info","provider_web_search_completed",JSON.stringify({sources:H.length,filed_sources:E}),U]),TJ(F,{run_id:N,provider:q,model:L,input_tokens:V.input_tokens,output_tokens:V.output_tokens,cost_usd:V.cost_usd,metadata:{web_search:!0,sources:H.length,filed_sources:E},created_at:U})}finally{F.close()}if(H.length===0)K.push("no_web_sources_returned");return{run_id:N,query:_,provider:q,model:L,answer:B,sources:H,filed_sources:E,usage:V,warnings:K}}import{createHash as bn,randomUUID as wn}from"crypto";function RW($,_){return`${$}_${bn("sha256").update(_).digest("hex").slice(0,20)}`}function CL($){return $.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"knowledge-page"}function gn($){return{year:String($.getUTCFullYear()),month:String($.getUTCMonth()+1).padStart(2,"0"),day:String($.getUTCDate()).padStart(2,"0")}}function kn($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function $E($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function In($){return Array.from(new Set(($??"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,12)}function _E($){return $.replace(/[\\%_]/g,(_)=>`\\${_}`)}function fn($,_){let J=Math.max(1,Math.min(_.limit??10,50)),U=_.sourceRefs??[],W=In(_.query),X=["c.kind = 'source'"],G=[];if(U.length>0){X.push(`(${U.map(()=>"(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`);for(let Y of U)G.push(Y,`%${_E(Y)}%`)}if(W.length>0){X.push(`(${W.map(()=>"lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`);for(let Y of W)G.push(`%${_E(Y)}%`)}return G.push(J),$.query(`SELECT + )`,["completed",g,"embedding","pending",D.provider,D.model]).changes}finally{I.close()}}async function pR(_){h(_.dbPath);let $=(_.now??new Date).toISOString(),g=`run_${lR()}`,U=_.full?xM(_.dbPath):{embeddings:0,vectorEntries:0},D=U3({..._,reason:_.full?"full_embedding_rebuild":"missing_embedding"}),I=v(_.dbPath);try{I.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[g,"embedding-refresh",_.full?"full":"incremental","running","local",I4(_.modelRef,_.config),JSON.stringify({full:_.full===!0,queued:D}),$,$])}finally{I.close()}let j=await sU({dbPath:_.dbPath,config:_.config,env:_.env,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake,limit:_.limit,now:_.now}),N=yM(_.dbPath,_,$),O=v(_.dbPath);try{O.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({full:_.full===!0,queued:D,indexed:j,completed_queue_items:N}),$,g]),O.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${lR()}`,g,"info","embedding_refresh_completed",JSON.stringify({queued:D,indexed:j,completed_queue_items:N}),$])}finally{O.close()}return{run_id:g,full:_.full===!0,deleted_embeddings:U.embeddings,deleted_vector_entries:U.vectorEntries,queued:D,indexed:j,completed_queue_items:N}}import{createHash as sR}from"crypto";import{existsSync as _G,lstatSync as hM,readdirSync as cM,readFileSync as nM,statSync as dM}from"fs";import{basename as _g,extname as mM,join as iM,relative as lM,resolve as E3,sep as tM}from"path";import{pathToFileURL as eR}from"url";var oM=100,pM=25,eM=262144,aM=5,sM=new Set([".md",".mdx",".txt",".json",".jsonc",".toml",".yaml",".yml"]),I3=new Set(["CODEWITH.md","AGENTS.md","CLAUDE.md","RULES.md","INSTRUCTIONS.md"]),_Z=new Set([".git","node_modules","dist","build",".codewith-worktrees",".connect",".secrets",".tmp","tmp","auth_profiles","profiles","preserved","backup","backups","cache","logs","runs"]),$Z=/(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i,tj=/(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i;function j3(_){return`sha256:${sR("sha256").update(_).digest("hex")}`}function gZ(_){return`sha256:${sR("sha256").update(_).digest("hex")}`}function NU(_){return _.split(tM).join("/")}function N3(_,$){let g=lM(_,$);return g?NU(g):_g($)}function n6(_){return sM.has(mM(_).toLowerCase())}function aR(_){return NU(_).split("/").some(($)=>$Z.test($))}function $G(_,$=220){let g=_.normalize("NFKC").trim().replace(/\s+/g," ");if(g.length<=$)return g;return`${g.slice(0,Math.max(0,$-1)).trim()}...`}function gG(_){if(!_)return 0;return _.split(/\r\n|\n|\r/).length}function DG(_){return{source_ref:_.sourceRef,source_path:_.sourcePath,line_start:_.lineCount>0?1:0,line_end:_.lineCount,content_hash:_.contentHash}}function DZ(){return[{base:".",maxDepth:0,spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:10,label:"root-rule-doc"},tags:["global-rules","rule-doc"],include:(_)=>I3.has(_)}},{base:".codewith",spec:{family:"codewith",owner:"codewith",scope:"global",precedence:{rank:20,label:"codewith"},tags:["global-rules","codewith","agent-instructions"],include:(_)=>{let $=NU(_),g=_g($);if(I3.has(g)||$==="config.toml")return!0;if($.endsWith("/SKILL.md"))return!0;if(/^(rules|instructions|prompts|plans)\//.test($)&&n6($))return!0;return!1}}},{base:".claude",spec:{family:"claude",owner:"claude",scope:"global",precedence:{rank:30,label:"claude-rules"},tags:["global-rules","claude","agent-instructions"],include:(_)=>{let $=NU(_);return $==="CLAUDE.md"||/^rules\//.test($)&&n6($)}}},{base:".codex",spec:{family:"codex",owner:"codex",scope:"global",precedence:{rank:40,label:"codex"},tags:["global-rules","codex","agent-instructions"],include:(_)=>{let $=NU(_),g=_g($);if(I3.has(g)||g==="config.toml")return!0;return/^(rules|instructions|prompts)\//.test($)&&n6($)}}},{base:".opencode",spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode"},tags:["global-rules","opencode","agent-instructions"],include:(_)=>tj.test(_)&&n6(_)}},{base:".",maxDepth:0,spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode-config"},tags:["global-rules","opencode","config"],include:(_)=>["opencode.json","opencode.jsonc","opencode.toml","opencode.yaml","opencode.yml"].includes(_)}},{base:".hasna/prompts",spec:{family:"prompt",owner:"hasna",scope:"global",precedence:{rank:60,label:"selected-prompts"},tags:["global-rules","prompt"],include:(_)=>tj.test(_)&&n6(_)}},{base:".hasna/plans",spec:{family:"plan",owner:"hasna",scope:"global",precedence:{rank:65,label:"selected-plans"},tags:["global-rules","plan"],include:(_)=>tj.test(_)&&n6(_)}},{base:"docs",spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:70,label:"rule-docs"},tags:["global-rules","rule-doc"],include:(_)=>tj.test(_)&&n6(_)}}]}function UZ(_,$){let g=new Map;for(let U of DZ()){let D=E3(_,U.base);if(!_G(D))continue;if(dM(D).isFile()){let j=_g(D);if(U.spec.include(j))g.set(D,{...U.spec,absPath:D});continue}UG({basePath:D,depth:0,maxDepth:U.maxDepth??aM,spec:U.spec,candidates:g,skipped:$})}return[...g.values()].sort((U,D)=>{if(U.precedence.rank!==D.precedence.rank)return U.precedence.rank-D.precedence.rank;return U.absPath.localeCompare(D.absPath)})}function UG(_){let $=_.rootBasePath??_.basePath;if(_.depth>_.maxDepth)return;for(let g of cM(_.basePath,{withFileTypes:!0})){let U=iM(_.basePath,g.name),D=N3($,U);if(g.isSymbolicLink())continue;if(g.isDirectory()){if(_Z.has(g.name))continue;if(aR(D)){_.skipped.push({source_family:_.spec.family,source_path:U,reason:"sensitive_path"});continue}UG({..._,rootBasePath:$,basePath:U,depth:_.depth+1});continue}if(!g.isFile())continue;let I=N3(E3($),U);if(aR(I)){_.skipped.push({source_family:_.spec.family,source_path:U,reason:"sensitive_path"});continue}if(!_.spec.include(I))continue;if(!n6(U))continue;_.candidates.set(U,{..._.spec,absPath:U})}}function IZ(_){if((_.tags??[]).map((U)=>U.toLowerCase()).some((U)=>["rule","rules","agent","instructions","global-rules","global-agent-rules"].includes(U)))return!0;let g=`${_.title} +${_.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(g)}function IG(_,$){let g={source_path:_.source_path,source_path_ref:_.source_path_ref,source_ref:_.source_ref,owner:_.owner,scope:_.scope,precedence:_.precedence,source_hash:_.source_hash,content_hash:_.content_hash,discovered_at:_.discovered_at,tags:_.tags,redaction_status:_.redaction_status,citations:_.citations};return{source_ref:_.source_ref,name:_.title,mime:"text/markdown",size:Buffer.byteLength($),hash:_.content_hash,revision:_.content_hash,status:"active",updated_at:_.discovered_at,permissions:{mode:"read_only",allowed_purposes:["knowledge_index","knowledge_answer","agent_context"]},rule_provenance:g,source_family:_.source_family,source_path_ref:_.source_path_ref,owner:_.owner,scope:_.scope,precedence:_.precedence,tags:_.tags,redaction_status:_.redaction_status,legacy_json_id:_.legacy_json_id??null,extracted_text:$}}function jZ(_){let $=hM(_.candidate.absPath),g=_.candidate.absPath,U=N3(_.root,g);if($.size>_.maxBytesPerFile){let J=eR(g).href;return{evidence:{source_family:_.candidate.family,title:_g(g),source_path:g,source_path_ref:U,source_ref:J,owner:_.candidate.owner,scope:_.candidate.scope,precedence:_.candidate.precedence,source_hash:"sha256:skipped-too-large",content_hash:"sha256:skipped-too-large",discovered_at:_.discoveredAt,tags:[..._.candidate.tags,"skipped"],redaction_status:"refused",redactions:[],citations:[],bytes:$.size,line_count:0,importable:!1,skipped_reason:"max_bytes_exceeded",preview:null},text:"",manifest:null}}let D=nM(g),I=D.toString("utf8"),j=u_(I,_.safetyPolicy),O=j.findings.some((J)=>J.severity==="high")?"refused":j.findings.length>0?"redacted":"clean",A=j3(j.text),L=eR(g).href,z=gG(j.text),W={source_family:_.candidate.family,title:_g(g),source_path:g,source_path_ref:U,source_ref:L,owner:_.candidate.owner,scope:_.candidate.scope,precedence:_.candidate.precedence,source_hash:gZ(D),content_hash:A,discovered_at:_.discoveredAt,tags:[..._.candidate.tags],redaction_status:O,redactions:j.findings.map((J)=>({type:J.type,severity:J.severity})),citations:[DG({sourceRef:L,sourcePath:g,lineCount:z,contentHash:A})],bytes:D.byteLength,line_count:z,importable:O!=="refused",skipped_reason:O==="refused"?"secret_refused":null,preview:O==="refused"?null:$G(j.text)};return{evidence:W,text:j.text,manifest:W.importable?IG(W,j.text):null}}function NZ(_){let $=u_(_.item.content,_.safetyPolicy),U=$.findings.some((A)=>A.severity==="high")?"refused":$.findings.length>0?"redacted":"clean",D=`open-files://source/legacy-json/path/${encodeURIComponent(_.item.id)}`,I=j3($.text),j=j3(_.item.content),N=gG($.text),O={source_family:"legacy_json",title:_.item.title,source_path:_.legacyStorePath,source_path_ref:`legacy-json:${_.item.id}`,source_ref:D,owner:"legacy-json",scope:_.scope,precedence:{rank:90,label:"legacy-json-note"},source_hash:j,content_hash:I,discovered_at:_.discoveredAt,tags:[...new Set(["global-rules","legacy-json",..._.item.tags??[]])],redaction_status:U,redactions:$.findings.map((A)=>({type:A.type,severity:A.severity})),citations:[DG({sourceRef:D,sourcePath:_.legacyStorePath,lineCount:N,contentHash:I})],bytes:Buffer.byteLength(_.item.content),line_count:N,importable:U!=="refused",skipped_reason:U==="refused"?"secret_refused":null,preview:U==="refused"?null:$G($.text),legacy_json_id:_.item.id};return{evidence:O,text:$.text,manifest:O.importable?IG(O,$.text):null}}function EZ(_){if(!_.legacyStorePath||!_G(_.legacyStorePath))return 0;let $=new Map(_.records.filter((g)=>g.legacy_json_id&&g.importable).map((g)=>[g.legacy_json_id,g]));if($.size===0)return 0;return v$(_.legacyStorePath,()=>{let g=I0(_.legacyStorePath);if(!g.exists)return 0;let U=0;for(let D of g.items){let I=$.get(D.id);if(!I)continue;let j=D.metadata??{};D.archived=!0,D.metadata={...j,knowledge_rules_import:{status:"deprecated_after_source_backed_promotion",deprecated_at:_.now,source_ref:I.source_ref,source_hash:I.source_hash,content_hash:I.content_hash,data_loss:!1}},D.tags=[...new Set([...D.tags??[],"deprecated:knowledge-rules-import"])],D.updated_at=_.now,U+=1}if(U>0)t$(_.legacyStorePath,{items:g.items});return U})}async function jG(_={}){let $=E3(_.root??process.cwd()),g=_.scope??"global",U=_.owner??"global-agent-rules-standard",D=_.dryRun!==!1,I=(_.now??new Date).toISOString(),j=Math.max(1,Math.min(_.maxItems??oM,1000)),N=Math.max(1,Math.min(_.limit??pM,100)),O=Math.max(1024,Math.min(_.maxBytesPerFile??eM,2097152)),A=[],z=UZ($,A).slice(0,j).map((Z)=>jZ({root:$,candidate:{...Z,owner:Z.owner==="repository"?U:Z.owner,scope:g},discoveredAt:I,maxBytesPerFile:O,safetyPolicy:_.safetyPolicy})),J=(_.includeLegacy===!1||!_.legacyStorePath?{exists:!1,items:[]}:I0(_.legacyStorePath)).items.filter((Z)=>Z.archived!==!0&&IZ(Z)).slice(0,j),P=J.map((Z)=>NZ({item:Z,legacyStorePath:_.legacyStorePath,discoveredAt:I,scope:g,safetyPolicy:_.safetyPolicy})),S=[...z,...P].slice(0,j),X=S.map((Z)=>Z.evidence),R=S.filter((Z)=>Z.manifest).map((Z)=>Z.manifest),K=X.filter((Z)=>Z.redaction_status==="refused").length,Q=X.slice(0,N),T=A.slice(0,N),q=null,V=0;if(!D){if(!_.dbPath)throw Error("rules provenance apply mode requires dbPath.");if(R.length>0)q=await $4({dbPath:_.dbPath,items:R,sourceLabel:"knowledge://rules-provenance/global-agent-rules",readAction:"rules_provenance_import",allowFileSourceRefs:!0,safetyPolicy:_.safetyPolicy,now:_.now,maxItems:j});if(_.deprecateLegacy!==!1)V=EZ({legacyStorePath:_.legacyStorePath,records:X,now:I})}return{ok:K===0||R.length>0||D,workflow:"global-rules-provenance-import",dry_run:D,writes_performed:!D,root:$,scope:g,owner:U,discovered_at:I,max_items:j,evidence_limit:N,records_seen:X.length,records_importable:R.length,records_refused:K,records_skipped:A.length,evidence_truncated:X.length>Q.length,skipped_truncated:A.length>T.length,evidence:Q,skipped:T,import_result:q,legacy:{store_path:_.legacyStorePath??null,candidates:J.length,promoted:P.filter((Z)=>Z.manifest).length,deprecated:V,data_loss:!1},message:D?`Discovered ${X.length} rule source(s); ${R.length} importable, ${K} refused`:`Imported ${q?.items_seen??0} rule source(s); ${V} legacy note(s) deprecated`}}import{createHash as OZ,randomUUID as NG}from"crypto";function AZ(_){return`sha256:${OZ("sha256").update(_).digest("hex")}`}function EG(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function OG(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function d6(_){return typeof _==="string"&&_.length>0?_:null}function LZ(_){let $=OG(_),g=d6($.url)??d6($.uri)??d6($.sourceUrl);if(!g)return null;return{url:g,title:d6($.title)??d6($.name),snippet:d6($.snippet)??d6($.text)??d6($.description),provider_metadata:$}}function oj(_,$){if(Array.isArray(_)){for(let D of _)oj(D,$);return}let g=LZ(_);if(g)$.set(g.url,g);let U=OG(_);for(let D of["sources","results","citations","annotations","output"])if(U[D])oj(U[D],$)}function JZ(_,$){return Array.from({length:Math.min($,3)},(g,U)=>({url:`https://example.com/knowledge-web-${U+1}`,title:`Fake web source ${U+1}`,snippet:`Deterministic web-search fixture for "${_}"`,provider_metadata:{fake:!0,rank:U+1}}))}async function PZ(_){let{generateText:$}=await import("ai"),{createOpenAI:g}=await import("@ai-sdk/openai"),U=$6(_.config,"openai"),D=g({apiKey:_.env[U.api_key_env],baseURL:U.base_url}),I=D.tools?.webSearch;if(!I)throw Error("OpenAI provider does not expose tools.webSearch.");return $({model:D(_.model),prompt:_.query,tools:{web_search:I({externalWebAccess:!0,searchContextSize:"medium",..._.domains.length>0?{allowedDomains:_.domains}:{}})},toolChoice:{type:"tool",toolName:"web_search"}})}async function zZ(_){let{generateText:$}=await import("ai"),{createAnthropic:g}=await import("@ai-sdk/anthropic"),U=$6(_.config,"anthropic"),D=g({apiKey:_.env[U.api_key_env],baseURL:U.base_url}),I=D.tools?.webSearch_20250305??D.tools?.webSearch;if(!I)throw Error("Anthropic provider does not expose a web search tool.");return $({model:D(_.model),prompt:_.query,tools:{web_search:I({maxUses:_.maxUses,..._.domains.length>0?{allowedDomains:_.domains}:{}})}})}async function SZ(_,$,g){if(!_.fileResults||$.length===0)return 0;let U=$.map((I)=>{let j=[I.title,I.snippet,I.url].filter(Boolean).join(` +`),N=AZ(j);return{source_ref:I.url,name:I.title??I.url,url:I.url,mime:"text/plain",hash:N,revision:N,status:"active",updated_at:g,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:I.url,content_source:"provider_web_search",provider_metadata:I.provider_metadata},extracted_text:j}});return(await $4({dbPath:_.dbPath,items:U,sourceLabel:`web-search:${_.query}`,readAction:"provider_web_search_file_results",safetyPolicy:_.safetyPolicy,now:new Date(g)})).sources_upserted}async function AG(_){let $=_.query.trim();if(!$)throw Error("Web search query is required.");let g=_.env??process.env,U=(_.now??new Date).toISOString(),D=Math.max(1,Math.min(_.limit??5,20)),I=Math.max(1,Math.min(_.maxUses??3,10)),j=_.domains??[],N=G$(_.modelRef??(_.provider?`${_.provider}:${$6(_.config,_.provider).default_model}`:"default"),_.config),O=f_(N),A=_.provider??O.provider,L=O.provider===A?O.model:$6(_.config,A).default_model,z=`run_${NG()}`;if(!_.fake&&_.safetyPolicy)J0(_.safetyPolicy);if(!_.fake&&A!=="openai"&&A!=="anthropic")throw Error(`Provider ${A} does not expose native web search yet.`);if(!_.fake)D4(A,_.config,g);h(_.dbPath);let W=v(_.dbPath);try{W.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[z,"provider-web-search",$,"running",A,L,JSON.stringify({domains:j,max_uses:I,fake:_.fake===!0}),U,U]),X_(W,{event_type:"source_read",action:_.fake?"fake_provider_web_search":"provider_web_search",target_uri:$,decision:"allow",metadata:{provider:A,model:L,domains:j,max_uses:I},created_at:U})}finally{W.close()}let J="",P=[],S={input_tokens:EG($),output_tokens:0,cost_usd:0},X=[];if(_.fake)P=JZ($,D),J=`Fake web search answer for: ${$}`,S.output_tokens=EG(J);else{let K=A==="openai"?await PZ({query:$,model:L,config:_.config,env:g,maxUses:I,domains:j}):await zZ({query:$,model:L,config:_.config,env:g,maxUses:I,domains:j});J=K.text;let Q=new Map;oj(K.sources,Q),oj(K.toolResults,Q),P=Array.from(Q.values()).slice(0,D);let T=U4({provider:A,model:L,usage:K.usage,providerMetadata:K.providerMetadata});S={input_tokens:T.input_tokens,output_tokens:T.output_tokens,cost_usd:T.cost_usd}}let G=await SZ(_,P,U),R=v(_.dbPath);try{R.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({domains:j,max_uses:I,sources:P.length,filed_sources:G,fake:_.fake===!0}),U,z]),R.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${NG()}`,z,"info","provider_web_search_completed",JSON.stringify({sources:P.length,filed_sources:G}),U]),S0(R,{run_id:z,provider:A,model:L,input_tokens:S.input_tokens,output_tokens:S.output_tokens,cost_usd:S.cost_usd,metadata:{web_search:!0,sources:P.length,filed_sources:G},created_at:U})}finally{R.close()}if(P.length===0)X.push("no_web_sources_returned");return{run_id:z,query:$,provider:A,model:L,answer:J,sources:P,filed_sources:G,usage:S,warnings:X}}import{createHash as WZ,randomUUID as XZ}from"crypto";function $g(_,$){return`${_}_${WZ("sha256").update($).digest("hex").slice(0,20)}`}function O3(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"knowledge-page"}function RZ(_){return{year:String(_.getUTCFullYear()),month:String(_.getUTCMonth()+1).padStart(2,"0"),day:String(_.getUTCDate()).padStart(2,"0")}}function GZ(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function LG(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function YZ(_){return Array.from(new Set((_??"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,12)}function JG(_){return _.replace(/[\\%_]/g,($)=>`\\${$}`)}function QZ(_,$){let g=Math.max(1,Math.min($.limit??10,50)),U=$.sourceRefs??[],D=YZ($.query),I=["c.kind = 'source'"],j=[];if(U.length>0){I.push(`(${U.map(()=>"(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`);for(let N of U)j.push(N,`%${JG(N)}%`)}if(D.length>0){I.push(`(${D.map(()=>"lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`);for(let N of D)j.push(`%${JG(N)}%`)}return j.push(g),_.query(`SELECT c.id AS chunk_id, c.text, c.start_offset, @@ -1038,12 +1039,12 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| FROM chunks c JOIN source_revisions sr ON sr.id = c.source_revision_id JOIN sources s ON s.id = sr.source_id - WHERE ${X.join(" AND ")} + WHERE ${I.join(" AND ")} ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`).all(...G)}function JE($,_=420){let J=$.replace(/\s+/g," ").trim();return J.length<=_?J:`${J.slice(0,_-1).trim()}...`}function Cn($,_){if($.title?.trim())return $.title.trim();if($.query?.trim())return $.query.trim();return _[0]?.source_title??"Compiled Knowledge"}function Pn($,_,J){let U=_.map((X,G)=>{return`- [${`S${G+1}`}] ${X.source_title??X.source_uri??"Source"} (${X.source_uri??"unknown"}, revision ${X.revision??"unknown"}, hash ${X.hash??"unknown"})`}),W=_.map((X,G)=>{let Y=`S${G+1}`;return[`## ${X.source_title??`Source ${G+1}`}`,"",JE(X.text),"",`Citation: [${Y}]`].join(` -`)});return[`# ${$}`,"",`Generated at: ${J}`,"","## Sources","",...U,"",...W,""].join(` -`)}async function lG($,_){let J=await $.put(_);return{key:J.key,uri:J.uri,kind:_.key.startsWith("logs/")?"log":"wiki_page",content_type:_.content_type,modified_at:J.modified_at,...IJ(_.body),metadata:{..._.metadata??{}}}}async function WE($,_,J){let{year:U,month:W,day:X}=gn(J),G=`logs/${U}/${W}/${X}.jsonl`,Y="";try{Y=await $.getText(G)}catch{Y=""}return lG($,{key:G,body:`${Y}${JSON.stringify(_)} -`,content_type:"application/x-ndjson",metadata:{provenance:X6({generated_from:String(_.event??"wiki_log"),artifact_key:G})}})}function PL($,_){$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + LIMIT ?`).all(...j)}function PG(_,$=420){let g=_.replace(/\s+/g," ").trim();return g.length<=$?g:`${g.slice(0,$-1).trim()}...`}function TZ(_,$){if(_.title?.trim())return _.title.trim();if(_.query?.trim())return _.query.trim();return $[0]?.source_title??"Compiled Knowledge"}function qZ(_,$,g){let U=$.map((I,j)=>{return`- [${`S${j+1}`}] ${I.source_title??I.source_uri??"Source"} (${I.source_uri??"unknown"}, revision ${I.revision??"unknown"}, hash ${I.hash??"unknown"})`}),D=$.map((I,j)=>{let N=`S${j+1}`;return[`## ${I.source_title??`Source ${j+1}`}`,"",PG(I.text),"",`Citation: [${N}]`].join(` +`)});return[`# ${_}`,"",`Generated at: ${g}`,"","## Sources","",...U,"",...D,""].join(` +`)}async function pj(_,$){let g=await _.put($);return{key:g.key,uri:g.uri,kind:$.key.startsWith("logs/")?"log":"wiki_page",content_type:$.content_type,modified_at:g.modified_at,...L0($.body),metadata:{...$.metadata??{}}}}async function zG(_,$,g){let{year:U,month:D,day:I}=RZ(g),j=`logs/${U}/${D}/${I}.jsonl`,N="";try{N=await _.getText(j)}catch{N=""}return pj(_,{key:j,body:`${N}${JSON.stringify($)} +`,content_type:"application/x-ndjson",metadata:{provenance:U$({generated_from:String($.event??"wiki_log"),artifact_key:j})}})}function A3(_,$){_.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title = excluded.title, @@ -1051,41 +1052,41 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| content_hash = excluded.content_hash, status = excluded.status, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[_.pageId,_.path,_.title,_.artifactUri,_.contentHash,"active",JSON.stringify({artifact_key:_.path,provenance:_.provenance}),_.now,_.now]);let J=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_.pageId);for(let W of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[W.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_.pageId]);let U=RW("chk",`${_.pageId}\x00${_.contentHash}`);$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.pageId,"wiki",0,_.body,kn(_.body),0,_.body.length,JSON.stringify({artifact_key:_.path,artifact_uri:_.artifactUri,content_hash:_.contentHash,provenance:_.provenance}),_.now]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,_.body,_.title,_.artifactUri])}function UE($,_,J,U){$.run("DELETE FROM citations WHERE wiki_page_id = ?",[_]);for(let W of J)$.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[RW("cit",`${_}\x00${W.source_uri}\x00${W.chunk_id??wn()}`),_,W.chunk_id,W.source_uri,W.quote,W.start_offset,W.end_offset,JSON.stringify(W.metadata),U]);return J.length}function XE($,_){return $.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + updated_at = excluded.updated_at`,[$.pageId,$.path,$.title,$.artifactUri,$.contentHash,"active",JSON.stringify({artifact_key:$.path,provenance:$.provenance}),$.now,$.now]);let g=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($.pageId);for(let D of g)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[D.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$.pageId]);let U=$g("chk",`${$.pageId}\x00${$.contentHash}`);_.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,$.pageId,"wiki",0,$.body,GZ($.body),0,$.body.length,JSON.stringify({artifact_key:$.path,artifact_uri:$.artifactUri,content_hash:$.contentHash,provenance:$.provenance}),$.now]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,$.body,$.title,$.artifactUri])}function SG(_,$,g,U){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);for(let D of g)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$g("cit",`${$}\x00${D.source_uri}\x00${D.chunk_id??XZ()}`),$,D.chunk_id,D.source_uri,D.quote,D.start_offset,D.end_offset,JSON.stringify(D.metadata),U]);return g.length}function WG(_,$){return _.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[RW("idx",`wiki-topic\x00${_.path}`),"wiki_topic",_.title,_.artifactUri,_.path,JSON.stringify({artifact_key:_.path,content_hash:_.contentHash}),_.now,_.now]),1}function Tn($){return $.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0]??"knowledge"}async function GE($){let _=$.now??new Date,J=_.toISOString();a($.dbPath);let U=m($.dbPath),W;try{W=fn(U,$)}finally{U.close()}if(W.length===0)throw Error("No source chunks matched wiki compile input.");let X=Cn($,W),Y=`wiki/generated/${CL(X)}.md`,Q=Pn(X,W,J),q=W.map((v)=>{let k=$E(v.metadata_json);return typeof k.source_ref==="string"?k.source_ref:v.source_uri}).filter((v)=>Boolean(v)),L=X6({generated_from:"wiki_compile",artifact_key:Y,source_refs:q}),N=await lG($.store,{key:Y,body:Q,content_type:"text/markdown",metadata:{generated_from:"wiki_compile"}}),R=RW("wiki",Y),B=W.map((v)=>({chunk_id:v.chunk_id,source_uri:v.source_uri??"unknown",quote:JE(v.text,240),start_offset:v.start_offset,end_offset:v.end_offset,metadata:{source_revision_id:v.source_revision_id,revision:v.revision,hash:v.hash,source_ref:$E(v.metadata_json).source_ref??v.source_uri}})),H=Tn(X),V=`wiki/concepts/${CL(H)}.md`,K=[`# ${H}`,"",`Related page: [[${Y}]]`,""].join(` -`),E=X6({generated_from:"wiki_compile_concept",artifact_key:V,source_refs:q}),F=await lG($.store,{key:V,body:K,content_type:"text/markdown",metadata:{generated_from:"wiki_compile_concept"}}),w=RW("wiki",V),A=await WE($.store,{ts:J,event:"wiki_compile_completed",page_key:Y,source_refs:q,chunks_seen:W.length},_),g=m($.dbPath);try{u4(g,[N,F,A],_),PL(g,{pageId:R,path:Y,title:X,artifactUri:N.uri,contentHash:N.hash??"",body:Q,provenance:L,now:J}),PL(g,{pageId:w,path:V,title:H,artifactUri:F.uri,contentHash:F.hash??"",body:K,provenance:E,now:J}),g.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) - VALUES (?, ?, ?, ?)`,[R,w,"concept",J]);let v=UE(g,R,B,J),k=XE(g,{title:X,path:Y,artifactUri:N.uri,contentHash:N.hash??"",now:J});return{page_id:R,path:Y,artifact_uri:N.uri,content_hash:N.hash??"",chunks_seen:W.length,citations_written:v,concept_page_id:w,indexes_updated:k,log_key:A.key,warnings:[]}}finally{g.close()}}async function YE($){if(!$.approveWrite)return{approved:!1,durable_writes_performed:!1,page_id:null,path:null,artifact_uri:null,citations_written:0,log_key:null,message:"Dry-run: answer filing requires --approve-write."};let _=$.now??new Date,J=_.toISOString(),U=$.prompt.length>80?`${$.prompt.slice(0,77)}...`:$.prompt,X=`wiki/answers/${CL(U)}.md`,G=$.context.citations,Y=[`# ${U}`,"",$.answer,"","## Citations","",...G.map((H,V)=>`- [C${V+1}] ${H.source_ref??H.source_uri??H.artifact_path??H.artifact_uri??"unknown"} ${H.hash?`(hash ${H.hash})`:""}`),""].join(` -`),Q=G.map((H)=>H.source_ref??H.source_uri).filter((H)=>Boolean(H)),q=X6({generated_from:"knowledge_answer",artifact_key:X,source_refs:Q}),L=await lG($.store,{key:X,body:Y,content_type:"text/markdown",metadata:{generated_from:"knowledge_answer"}}),N=await WE($.store,{ts:J,event:"wiki_answer_filed",page_key:X,prompt:$.prompt,citations:G.length},_),R=RW("wiki",X),B=m($.dbPath);try{u4(B,[L,N],_),PL(B,{pageId:R,path:X,title:U,artifactUri:L.uri,contentHash:L.hash??"",body:Y,provenance:q,now:J});let H=UE(B,R,G.map((V)=>({chunk_id:V.chunk_id,source_uri:V.source_uri??V.artifact_uri??"unknown",quote:V.quote,start_offset:V.start_offset,end_offset:V.end_offset,metadata:{source_ref:V.source_ref,artifact_path:V.artifact_path,revision:V.revision,hash:V.hash}})),J);return XE(B,{title:U,path:X,artifactUri:L.uri,contentHash:L.hash??"",now:J}),{approved:!0,durable_writes_performed:!0,page_id:R,path:X,artifact_uri:L.uri,citations_written:H,log_key:N.key,message:`Filed answer to ${X}`}}finally{B.close()}}function q2($,_){$.push(_)}function QE($){a($.dbPath);let _=m($.dbPath),J=[];try{let U=_.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n??0,W=_.query("SELECT COUNT(*) AS n FROM citations").get()?.n??0,X=_.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n??0,G=_.query(`SELECT wp.id, wp.path + updated_at = excluded.updated_at`,[$g("idx",`wiki-topic\x00${$.path}`),"wiki_topic",$.title,$.artifactUri,$.path,JSON.stringify({artifact_key:$.path,content_hash:$.contentHash}),$.now,$.now]),1}function BZ(_){return _.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0]??"knowledge"}async function XG(_){let $=_.now??new Date,g=$.toISOString();h(_.dbPath);let U=v(_.dbPath),D;try{D=QZ(U,_)}finally{U.close()}if(D.length===0)throw Error("No source chunks matched wiki compile input.");let I=TZ(_,D),N=`wiki/generated/${O3(I)}.md`,O=qZ(I,D,g),A=D.map((q)=>{let V=LG(q.metadata_json);return typeof V.source_ref==="string"?V.source_ref:q.source_uri}).filter((q)=>Boolean(q)),L=U$({generated_from:"wiki_compile",artifact_key:N,source_refs:A}),z=await pj(_.store,{key:N,body:O,content_type:"text/markdown",metadata:{generated_from:"wiki_compile"}}),W=$g("wiki",N),J=D.map((q)=>({chunk_id:q.chunk_id,source_uri:q.source_uri??"unknown",quote:PG(q.text,240),start_offset:q.start_offset,end_offset:q.end_offset,metadata:{source_revision_id:q.source_revision_id,revision:q.revision,hash:q.hash,source_ref:LG(q.metadata_json).source_ref??q.source_uri}})),P=BZ(I),S=`wiki/concepts/${O3(P)}.md`,X=[`# ${P}`,"",`Related page: [[${N}]]`,""].join(` +`),G=U$({generated_from:"wiki_compile_concept",artifact_key:S,source_refs:A}),R=await pj(_.store,{key:S,body:X,content_type:"text/markdown",metadata:{generated_from:"wiki_compile_concept"}}),K=$g("wiki",S),Q=await zG(_.store,{ts:g,event:"wiki_compile_completed",page_key:N,source_refs:A,chunks_seen:D.length},$),T=v(_.dbPath);try{s$(T,[z,R,Q],$),A3(T,{pageId:W,path:N,title:I,artifactUri:z.uri,contentHash:z.hash??"",body:O,provenance:L,now:g}),A3(T,{pageId:K,path:S,title:P,artifactUri:R.uri,contentHash:R.hash??"",body:X,provenance:G,now:g}),T.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) + VALUES (?, ?, ?, ?)`,[W,K,"concept",g]);let q=SG(T,W,J,g),V=WG(T,{title:I,path:N,artifactUri:z.uri,contentHash:z.hash??"",now:g});return{page_id:W,path:N,artifact_uri:z.uri,content_hash:z.hash??"",chunks_seen:D.length,citations_written:q,concept_page_id:K,indexes_updated:V,log_key:Q.key,warnings:[]}}finally{T.close()}}async function RG(_){if(!_.approveWrite)return{approved:!1,durable_writes_performed:!1,page_id:null,path:null,artifact_uri:null,citations_written:0,log_key:null,message:"Dry-run: answer filing requires --approve-write."};let $=_.now??new Date,g=$.toISOString(),U=_.prompt.length>80?`${_.prompt.slice(0,77)}...`:_.prompt,I=`wiki/answers/${O3(U)}.md`,j=_.context.citations,N=[`# ${U}`,"",_.answer,"","## Citations","",...j.map((P,S)=>`- [C${S+1}] ${P.source_ref??P.source_uri??P.artifact_path??P.artifact_uri??"unknown"} ${P.hash?`(hash ${P.hash})`:""}`),""].join(` +`),O=j.map((P)=>P.source_ref??P.source_uri).filter((P)=>Boolean(P)),A=U$({generated_from:"knowledge_answer",artifact_key:I,source_refs:O}),L=await pj(_.store,{key:I,body:N,content_type:"text/markdown",metadata:{generated_from:"knowledge_answer"}}),z=await zG(_.store,{ts:g,event:"wiki_answer_filed",page_key:I,prompt:_.prompt,citations:j.length},$),W=$g("wiki",I),J=v(_.dbPath);try{s$(J,[L,z],$),A3(J,{pageId:W,path:I,title:U,artifactUri:L.uri,contentHash:L.hash??"",body:N,provenance:A,now:g});let P=SG(J,W,j.map((S)=>({chunk_id:S.chunk_id,source_uri:S.source_uri??S.artifact_uri??"unknown",quote:S.quote,start_offset:S.start_offset,end_offset:S.end_offset,metadata:{source_ref:S.source_ref,artifact_path:S.artifact_path,revision:S.revision,hash:S.hash}})),g);return WG(J,{title:U,path:I,artifactUri:L.uri,contentHash:L.hash??"",now:g}),{approved:!0,durable_writes_performed:!0,page_id:W,path:I,artifact_uri:L.uri,citations_written:P,log_key:z.key,message:`Filed answer to ${I}`}}finally{J.close()}}function y4(_,$){_.push($)}function GG(_){h(_.dbPath);let $=v(_.dbPath),g=[];try{let U=$.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n??0,D=$.query("SELECT COUNT(*) AS n FROM citations").get()?.n??0,I=$.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n??0,j=$.query(`SELECT wp.id, wp.path FROM wiki_pages wp LEFT JOIN citations c ON c.wiki_page_id = wp.id WHERE wp.status = 'active' AND wp.path LIKE 'wiki/generated/%' GROUP BY wp.id - HAVING COUNT(c.id) = 0`).all();for(let B of G)q2(J,{type:"missing_citation",severity:"error",page_id:B.id,path:B.path,message:"Generated wiki page has no citations."});let Y=_.query(`SELECT wp.id AS page_id, wp.path, c.source_uri, c.chunk_id + HAVING COUNT(c.id) = 0`).all();for(let J of j)y4(g,{type:"missing_citation",severity:"error",page_id:J.id,path:J.path,message:"Generated wiki page has no citations."});let N=$.query(`SELECT wp.id AS page_id, wp.path, c.source_uri, c.chunk_id FROM citations c JOIN wiki_pages wp ON wp.id = c.wiki_page_id LEFT JOIN chunks ch ON ch.id = c.chunk_id - WHERE ch.metadata_json LIKE '%"stale":true%' OR ch.metadata_json LIKE '%"status":"stale"%' OR ch.metadata_json LIKE '%"status":"deleted"%'`).all();for(let B of Y)q2(J,{type:"stale_citation",severity:"warn",page_id:B.page_id,path:B.path,source_uri:B.source_uri,chunk_id:B.chunk_id??void 0,message:"Page cites a stale or deleted source chunk."});let Q=_.query(`SELECT lower(title) AS title, COUNT(*) AS n + WHERE ch.metadata_json LIKE '%"stale":true%' OR ch.metadata_json LIKE '%"status":"stale"%' OR ch.metadata_json LIKE '%"status":"deleted"%'`).all();for(let J of N)y4(g,{type:"stale_citation",severity:"warn",page_id:J.page_id,path:J.path,source_uri:J.source_uri,chunk_id:J.chunk_id??void 0,message:"Page cites a stale or deleted source chunk."});let O=$.query(`SELECT lower(title) AS title, COUNT(*) AS n FROM wiki_pages WHERE status = 'active' GROUP BY lower(title) - HAVING COUNT(*) > 1`).all();for(let B of Q)q2(J,{type:"duplicate_page",severity:"warn",message:`Duplicate active wiki title: ${B.title} (${B.n} pages).`});let q=_.query(`SELECT wp.id, wp.path + HAVING COUNT(*) > 1`).all();for(let J of O)y4(g,{type:"duplicate_page",severity:"warn",message:`Duplicate active wiki title: ${J.title} (${J.n} pages).`});let A=$.query(`SELECT wp.id, wp.path FROM wiki_pages wp LEFT JOIN wiki_backlinks wb1 ON wb1.from_page_id = wp.id LEFT JOIN wiki_backlinks wb2 ON wb2.to_page_id = wp.id WHERE wp.status = 'active' AND wp.path NOT IN ('wiki/README.md') GROUP BY wp.id - HAVING COUNT(wb1.to_page_id) = 0 AND COUNT(wb2.from_page_id) = 0`).all();for(let B of q)q2(J,{type:"orphan_page",severity:"info",page_id:B.id,path:B.path,message:"Wiki page has no backlinks."});let L=_.query(`SELECT wp.id AS page_id, wp.path, c.source_uri + HAVING COUNT(wb1.to_page_id) = 0 AND COUNT(wb2.from_page_id) = 0`).all();for(let J of A)y4(g,{type:"orphan_page",severity:"info",page_id:J.id,path:J.path,message:"Wiki page has no backlinks."});let L=$.query(`SELECT wp.id AS page_id, wp.path, c.source_uri FROM citations c JOIN wiki_pages wp ON wp.id = c.wiki_page_id LEFT JOIN sources s ON s.uri = c.source_uri - WHERE s.id IS NULL AND c.source_uri NOT LIKE 'file://%' AND c.source_uri NOT LIKE 's3://%' AND c.source_uri NOT LIKE 'https://%' AND c.source_uri NOT LIKE 'open-files://%'`).all();for(let B of L)q2(J,{type:"unresolved_source_ref",severity:"error",page_id:B.page_id,path:B.path,source_uri:B.source_uri,message:"Citation source URI cannot be resolved to a known or allowed source ref."});let N=_.query("SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'").all();for(let B of N)q2(J,{type:"contradiction_marker",severity:"warn",page_id:B.id,path:B.path,message:"Page metadata contains a contradiction marker."});let R=_.query(`SELECT c.id AS chunk_id, s.uri AS source_uri + WHERE s.id IS NULL AND c.source_uri NOT LIKE 'file://%' AND c.source_uri NOT LIKE 's3://%' AND c.source_uri NOT LIKE 'https://%' AND c.source_uri NOT LIKE 'open-files://%'`).all();for(let J of L)y4(g,{type:"unresolved_source_ref",severity:"error",page_id:J.page_id,path:J.path,source_uri:J.source_uri,message:"Citation source URI cannot be resolved to a known or allowed source ref."});let z=$.query("SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'").all();for(let J of z)y4(g,{type:"contradiction_marker",severity:"warn",page_id:J.id,path:J.path,message:"Page metadata contains a contradiction marker."});let W=$.query(`SELECT c.id AS chunk_id, s.uri AS source_uri FROM chunks c JOIN source_revisions sr ON sr.id = c.source_revision_id JOIN sources s ON s.id = sr.source_id @@ -1093,7 +1094,7 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| WHERE c.kind = 'source' GROUP BY c.id HAVING COUNT(cit.id) = 0 - LIMIT 25`).all();for(let B of R)q2(J,{type:"new_article_candidate",severity:"info",chunk_id:B.chunk_id,source_uri:B.source_uri??void 0,message:"Source chunk is indexed but not cited by any wiki page yet."});return{ok:J.every((B)=>B.severity!=="error"),issue_count:J.length,issues:J,counts:{active_pages:U,citations:W,backlinks:X,new_article_candidates:R.length}}}finally{_.close()}}import{createHash as Sn}from"crypto";function Zn($){let _=String($.getUTCFullYear()),J=String($.getUTCMonth()+1).padStart(2,"0"),U=String($.getUTCDate()).padStart(2,"0");return{year:_,month:J,day:U}}function TL($,_){return`${$}_${Sn("sha256").update(_).digest("hex").slice(0,20)}`}function vn($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function yn(){return`# Knowledge Agent Schema v1 + LIMIT 25`).all();for(let J of W)y4(g,{type:"new_article_candidate",severity:"info",chunk_id:J.chunk_id,source_uri:J.source_uri??void 0,message:"Source chunk is indexed but not cited by any wiki page yet."});return{ok:g.every((J)=>J.severity!=="error"),issue_count:g.length,issues:g,counts:{active_pages:U,citations:D,backlinks:I,new_article_candidates:W.length}}}finally{$.close()}}import{createHash as KZ}from"crypto";function VZ(_){let $=String(_.getUTCFullYear()),g=String(_.getUTCMonth()+1).padStart(2,"0"),U=String(_.getUTCDate()).padStart(2,"0");return{year:$,month:g,day:U}}function L3(_,$){return`${_}_${KZ("sha256").update($).digest("hex").slice(0,20)}`}function FZ(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function MZ(){return`# Knowledge Agent Schema v1 ## Source Rules @@ -1118,7 +1119,7 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| ## Lint Rules - Flag stale pages, missing citations, contradictions, orphan pages, duplicate pages, and unresolved source refs. -`}function hn(){return`# Knowledge Index +`}function ZZ(){return`# Knowledge Index This is a compact orientation index for agents. It is not the full search index. @@ -1133,19 +1134,19 @@ This is a compact orientation index for agents. It is not the full search index. Raw source files are resolved through open-files. This app stores source refs, citations, chunks, generated wiki artifacts, indexes, and run records. -`}function qE(){return`# Wiki +`}function YG(){return`# Wiki Generated durable knowledge pages live here. Pages should be concise, cited, and organized for both humans and agents. -`}async function zE($,_=new Date){let{year:J,month:U,day:W}=Zn(_),X="schemas/v1.md",G="indexes/root.md",Y="wiki/README.md",Q=`logs/${J}/${U}/${W}.jsonl`,q={ts:_.toISOString(),event:"wiki_layout_initialized",schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md"},L=[{key:"schemas/v1.md",body:yn(),content_type:"text/markdown"},{key:"indexes/root.md",body:hn(),content_type:"text/markdown"},{key:"wiki/README.md",body:qE(),content_type:"text/markdown"},{key:Q,body:`${JSON.stringify(q)} -`,content_type:"application/x-ndjson"}],N=await Promise.all(L.map(async(R)=>{let B=await $.put(R);return{key:B.key,uri:B.uri,kind:V3(R.key),content_type:R.content_type,modified_at:B.modified_at,metadata:{provenance:X6({generated_from:"wiki_layout_init",artifact_key:R.key,citation_required:R.key.startsWith("wiki/")||R.key.startsWith("indexes/")})},...IJ(R.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:Q,artifacts:N,written:["schemas/v1.md","indexes/root.md","wiki/README.md",Q]}}function SL($){let _=$.metadata?.provenance;if(_&&typeof _==="object"&&!Array.isArray(_))return _;return X6({generated_from:"wiki_layout_init",artifact_key:$.key})}function mn($,_,J,U,W,X){let G=SL(U),Y=TL("chk",`${_}\x00${U.hash??U.uri}`),Q=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_);for(let q of Q)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[q.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_]),$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[Y,_,"wiki",0,W,vn(W),0,W.length,JSON.stringify({artifact_key:U.key,artifact_uri:U.uri,content_hash:U.hash??null,provenance:G}),X]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[Y,W,J,U.uri])}function jE($,_,J=new Date){let U=J.toISOString(),W=_.find((G)=>G.key.endsWith("indexes/root.md")),X=_.find((G)=>G.key.endsWith("wiki/README.md"));if(W)$.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) +`}async function QG(_,$=new Date){let{year:g,month:U,day:D}=VZ($),I="schemas/v1.md",j="indexes/root.md",N="wiki/README.md",O=`logs/${g}/${U}/${D}.jsonl`,A={ts:$.toISOString(),event:"wiki_layout_initialized",schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md"},L=[{key:"schemas/v1.md",body:MZ(),content_type:"text/markdown"},{key:"indexes/root.md",body:ZZ(),content_type:"text/markdown"},{key:"wiki/README.md",body:YG(),content_type:"text/markdown"},{key:O,body:`${JSON.stringify(A)} +`,content_type:"application/x-ndjson"}],z=await Promise.all(L.map(async(W)=>{let J=await _.put(W);return{key:J.key,uri:J.uri,kind:ZS(W.key),content_type:W.content_type,modified_at:J.modified_at,metadata:{provenance:U$({generated_from:"wiki_layout_init",artifact_key:W.key,citation_required:W.key.startsWith("wiki/")||W.key.startsWith("indexes/")})},...L0(W.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:O,artifacts:z,written:["schemas/v1.md","indexes/root.md","wiki/README.md",O]}}function J3(_){let $=_.metadata?.provenance;if($&&typeof $==="object"&&!Array.isArray($))return $;return U$({generated_from:"wiki_layout_init",artifact_key:_.key})}function bZ(_,$,g,U,D,I){let j=J3(U),N=L3("chk",`${$}\x00${U.hash??U.uri}`),O=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($);for(let A of O)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[A.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$]),_.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,$,"wiki",0,D,FZ(D),0,D.length,JSON.stringify({artifact_key:U.key,artifact_uri:U.uri,content_hash:U.hash??null,provenance:j}),I]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[N,D,g,U.uri])}function TG(_,$,g=new Date){let U=g.toISOString(),D=$.find((j)=>j.key.endsWith("indexes/root.md")),I=$.find((j)=>j.key.endsWith("wiki/README.md"));if(D)_.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[TL("idx","root:indexes/root.md"),"root","root",W.uri,"root",JSON.stringify({artifact_key:W.key,content_hash:W.hash??null,provenance:SL(W)}),U,U]);if(X){let G=TL("wiki","wiki/README.md");$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + updated_at = excluded.updated_at`,[L3("idx","root:indexes/root.md"),"root","root",D.uri,"root",JSON.stringify({artifact_key:D.key,content_hash:D.hash??null,provenance:J3(D)}),U,U]);if(I){let j=L3("wiki","wiki/README.md");_.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title = excluded.title, @@ -1153,13 +1154,13 @@ Pages should be concise, cited, and organized for both humans and agents. content_hash = excluded.content_hash, status = excluded.status, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[G,"wiki/README.md","Wiki",X.uri,X.hash??null,"active",JSON.stringify({artifact_key:X.key,provenance:SL(X)}),U,U]),mn($,G,"Wiki",X,qE(),U)}}import{createHash as DE}from"crypto";import{cpSync as uL,chmodSync as vL,existsSync as c6,lstatSync as NE,mkdirSync as rG,readdirSync as dL,readFileSync as lX,renameSync as xn,rmSync as oG,writeFileSync as OE}from"fs";import{dirname as yL,join as e4,relative as un}from"path";function hL($,_=$){if(!c6($))return[];let J=NE($);if(J.isFile())return[un(_,$)||"."];if(!J.isDirectory())return[];return dL($).flatMap((U)=>hL(e4($,U),_)).sort()}function LE($,_){if(_.length===0)return{sha256:null,bytes:0};let J=DE("sha256"),U=0;for(let W of _){let X=e4($,W),G=lX(X),Y=DE("sha256").update(G).digest("hex");U+=G.byteLength,J.update(W),J.update("\x00"),J.update(Y),J.update("\x00")}return{sha256:J.digest("hex"),bytes:U}}function dn($){if(!c6($))return null;let _=JSON.parse(lX($,"utf8"));return Array.isArray(_.items)?_.items.length:null}function nn($){if(!c6($))return{exists:!1,integrity_check:null,table_counts:{}};let _=W3($);try{let J=_.query("PRAGMA integrity_check").get(),U=J?Object.values(J)[0]??null:null,W=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),X={};for(let G of W){let Y=`"${G.name.replaceAll('"','""')}"`,Q=_.query(`SELECT COUNT(*) AS n FROM ${Y}`).get();X[G.name]=Q?.n??0}return{exists:!0,integrity_check:U,table_counts:X}}finally{_.close()}}function y_($,_={}){let J=hL($.home),U=LE($.home,J),W=hL($.artifactsDir),X=LE($.artifactsDir,W),G=c6($.knowledgeDbPath);return{path:$.home,exists:c6($.home),file_count:J.length,total_bytes:U.bytes,tree_sha256:U.sha256,json_items:dn($.jsonStorePath),sqlite:_.includeSqlite===!1?{exists:G,integrity_check:null,table_counts:{}}:nn($.knowledgeDbPath),artifacts:{exists:c6($.artifactsDir),file_count:W.length,total_bytes:X.bytes,tree_sha256:X.sha256},files:J}}function cn($,_){if(!_.exists)return!0;if(_.files.filter((U)=>U!=="config.json").length>0)return!1;if(!_.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(lX($.configPath,"utf8")))===JSON.stringify(dW())}catch{return!1}}function mL($,_){return $.file_count===_.file_count&&$.total_bytes===_.total_bytes&&$.tree_sha256===_.tree_sha256&&$.json_items===_.json_items&&$.sqlite.integrity_check===_.sqlite.integrity_check&&JSON.stringify($.sqlite.table_counts)===JSON.stringify(_.sqlite.table_counts)&&$.artifacts.file_count===_.artifacts.file_count&&$.artifacts.total_bytes===_.artifacts.total_bytes&&$.artifacts.tree_sha256===_.artifacts.tree_sha256}function pG($){return $.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function xL($){if(Array.isArray($))return`[${$.map(xL).join(",")}]`;if($&&typeof $==="object")return`{${Object.entries($).sort(([_],[J])=>_.localeCompare(J)).map(([_,J])=>`${JSON.stringify(_)}:${xL(J)}`).join(",")}}`;return JSON.stringify($)}function BE($){return xL($)}function ZL($){return typeof $.short_id==="string"&&$.short_id.trim().length>0?$.short_id:null}function z2($){if(!c6($))return{items:[]};let _=JSON.parse(lX($,"utf8"));if(!_||!Array.isArray(_.items))throw Error(`Invalid knowledge JSON store shape at ${$}`);return{items:_.items}}function HE($,_){let J=new Map($.items.map((L)=>[L.id,L])),U=new Map;for(let L of $.items){let N=U.get(L.id);if(N&&N.item.id!==L.id);U.set(L.id,{item:L,keyKind:"id",source:"current"});let R=ZL(L);if(R&&!U.has(R))U.set(R,{item:L,keyKind:"short_id",source:"current"})}let W=[],X=0,G=0,Y=0,Q=[];for(let L of _.items){let N=J.get(L.id);if(N){if(BE(N)===BE(L))X+=1;else G+=1,W.push({type:"id_conflict",id:L.id,legacy_title:L.title,current_title:N.title});continue}let R=[{key:L.id,keyKind:"id"},...ZL(L)?[{key:ZL(L),keyKind:"short_id"}]:[]],B=!1;for(let{key:H,keyKind:V}of R){let K=U.get(H);if(!K)continue;if(V==="id"&&K.keyKind==="id")G+=1,W.push({type:"id_conflict",id:H,legacy_id:L.id,current_id:K.item.id,legacy_title:L.title,current_title:K.item.title});else Y+=1,W.push({type:"short_id_conflict",id:H,legacy_id:L.id,current_id:K.item.id,legacy_title:L.title,current_title:K.item.title});B=!0}if(B)continue;Q.push(L);for(let{key:H,keyKind:V}of R)U.set(H,{item:L,keyKind:V,source:"legacy"})}let q={items:[...$.items,...Q]};return{stats:{current_items:$.items.length,legacy_items:_.items.length,duplicate_ids_identical:X,duplicate_ids_conflicting:G,short_id_conflicts:Y,stranded_items:Q.length,merged_items:W.length===0?Q.length:0,expected_total_items:$.items.length+Q.length,final_items:null},conflicts:W,mergedStore:q}}function ln($,_){let J=[...new Set($)].sort(),U=(W)=>{if(W>=J.length)return _();return $4(J[W],()=>U(W+1),{createParent:!0})};return U(0)}function VE($){let _=$.now??new Date,J=$.approveWrite!==!0,U=y_($.legacy),W=y_($.current),X={legacy_exists:U.exists,legacy_store_exists:c6($.legacy.jsonStorePath),current_store_exists:c6($.current.jsonStorePath),approval_present:$.approveWrite===!0&&Boolean($.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},G=[];if(!U.exists||!X.legacy_store_exists)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:U,current_before:W,backup_after:null,current_after:W,merge:{current_items:z2($.current.jsonStorePath).items.length,legacy_items:0,duplicate_ids_identical:0,duplicate_ids_conflicting:0,short_id_conflicts:0,stranded_items:0,merged_items:0,expected_total_items:z2($.current.jsonStorePath).items.length,final_items:W.json_items},conflicts:[],checks:{...X,no_conflicts:!0,final_count_matches_expected:!0},warnings:G,message:`No legacy knowledge JSON store found at ${$.legacy.jsonStorePath}`};let Y=z2($.current.jsonStorePath),Q=z2($.legacy.jsonStorePath),q=HE(Y,Q);if(X.no_conflicts=q.conflicts.length===0,q.conflicts.length>0)G.push("merge_conflicts_detected");if(!X.approval_present)G.push("write_approval_required");if(J||!X.approval_present||q.conflicts.length>0)return{ok:q.conflicts.length===0,dry_run:!0,approval_required:!X.approval_present,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:`${$.legacy.home}.merge-backup-${pG(_)}`,legacy_before:U,current_before:W,backup_after:null,current_after:null,merge:q.stats,conflicts:q.conflicts,checks:X,warnings:G,message:q.conflicts.length===0?`Dry run: would merge ${q.stats.stranded_items} legacy item(s) into ${$.current.jsonStorePath}`:`Refusing legacy merge with ${q.conflicts.length} conflict(s)`};return ln([$.current.jsonStorePath,$.legacy.jsonStorePath],()=>{let L=z2($.current.jsonStorePath),N=z2($.legacy.jsonStorePath),R=HE(L,N);if(X.no_conflicts=R.conflicts.length===0,R.conflicts.length>0)return{ok:!1,dry_run:!0,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:y_($.legacy),current_before:y_($.current),backup_after:null,current_after:null,merge:R.stats,conflicts:R.conflicts,checks:X,warnings:[...G,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${R.conflicts.length} conflict(s)`};if(R.stats.stranded_items===0)return R.stats.final_items=L.items.length,X.final_count_matches_expected=L.items.length===R.stats.expected_total_items,{ok:X.no_conflicts&&X.final_count_matches_expected,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:y_($.legacy),current_before:y_($.current),backup_after:null,current_after:y_($.current),merge:R.stats,conflicts:[],checks:X,warnings:G,message:`Legacy merge already up to date for ${$.current.jsonStorePath}`};let B=`${$.legacy.home}.merge-backup-${pG(_)}`;rG(yL(B),{recursive:!0}),uL($.legacy.home,B,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let H=s_(B),V=y_(H);if(X.legacy_backup_written=mL(y_($.legacy),V),!X.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${B}`);F4($.current.jsonStorePath,R.mergedStore);let K=z2($.current.jsonStorePath);R.stats.final_items=K.items.length,X.final_count_matches_expected=K.items.length===R.stats.expected_total_items;let E=y_($.current),F=X.legacy_backup_written&&X.no_conflicts&&X.final_count_matches_expected;return{ok:F,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:B,legacy_before:U,current_before:W,backup_after:V,current_after:E,merge:R.stats,conflicts:[],checks:X,warnings:G,message:F?`Merged ${R.stats.merged_items} legacy item(s) into ${$.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${$.current.jsonStorePath}`}})}function rn($){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,$)}function nL($){return $ instanceof Error&&/\b(EBUSY|EPERM)\b/.test($.message)}function pn($){let _;for(let J=0;J<8;J+=1)try{oG($,{recursive:!0,force:!1});return}catch(U){if(_=U,!nL(U))throw U;rn(50*(J+1))}throw _}function RE($){if(!c6($))return;let _=NE($);if(vL($,_.isDirectory()?448:384),!_.isDirectory())return;for(let J of dL($))RE(e4($,J))}function on($){return $==="TOMBSTONE.md"||$==="migration.json"||$==="knowledge.db"||$==="knowledge.db-shm"||$==="knowledge.db-wal"||$==="knowledge.db-journal"}function tn($){for(let _ of dL($)){if(_==="TOMBSTONE.md"||_==="migration.json")continue;try{oG(e4($,_),{recursive:!0,force:!1})}catch(J){if(!nL(J)||!_.startsWith("knowledge.db"))throw J}}}function an($,_){try{xn($,_);return}catch(J){uL($,_,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{pn($)}catch(U){if(nL(U)){tn($);return}throw oG(_,{recursive:!0,force:!0}),U}if(J instanceof Error&&J.message.includes("EXDEV"))return}}function sn($,_,J){if(!_.exists)return!1;if(!_.files.includes("TOMBSTONE.md")||!_.files.includes("migration.json"))return!1;if(_.files.some((U)=>!on(U)))return!1;try{let U=JSON.parse(lX(e4($.home,"migration.json"),"utf8"));return U.new_path===J&&typeof U.backup_path==="string"}catch{return!1}}function KE($){let _=$.now??new Date,J=$.approveWrite!==!0,U=y_($.current),W=cn($.current,U),X=$.approveWrite===!0&&Boolean($.approvedBy)&&(!U.exists||W),G=y_($.legacy,{includeSqlite:!X}),Y={legacy_exists:G.exists,current_absent_or_default_scaffold:!U.exists||W,approval_present:$.approveWrite===!0&&Boolean($.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},Q=[];if(!G.exists)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,tombstone_path:null,legacy_before:G,current_before:U,backup_after:null,current_after:null,checks:Y,warnings:Q,message:`No legacy knowledge workspace found at ${$.legacy.home}`};if(Y.legacy_is_tombstone=sn($.legacy,G,$.current.home),Y.legacy_is_tombstone)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,tombstone_path:e4($.legacy.home,"TOMBSTONE.md"),legacy_before:G,current_before:U,backup_after:null,current_after:U,checks:{...Y,tombstone_written:!0},warnings:Q,message:`Legacy knowledge workspace already migrated to ${$.current.home}`};if(!Y.current_absent_or_default_scaffold)Q.push("current_workspace_contains_data");if(!Y.approval_present)Q.push("write_approval_required");if(J||!Y.current_absent_or_default_scaffold||!Y.approval_present)return{ok:Y.current_absent_or_default_scaffold,dry_run:!0,approval_required:!0,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:`${$.legacy.home}.backup-${pG(_)}`,tombstone_path:e4($.legacy.home,"TOMBSTONE.md"),legacy_before:G,current_before:U,backup_after:null,current_after:null,checks:Y,warnings:Q,message:Y.current_absent_or_default_scaffold?`Dry run: would migrate ${$.legacy.home} to ${$.current.home}`:`Cannot migrate while ${$.current.home} contains data`};let q=`${$.legacy.home}.backup-${pG(_)}`;rG(yL($.current.home),{recursive:!0}),rG(yL(q),{recursive:!0}),uL($.legacy.home,q,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),RE(q);let L=s_(q),N=y_(L,{includeSqlite:!1});if(Y.backup_matches_legacy=mL(G,N),!Y.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${q}`);if(U.exists&&W)oG($.current.home,{recursive:!0,force:!0});an($.legacy.home,$.current.home);let R=y_($.current,{includeSqlite:!1});Y.migrated_matches_backup=mL(N,R);let B=y_(L),H=y_($.current),V={...B,path:$.legacy.home};rG($.legacy.home,{recursive:!0});let K=e4($.legacy.home,"TOMBSTONE.md");OE(K,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${_.toISOString()}`,`Approved by: ${$.approvedBy}`,`New path: ${$.current.home}`,`Backup path: ${q}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` -`),{mode:384}),vL(K,384);let E=e4($.legacy.home,"migration.json");OE(E,`${JSON.stringify({migrated_at:_.toISOString(),approved_by:$.approvedBy,new_path:$.current.home,backup_path:q,legacy_before:V,backup_after:B,current_after:H},null,2)} -`,{mode:384}),vL(E,384),Y.tombstone_written=c6(K);let F=Y.backup_matches_legacy&&Y.migrated_matches_backup&&Y.tombstone_written;return{ok:F,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:q,tombstone_path:K,legacy_before:V,current_before:U,backup_after:B,current_after:H,checks:Y,warnings:Q,message:F?`Migrated legacy knowledge workspace to ${$.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${$.current.home}`}}function Jc($){let _=ZE($);if(e$(FE(_,"knowledge.db"))||e$(FE(_,"config.json")))return b2(_);return b2(s_(VY(_)).home)}function cL($){return`${_c()}:${pX("sha256").update($.home).digest("hex").slice(0,12)}`}function rL($){return`'${$.replace(/'/g,"'\\''")}'`}function Wc($){return["knowledge",...$].map(rL).join(" ")}function EE($,_){return`cd ${rL($)} && knowledge ${_.map(rL).join(" ")}`}function vE($){return!$||$==="local"||$==="localhost"}function rX($,_){return{source:$.source,adapter:$.adapter,project_root:_,project_root_source:$.project_root_source,workspace_root:$.workspace_root,workspace_root_source:$.workspace_root_source,open_files_root:$.open_files_root,open_files_root_source:$.open_files_root_source,trust_status:$.trust_status,auth_status:$.auth_status,current:$.current,primary:$.primary,diagnostics:$.diagnostics,repair_hints:$.repair_hints,evidence:$.evidence,cacheability:$.cacheability,warnings:$.warnings}}function iL($){return{source:$.source,adapter:$.adapter,target:$.target,route:$.route,target_kind:$.targetKind,confidence:$.confidence,evidence:$.evidence,cacheability:$.cacheability}}function Uc($){try{let _=JSON.parse($);return Array.isArray(_)?_.filter((J)=>typeof J==="string"):[]}catch{return[]}}function oX($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function E_($){return typeof $==="string"&&$.length>0?$:null}function Xc($){return typeof $==="number"&&Number.isFinite($)?$:null}function tG($){return typeof $==="boolean"?$:null}function Gc($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function yE($,_,J){let U=oX($),W=E_(U.observed_at)??E_(_[`${J}_observed_at`]),X=E_(U.source_authority)??E_(_[`${J}_source_authority`]);if(!W||!X)return null;return{observed_at:W,verified_at:E_(U.verified_at),expires_at:E_(U.expires_at)??E_(_[`${J}_expires_at`]),ttl_ms:Xc(U.ttl_ms),source_authority:X,confidence:E_(U.confidence)??(J==="route"?E_(_.route_confidence):null),cacheable:tG(U.cacheable)??tG(_[`${J}_cacheable`])??!1,stale:tG(U.stale)??tG(_[`${J}_stale`])??!1,reasons:Gc(U.reasons)}}function Yc($,_){return $.machine_id===_||$.hostname===_||$.ssh_target===_||$.tailscale_dns===_||Uc($.tailscale_ips_json).includes(_)}function ME($,_){return Wq($).find((J)=>Yc(J,_))??null}function hE($){return oX(j2($.metadata_json).resolver_evidence)}function tX($){return oX(j2($.capabilities_json).resolver)}function mE($){let _=tX($),J=E_(_.route_kind);if(J==="local"||J==="lan"||J==="tailscale"||J==="ssh"||J==="unknown")return J;if($.tailscale_dns&&$.ssh_target===$.tailscale_dns)return"tailscale";return $.ssh_target?"ssh":"unknown"}function Qc($){let _=tX($),J=E_(_.route_target_kind);if(J==="local"||J==="lan"||J==="tailscale"||J==="ssh"||J==="unknown")return J;return mE($)}function qc($){return E_(tX($).route_confidence)??"medium"}function AE($,_,J){let U=hE($),W=oX(U.route),X=tX($);return{target:$.ssh_target??$.tailscale_dns??$.hostname??$.machine_id,route:mE($),targetKind:Qc($),confidence:qc($),source:"registry",adapter:J.adapter,evidence:{registry:!0,requested_machine_id:_,machine_id:$.machine_id,recorded_at:$.updated_at,route:W},cacheability:yE(W.cacheability,X,"route")??J.cacheability,warnings:[...new Set([...J.warnings,"registry_route_fallback"])]}}function bE($,_,J){if(!$.workspace_home)return null;let U=hE($),W=oX(U.workspace),X=tX($);return{ok:!0,source:"registry",adapter:J.adapter,requested_machine_id:_,machine_id:$.machine_id,project_id:E_(W.project_id)??J.project_id,repo_name:E_(W.repo_name)??J.repo_name,project_root:$.workspace_home,project_root_source:E_(X.project_root_source)??"registry",workspace_root:E_(W.workspace_root),workspace_root_source:E_(X.workspace_root_source)??"registry",open_files_root:E_(W.open_files_root),open_files_root_source:E_(X.open_files_root_source)??"registry",trust_status:E_(X.trust_status)??"unknown",auth_status:E_(X.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:_,machine_id:$.machine_id,recorded_at:$.updated_at,workspace:W},cacheability:yE(W.cacheability,X,"workspace")??J.cacheability,warnings:[...new Set([...J.warnings,"registry_workspace_fallback"])]}}function wE($){if(!$)return null;let _=$.diagnostics.filter((U)=>U.severity!=="ok"),J=$.repair_hints[0];if(!_.length&&!$.warnings.length&&!J)return null;return[_.length?`workspace diagnostics: ${_.map((U)=>`${U.id}=${U.status}`).join(", ")}`:null,$.warnings.length?`warnings: ${$.warnings.join(", ")}`:null,J?`repair: ${J.shell_command}`:null].filter(Boolean).join("; ")}function aG($){return{id:$.id,reason:$.reason,command:["knowledge",...$.args],shell_command:Wc($.args)}}function sG($,_){let J=m($);try{return Number(J.query(_).get()?.count??0)}finally{J.close()}}function zc($,_){let J=sG($,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),U=sG($,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),W=sG($,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),X=sG($,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),G=X===0;return{ok:G,source_of_truth:"open-files",configured_root:_?.open_files_root??null,configured_root_source:_?.open_files_root_source??null,source_refs:{open_files:J,metadata_mentions:U},extracted_text_artifacts:W,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:X,message:G?`${J} open-files source ref(s); raw source bytes remain owned by open-files`:`${X} raw source payload metadata sentinel(s) found`}}var jc=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function pL($,_=0){if(_>8)return!1;if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some((J)=>pL(J,_+1));for(let[J,U]of Object.entries($)){if(jc.has(J.toLowerCase()))return!0;if(pL(U,_+1))return!0}return!1}function j2($){try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function gE($,_=20,J=200){if(!Number.isFinite($)||$<=0)return _;return Math.min(Math.floor($),J)}function Dc($,_=220){let J=$??"";return J.length>_?`${J.slice(0,_)}...`:J}function K6($,_=["metadata_json"]){return $.map((J)=>{let U={...J};for(let W of _){let X=U[W];if(typeof X==="string"){let G=W.endsWith("_json")?W.slice(0,-5):W;U[G]=j2(X),delete U[W]}}return U})}function eG($){if(typeof $!=="string")return[];try{let _=JSON.parse($);return Array.isArray(_)?_:[]}catch{return[]}}function oL($){if(typeof $!=="string")return{};return j2($)}function Oc($){let _={...$};return _.source_refs=eG(_.source_refs_json),_.evidence_refs=eG(_.evidence_refs_json),_.requires_approval=_.requires_approval===1||_.requires_approval===!0,_.checks=oL(_.checks_json),_.metadata=oL(_.metadata_json),delete _.source_refs_json,delete _.evidence_refs_json,delete _.checks_json,delete _.metadata_json,_}function Lc($){let _={...$};return _.source_refs=eG(_.source_refs_json),_.evidence_refs=eG(_.evidence_refs_json),_.metadata=oL(_.metadata_json),delete _.source_refs_json,delete _.evidence_refs_json,delete _.metadata_json,_}function l_($,_,J=[]){return $.query(_).all(...J)}function Bc($){if(!e$($))return{exists:!1,read_error:null,items:[]};try{let _=JSON.parse($c($,"utf8"));if(!_||!Array.isArray(_.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:_.items}}catch(_){return{exists:!0,read_error:_ instanceof Error?_.message:String(_),items:[]}}}function kE($){return{id:$.id,short_id:$.short_id??null,title:$.title,content_preview:Dc($.content),url:$.url??null,tags:$.tags??[],metadata:$.metadata??{},archived:$.archived===!0,created_at:$.created_at,updated_at:$.updated_at}}function IE(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0,promotion_candidates:0,durable_records:0}}function xE($,_,J=!1){return{query:$,limit:_,offset:0,mode:{keyword:!0,catalog:!0,semantic:J},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function Hc($){return $.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function Nc($,_,J=!1){let U=xE($,_,J);return{query:$,normalized_query:Hc($),created_at:new Date().toISOString(),mode:U.mode,warnings:U.warnings,search_counts:U.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function lL($,_,J){let U=J??_.jsonStorePath;if(e$(U))return U;if($==="global"){let W=uW();if(e$(W))return W}return U}function Vc($){let _=JSON.stringify($);return Math.max(1,Math.ceil(_.length/4))}function tL($,_){let J=($??"").normalize("NFKC").trim().replace(/\s+/g," ");if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-1)).trim()}...`}function fE($,_,J){let U=k_(tL($,J),_);return{text:U.text,redactions:U.findings.length}}function CE($,_,J){let U=$.now??new Date,W=$.source??"search",X=$.purpose??(W==="loops"||W==="runs"?"proposal":"agent_context"),G=($.query??$.topic??_.query).normalize("NFKC").trim().replace(/\s+/g," "),Y=Math.max(1,Math.min($.maxItems??$.limit??8,50)),Q=Math.max(500,Math.min($.maxTokens??6000,1e5)),q=0,L=_.citations.slice(0,Math.max(Y*2,Y)).map((F,w)=>{let A=fE(F.quote,J,w<3?220:140);q+=A.redactions;let g=F.source_ref??F.source_uri??F.artifact_path??F.artifact_uri??F.id;return{id:`cite_${pX("sha256").update(`${F.id}\x00${g}`).digest("hex").slice(0,12)}`,kind:F.artifact_uri||F.artifact_path?"artifact":"source",ref:g,source_ref:F.source_ref,source_uri:F.source_uri,artifact_uri:F.artifact_uri,artifact_path:F.artifact_path,run_id:null,run_event_id:null,revision:F.revision,hash:F.hash,chunk_id:F.chunk_id,offsets:{start:F.start_offset,end:F.end_offset},quote_preview:A.text}}),N=new Map(_.citations.map((F,w)=>[F.id,L[w]])),R=_.excerpts.slice(0,Math.max(Y*2,Y)).map((F)=>{let w=_.results.find((v)=>v.id===F.result_id),A=F.citation_id?N.get(F.citation_id):void 0,g=fE(F.text,J,520);return q+=g.redactions,{id:`ev_${pX("sha256").update(`${F.kind}\x00${F.result_id}\x00${F.citation_id??""}`).digest("hex").slice(0,14)}`,kind:F.kind,title:tL(w?.title??A?.ref??F.kind,100),text_preview:g.text,score:Number(F.score.toFixed(6)),citation_ids:A?[A.id]:[],provenance:{source:W,record_ref:`${F.kind}:${F.result_id}`,created_at:_.created_at,updated_at:null,metadata_keys:[]}}}).sort((F,w)=>w.score-F.score||F.id.localeCompare(w.id)).slice(0,Y),B=new Set(R.flatMap((F)=>F.citation_ids)),H=L.filter((F)=>B.has(F.id)),V=Array.from(new Set(_.warnings)),K=`ctx_${pX("sha256").update([W,X,G,V.join(","),R.map((F)=>F.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,E={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:U.toISOString(),source:W,purpose:X,query:G,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:K,budgets:{max_tokens:Q,estimated_tokens:0,max_items:Y,items_included:R.length,items_available:_.excerpts.length,items_truncated:Math.max(0,_.excerpts.length-R.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:q,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:H,evidence:R,duplicate_candidates:[],outline:{title:G?`Knowledge context: ${tL(G,80)}`:"Knowledge context",bullets:R.length>0?R.slice(0,5).map((F)=>`${F.id}: ${F.title}`):["No matching bounded evidence was found."],evidence_ids:R.slice(0,8).map((F)=>F.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:V,message:`${R.length} bounded evidence item(s), estimated under ${Q} token(s)`};return E.budgets.estimated_tokens=Vc(E),E.budgets.token_budget_exceeded=E.budgets.estimated_tokens>Q,E.message=`${E.evidence.length} bounded evidence item(s), estimated ${E.budgets.estimated_tokens}/${Q} token(s)`,E}function Rc(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function Kc(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function Fc($){return{ok:!0,scope:$.scope,workspace_home:$.workspaceHome,sqlite_schema_version:0,local_machine_id:$.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function PE($){let _=$.now??new Date,J=$.source??"search",U=$.purpose??(J==="loops"||J==="runs"?"proposal":"agent_context"),W=($.query??$.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),X=Math.max(1,Math.min($.maxItems??$.limit??8,50)),G=Math.max(500,Math.min($.maxTokens??6000,1e5)),Y=`ctx_${pX("sha256").update(["empty",J,U,W,$.topic??"",$.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:_.toISOString(),source:J,purpose:U,query:W,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:Y,budgets:{max_tokens:G,estimated_tokens:0,max_items:X,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:W?`Context for ${W}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${G} token(s)`}}function aL($){let _=$.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return _?`${_}/`:null}function Ec($,_){let J=m($);try{let U=J.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json + updated_at = excluded.updated_at`,[j,"wiki/README.md","Wiki",I.uri,I.hash??null,"active",JSON.stringify({artifact_key:I.key,provenance:J3(I)}),U,U]),bZ(_,j,"Wiki",I,YG(),U)}}import{createHash as qG}from"crypto";import{cpSync as G3,chmodSync as z3,existsSync as V$,lstatSync as MG,mkdirSync as ej,readdirSync as Y3,readFileSync as EU,renameSync as HZ,rmSync as sj,writeFileSync as BG}from"fs";import{dirname as S3,join as L6,relative as kZ}from"path";function W3(_,$=_){if(!V$(_))return[];let g=MG(_);if(g.isFile())return[kZ($,_)||"."];if(!g.isDirectory())return[];return Y3(_).flatMap((U)=>W3(L6(_,U),$)).sort()}function KG(_,$){if($.length===0)return{sha256:null,bytes:0};let g=qG("sha256"),U=0;for(let D of $){let I=L6(_,D),j=EU(I),N=qG("sha256").update(j).digest("hex");U+=j.byteLength,g.update(D),g.update("\x00"),g.update(N),g.update("\x00")}return{sha256:g.digest("hex"),bytes:U}}function CZ(_){if(!V$(_))return null;let $=JSON.parse(EU(_,"utf8"));return Array.isArray($.items)?$.items.length:null}function rZ(_){if(!V$(_))return{exists:!1,integrity_check:null,table_counts:{}};let $=zS(_);try{let g=$.query("PRAGMA integrity_check").get(),U=g?Object.values(g)[0]??null:null,D=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),I={};for(let j of D){let N=`"${j.name.replaceAll('"','""')}"`,O=$.query(`SELECT COUNT(*) AS n FROM ${N}`).get();I[j.name]=O?.n??0}return{exists:!0,integrity_check:U,table_counts:I}}finally{$.close()}}function d_(_,$={}){let g=W3(_.home),U=KG(_.home,g),D=W3(_.artifactsDir),I=KG(_.artifactsDir,D),j=V$(_.knowledgeDbPath);return{path:_.home,exists:V$(_.home),file_count:g.length,total_bytes:U.bytes,tree_sha256:U.sha256,json_items:CZ(_.jsonStorePath),sqlite:$.includeSqlite===!1?{exists:j,integrity_check:null,table_counts:{}}:rZ(_.knowledgeDbPath),artifacts:{exists:V$(_.artifactsDir),file_count:D.length,total_bytes:I.bytes,tree_sha256:I.sha256},files:g}}function vZ(_,$){if(!$.exists)return!0;if($.files.filter((U)=>U!=="config.json").length>0)return!1;if(!$.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(EU(_.configPath,"utf8")))===JSON.stringify(Fg())}catch{return!1}}function X3(_,$){return _.file_count===$.file_count&&_.total_bytes===$.total_bytes&&_.tree_sha256===$.tree_sha256&&_.json_items===$.json_items&&_.sqlite.integrity_check===$.sqlite.integrity_check&&JSON.stringify(_.sqlite.table_counts)===JSON.stringify($.sqlite.table_counts)&&_.artifacts.file_count===$.artifacts.file_count&&_.artifacts.total_bytes===$.artifacts.total_bytes&&_.artifacts.tree_sha256===$.artifacts.tree_sha256}function aj(_){return _.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function R3(_){if(Array.isArray(_))return`[${_.map(R3).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).sort(([$],[g])=>$.localeCompare(g)).map(([$,g])=>`${JSON.stringify($)}:${R3(g)}`).join(",")}}`;return JSON.stringify(_)}function VG(_){return R3(_)}function P3(_){return typeof _.short_id==="string"&&_.short_id.trim().length>0?_.short_id:null}function h4(_){if(!V$(_))return{items:[]};let $=JSON.parse(EU(_,"utf8"));if(!$||!Array.isArray($.items))throw Error(`Invalid knowledge JSON store shape at ${_}`);return{items:$.items}}function FG(_,$){let g=new Map(_.items.map((L)=>[L.id,L])),U=new Map;for(let L of _.items){let z=U.get(L.id);if(z&&z.item.id!==L.id);U.set(L.id,{item:L,keyKind:"id",source:"current"});let W=P3(L);if(W&&!U.has(W))U.set(W,{item:L,keyKind:"short_id",source:"current"})}let D=[],I=0,j=0,N=0,O=[];for(let L of $.items){let z=g.get(L.id);if(z){if(VG(z)===VG(L))I+=1;else j+=1,D.push({type:"id_conflict",id:L.id,legacy_title:L.title,current_title:z.title});continue}let W=[{key:L.id,keyKind:"id"},...P3(L)?[{key:P3(L),keyKind:"short_id"}]:[]],J=!1;for(let{key:P,keyKind:S}of W){let X=U.get(P);if(!X)continue;if(S==="id"&&X.keyKind==="id")j+=1,D.push({type:"id_conflict",id:P,legacy_id:L.id,current_id:X.item.id,legacy_title:L.title,current_title:X.item.title});else N+=1,D.push({type:"short_id_conflict",id:P,legacy_id:L.id,current_id:X.item.id,legacy_title:L.title,current_title:X.item.title});J=!0}if(J)continue;O.push(L);for(let{key:P,keyKind:S}of W)U.set(P,{item:L,keyKind:S,source:"legacy"})}let A={items:[..._.items,...O]};return{stats:{current_items:_.items.length,legacy_items:$.items.length,duplicate_ids_identical:I,duplicate_ids_conflicting:j,short_id_conflicts:N,stranded_items:O.length,merged_items:D.length===0?O.length:0,expected_total_items:_.items.length+O.length,final_items:null},conflicts:D,mergedStore:A}}function fZ(_,$){let g=[...new Set(_)].sort(),U=(D)=>{if(D>=g.length)return $();return v$(g[D],()=>U(D+1),{createParent:!0})};return U(0)}function ZG(_){let $=_.now??new Date,g=_.approveWrite!==!0,U=d_(_.legacy),D=d_(_.current),I={legacy_exists:U.exists,legacy_store_exists:V$(_.legacy.jsonStorePath),current_store_exists:V$(_.current.jsonStorePath),approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},j=[];if(!U.exists||!I.legacy_store_exists)return{ok:!0,dry_run:g,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:U,current_before:D,backup_after:null,current_after:D,merge:{current_items:h4(_.current.jsonStorePath).items.length,legacy_items:0,duplicate_ids_identical:0,duplicate_ids_conflicting:0,short_id_conflicts:0,stranded_items:0,merged_items:0,expected_total_items:h4(_.current.jsonStorePath).items.length,final_items:D.json_items},conflicts:[],checks:{...I,no_conflicts:!0,final_count_matches_expected:!0},warnings:j,message:`No legacy knowledge JSON store found at ${_.legacy.jsonStorePath}`};let N=h4(_.current.jsonStorePath),O=h4(_.legacy.jsonStorePath),A=FG(N,O);if(I.no_conflicts=A.conflicts.length===0,A.conflicts.length>0)j.push("merge_conflicts_detected");if(!I.approval_present)j.push("write_approval_required");if(g||!I.approval_present||A.conflicts.length>0)return{ok:A.conflicts.length===0,dry_run:!0,approval_required:!I.approval_present,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.merge-backup-${aj($)}`,legacy_before:U,current_before:D,backup_after:null,current_after:null,merge:A.stats,conflicts:A.conflicts,checks:I,warnings:j,message:A.conflicts.length===0?`Dry run: would merge ${A.stats.stranded_items} legacy item(s) into ${_.current.jsonStorePath}`:`Refusing legacy merge with ${A.conflicts.length} conflict(s)`};return fZ([_.current.jsonStorePath,_.legacy.jsonStorePath],()=>{let L=h4(_.current.jsonStorePath),z=h4(_.legacy.jsonStorePath),W=FG(L,z);if(I.no_conflicts=W.conflicts.length===0,W.conflicts.length>0)return{ok:!1,dry_run:!0,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:d_(_.legacy),current_before:d_(_.current),backup_after:null,current_after:null,merge:W.stats,conflicts:W.conflicts,checks:I,warnings:[...j,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${W.conflicts.length} conflict(s)`};if(W.stats.stranded_items===0)return W.stats.final_items=L.items.length,I.final_count_matches_expected=L.items.length===W.stats.expected_total_items,{ok:I.no_conflicts&&I.final_count_matches_expected,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:d_(_.legacy),current_before:d_(_.current),backup_after:null,current_after:d_(_.current),merge:W.stats,conflicts:[],checks:I,warnings:j,message:`Legacy merge already up to date for ${_.current.jsonStorePath}`};let J=`${_.legacy.home}.merge-backup-${aj($)}`;ej(S3(J),{recursive:!0}),G3(_.legacy.home,J,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let P=D$(J),S=d_(P);if(I.legacy_backup_written=X3(d_(_.legacy),S),!I.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${J}`);t$(_.current.jsonStorePath,W.mergedStore);let X=h4(_.current.jsonStorePath);W.stats.final_items=X.items.length,I.final_count_matches_expected=X.items.length===W.stats.expected_total_items;let G=d_(_.current),R=I.legacy_backup_written&&I.no_conflicts&&I.final_count_matches_expected;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:J,legacy_before:U,current_before:D,backup_after:S,current_after:G,merge:W.stats,conflicts:[],checks:I,warnings:j,message:R?`Merged ${W.stats.merged_items} legacy item(s) into ${_.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${_.current.jsonStorePath}`}})}function wZ(_){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,_)}function Q3(_){return _ instanceof Error&&/\b(EBUSY|EPERM)\b/.test(_.message)}function uZ(_){let $;for(let g=0;g<8;g+=1)try{sj(_,{recursive:!0,force:!1});return}catch(U){if($=U,!Q3(U))throw U;wZ(50*(g+1))}throw $}function bG(_){if(!V$(_))return;let $=MG(_);if(z3(_,$.isDirectory()?448:384),!$.isDirectory())return;for(let g of Y3(_))bG(L6(_,g))}function xZ(_){return _==="TOMBSTONE.md"||_==="migration.json"||_==="knowledge.db"||_==="knowledge.db-shm"||_==="knowledge.db-wal"||_==="knowledge.db-journal"}function yZ(_){for(let $ of Y3(_)){if($==="TOMBSTONE.md"||$==="migration.json")continue;try{sj(L6(_,$),{recursive:!0,force:!1})}catch(g){if(!Q3(g)||!$.startsWith("knowledge.db"))throw g}}}function hZ(_,$){try{HZ(_,$);return}catch(g){G3(_,$,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{uZ(_)}catch(U){if(Q3(U)){yZ(_);return}throw sj($,{recursive:!0,force:!0}),U}if(g instanceof Error&&g.message.includes("EXDEV"))return}}function cZ(_,$,g){if(!$.exists)return!1;if(!$.files.includes("TOMBSTONE.md")||!$.files.includes("migration.json"))return!1;if($.files.some((U)=>!xZ(U)))return!1;try{let U=JSON.parse(EU(L6(_.home,"migration.json"),"utf8"));return U.new_path===g&&typeof U.backup_path==="string"}catch{return!1}}function HG(_){let $=_.now??new Date,g=_.approveWrite!==!0,U=d_(_.current),D=vZ(_.current,U),I=_.approveWrite===!0&&Boolean(_.approvedBy)&&(!U.exists||D),j=d_(_.legacy,{includeSqlite:!I}),N={legacy_exists:j.exists,current_absent_or_default_scaffold:!U.exists||D,approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},O=[];if(!j.exists)return{ok:!0,dry_run:g,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:null,legacy_before:j,current_before:U,backup_after:null,current_after:null,checks:N,warnings:O,message:`No legacy knowledge workspace found at ${_.legacy.home}`};if(N.legacy_is_tombstone=cZ(_.legacy,j,_.current.home),N.legacy_is_tombstone)return{ok:!0,dry_run:g,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:L6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:U,backup_after:null,current_after:U,checks:{...N,tombstone_written:!0},warnings:O,message:`Legacy knowledge workspace already migrated to ${_.current.home}`};if(!N.current_absent_or_default_scaffold)O.push("current_workspace_contains_data");if(!N.approval_present)O.push("write_approval_required");if(g||!N.current_absent_or_default_scaffold||!N.approval_present)return{ok:N.current_absent_or_default_scaffold,dry_run:!0,approval_required:!0,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.backup-${aj($)}`,tombstone_path:L6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:U,backup_after:null,current_after:null,checks:N,warnings:O,message:N.current_absent_or_default_scaffold?`Dry run: would migrate ${_.legacy.home} to ${_.current.home}`:`Cannot migrate while ${_.current.home} contains data`};let A=`${_.legacy.home}.backup-${aj($)}`;ej(S3(_.current.home),{recursive:!0}),ej(S3(A),{recursive:!0}),G3(_.legacy.home,A,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),bG(A);let L=D$(A),z=d_(L,{includeSqlite:!1});if(N.backup_matches_legacy=X3(j,z),!N.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${A}`);if(U.exists&&D)sj(_.current.home,{recursive:!0,force:!0});hZ(_.legacy.home,_.current.home);let W=d_(_.current,{includeSqlite:!1});N.migrated_matches_backup=X3(z,W);let J=d_(L),P=d_(_.current),S={...J,path:_.legacy.home};ej(_.legacy.home,{recursive:!0});let X=L6(_.legacy.home,"TOMBSTONE.md");BG(X,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${$.toISOString()}`,`Approved by: ${_.approvedBy}`,`New path: ${_.current.home}`,`Backup path: ${A}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` +`),{mode:384}),z3(X,384);let G=L6(_.legacy.home,"migration.json");BG(G,`${JSON.stringify({migrated_at:$.toISOString(),approved_by:_.approvedBy,new_path:_.current.home,backup_path:A,legacy_before:S,backup_after:J,current_after:P},null,2)} +`,{mode:384}),z3(G,384),N.tombstone_written=V$(X);let R=N.backup_matches_legacy&&N.migrated_matches_backup&&N.tombstone_written;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:A,tombstone_path:X,legacy_before:S,current_before:U,backup_after:J,current_after:P,checks:N,warnings:O,message:R?`Migrated legacy knowledge workspace to ${_.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${_.current.home}`}}function iZ(_){let $=iG(_);if(W_(kG($,"knowledge.db"))||W_(kG($,"config.json")))return D0($);return D0(D$(VN($)).home)}function T3(_){return`${mZ()}:${AU("sha256").update(_.home).digest("hex").slice(0,12)}`}function K3(_){return`'${_.replace(/'/g,"'\\''")}'`}function lZ(_){return["knowledge",..._].map(K3).join(" ")}function CG(_,$){return`cd ${K3(_)} && knowledge ${$.map(K3).join(" ")}`}function lG(_){return!_||_==="local"||_==="localhost"}function OU(_,$){return{source:_.source,adapter:_.adapter,project_root:$,project_root_source:_.project_root_source,workspace_root:_.workspace_root,workspace_root_source:_.workspace_root_source,open_files_root:_.open_files_root,open_files_root_source:_.open_files_root_source,trust_status:_.trust_status,auth_status:_.auth_status,current:_.current,primary:_.primary,diagnostics:_.diagnostics,repair_hints:_.repair_hints,evidence:_.evidence,cacheability:_.cacheability,warnings:_.warnings}}function q3(_){return{source:_.source,adapter:_.adapter,target:_.target,route:_.route,target_kind:_.targetKind,confidence:_.confidence,evidence:_.evidence,cacheability:_.cacheability}}function tZ(_){try{let $=JSON.parse(_);return Array.isArray($)?$.filter((g)=>typeof g==="string"):[]}catch{return[]}}function LU(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function k_(_){return typeof _==="string"&&_.length>0?_:null}function oZ(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function _N(_){return typeof _==="boolean"?_:null}function pZ(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function tG(_,$,g){let U=LU(_),D=k_(U.observed_at)??k_($[`${g}_observed_at`]),I=k_(U.source_authority)??k_($[`${g}_source_authority`]);if(!D||!I)return null;return{observed_at:D,verified_at:k_(U.verified_at),expires_at:k_(U.expires_at)??k_($[`${g}_expires_at`]),ttl_ms:oZ(U.ttl_ms),source_authority:I,confidence:k_(U.confidence)??(g==="route"?k_($.route_confidence):null),cacheable:_N(U.cacheable)??_N($[`${g}_cacheable`])??!1,stale:_N(U.stale)??_N($[`${g}_stale`])??!1,reasons:pZ(U.reasons)}}function eZ(_,$){return _.machine_id===$||_.hostname===$||_.ssh_target===$||_.tailscale_dns===$||tZ(_.tailscale_ips_json).includes($)}function rG(_,$){return vE(_).find((g)=>eZ(g,$))??null}function oG(_){return LU(c4(_.metadata_json).resolver_evidence)}function JU(_){return LU(c4(_.capabilities_json).resolver)}function pG(_){let $=JU(_),g=k_($.route_kind);if(g==="local"||g==="lan"||g==="tailscale"||g==="ssh"||g==="unknown")return g;if(_.tailscale_dns&&_.ssh_target===_.tailscale_dns)return"tailscale";return _.ssh_target?"ssh":"unknown"}function aZ(_){let $=JU(_),g=k_($.route_target_kind);if(g==="local"||g==="lan"||g==="tailscale"||g==="ssh"||g==="unknown")return g;return pG(_)}function sZ(_){return k_(JU(_).route_confidence)??"medium"}function vG(_,$,g){let U=oG(_),D=LU(U.route),I=JU(_);return{target:_.ssh_target??_.tailscale_dns??_.hostname??_.machine_id,route:pG(_),targetKind:aZ(_),confidence:sZ(_),source:"registry",adapter:g.adapter,evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,route:D},cacheability:tG(D.cacheability,I,"route")??g.cacheability,warnings:[...new Set([...g.warnings,"registry_route_fallback"])]}}function fG(_,$,g){if(!_.workspace_home)return null;let U=oG(_),D=LU(U.workspace),I=JU(_);return{ok:!0,source:"registry",adapter:g.adapter,requested_machine_id:$,machine_id:_.machine_id,project_id:k_(D.project_id)??g.project_id,repo_name:k_(D.repo_name)??g.repo_name,project_root:_.workspace_home,project_root_source:k_(I.project_root_source)??"registry",workspace_root:k_(D.workspace_root),workspace_root_source:k_(I.workspace_root_source)??"registry",open_files_root:k_(D.open_files_root),open_files_root_source:k_(I.open_files_root_source)??"registry",trust_status:k_(I.trust_status)??"unknown",auth_status:k_(I.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,workspace:D},cacheability:tG(D.cacheability,I,"workspace")??g.cacheability,warnings:[...new Set([...g.warnings,"registry_workspace_fallback"])]}}function wG(_){if(!_)return null;let $=_.diagnostics.filter((U)=>U.severity!=="ok"),g=_.repair_hints[0];if(!$.length&&!_.warnings.length&&!g)return null;return[$.length?`workspace diagnostics: ${$.map((U)=>`${U.id}=${U.status}`).join(", ")}`:null,_.warnings.length?`warnings: ${_.warnings.join(", ")}`:null,g?`repair: ${g.shell_command}`:null].filter(Boolean).join("; ")}function $N(_){return{id:_.id,reason:_.reason,command:["knowledge",..._.args],shell_command:lZ(_.args)}}function gN(_,$){let g=v(_);try{return Number(g.query($).get()?.count??0)}finally{g.close()}}function _b(_,$){let g=gN(_,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),U=gN(_,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),D=gN(_,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),I=gN(_,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),j=I===0;return{ok:j,source_of_truth:"open-files",configured_root:$?.open_files_root??null,configured_root_source:$?.open_files_root_source??null,source_refs:{open_files:g,metadata_mentions:U},extracted_text_artifacts:D,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:I,message:j?`${g} open-files source ref(s); raw source bytes remain owned by open-files`:`${I} raw source payload metadata sentinel(s) found`}}var $b=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function V3(_,$=0){if($>8)return!1;if(!_||typeof _!=="object")return!1;if(Array.isArray(_))return _.some((g)=>V3(g,$+1));for(let[g,U]of Object.entries(_)){if($b.has(g.toLowerCase()))return!0;if(V3(U,$+1))return!0}return!1}function c4(_){try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function uG(_,$=20,g=200){if(!Number.isFinite(_)||_<=0)return $;return Math.min(Math.floor(_),g)}function gb(_,$=220){let g=_??"";return g.length>$?`${g.slice(0,$)}...`:g}function S$(_,$=["metadata_json"]){return _.map((g)=>{let U={...g};for(let D of $){let I=U[D];if(typeof I==="string"){let j=D.endsWith("_json")?D.slice(0,-5):D;U[j]=c4(I),delete U[D]}}return U})}function DN(_){if(typeof _!=="string")return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function F3(_){if(typeof _!=="string")return{};return c4(_)}function Db(_){let $={..._};return $.source_refs=DN($.source_refs_json),$.evidence_refs=DN($.evidence_refs_json),$.requires_approval=$.requires_approval===1||$.requires_approval===!0,$.checks=F3($.checks_json),$.metadata=F3($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.checks_json,delete $.metadata_json,$}function Ub(_){let $={..._};return $.source_refs=DN($.source_refs_json),$.evidence_refs=DN($.evidence_refs_json),$.metadata=F3($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.metadata_json,$}function p_(_,$,g=[]){return _.query($).all(...g)}function Ib(_){if(!W_(_))return{exists:!1,read_error:null,items:[]};try{let $=JSON.parse(dZ(_,"utf8"));if(!$||!Array.isArray($.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:$.items}}catch($){return{exists:!0,read_error:$ instanceof Error?$.message:String($),items:[]}}}function xG(_){return{id:_.id,short_id:_.short_id??null,title:_.title,content_preview:gb(_.content),url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:_.archived===!0,created_at:_.created_at,updated_at:_.updated_at}}function yG(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0,promotion_candidates:0,durable_records:0}}function eG(_,$,g=!1){return{query:_,limit:$,offset:0,mode:{keyword:!0,catalog:!0,semantic:g},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function jb(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function Nb(_,$,g=!1){let U=eG(_,$,g);return{query:_,normalized_query:jb(_),created_at:new Date().toISOString(),mode:U.mode,warnings:U.warnings,search_counts:U.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function B3(_,$,g){let U=g??$.jsonStorePath;if(W_(U))return U;if(_==="global"){let D=Vg();if(W_(D))return D}return U}function Eb(_){let $=JSON.stringify(_);return Math.max(1,Math.ceil($.length/4))}function M3(_,$){let g=(_??"").normalize("NFKC").trim().replace(/\s+/g," ");if(g.length<=$)return g;return`${g.slice(0,Math.max(0,$-1)).trim()}...`}function hG(_,$,g){let U=u_(M3(_,g),$);return{text:U.text,redactions:U.findings.length}}function cG(_,$,g){let U=_.now??new Date,D=_.source??"search",I=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),j=(_.query??_.topic??$.query).normalize("NFKC").trim().replace(/\s+/g," "),N=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),O=Math.max(500,Math.min(_.maxTokens??6000,1e5)),A=0,L=$.citations.slice(0,Math.max(N*2,N)).map((R,K)=>{let Q=hG(R.quote,g,K<3?220:140);A+=Q.redactions;let T=R.source_ref??R.source_uri??R.artifact_path??R.artifact_uri??R.id;return{id:`cite_${AU("sha256").update(`${R.id}\x00${T}`).digest("hex").slice(0,12)}`,kind:R.artifact_uri||R.artifact_path?"artifact":"source",ref:T,source_ref:R.source_ref,source_uri:R.source_uri,artifact_uri:R.artifact_uri,artifact_path:R.artifact_path,run_id:null,run_event_id:null,revision:R.revision,hash:R.hash,chunk_id:R.chunk_id,offsets:{start:R.start_offset,end:R.end_offset},quote_preview:Q.text}}),z=new Map($.citations.map((R,K)=>[R.id,L[K]])),W=$.excerpts.slice(0,Math.max(N*2,N)).map((R)=>{let K=$.results.find((q)=>q.id===R.result_id),Q=R.citation_id?z.get(R.citation_id):void 0,T=hG(R.text,g,520);return A+=T.redactions,{id:`ev_${AU("sha256").update(`${R.kind}\x00${R.result_id}\x00${R.citation_id??""}`).digest("hex").slice(0,14)}`,kind:R.kind,title:M3(K?.title??Q?.ref??R.kind,100),text_preview:T.text,score:Number(R.score.toFixed(6)),citation_ids:Q?[Q.id]:[],provenance:{source:D,record_ref:`${R.kind}:${R.result_id}`,created_at:$.created_at,updated_at:null,metadata_keys:[]}}}).sort((R,K)=>K.score-R.score||R.id.localeCompare(K.id)).slice(0,N),J=new Set(W.flatMap((R)=>R.citation_ids)),P=L.filter((R)=>J.has(R.id)),S=Array.from(new Set($.warnings)),X=`ctx_${AU("sha256").update([D,I,j,S.join(","),W.map((R)=>R.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,G={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:U.toISOString(),source:D,purpose:I,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:X,budgets:{max_tokens:O,estimated_tokens:0,max_items:N,items_included:W.length,items_available:$.excerpts.length,items_truncated:Math.max(0,$.excerpts.length-W.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:A,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:P,evidence:W,duplicate_candidates:[],outline:{title:j?`Knowledge context: ${M3(j,80)}`:"Knowledge context",bullets:W.length>0?W.slice(0,5).map((R)=>`${R.id}: ${R.title}`):["No matching bounded evidence was found."],evidence_ids:W.slice(0,8).map((R)=>R.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:S,message:`${W.length} bounded evidence item(s), estimated under ${O} token(s)`};return G.budgets.estimated_tokens=Eb(G),G.budgets.token_budget_exceeded=G.budgets.estimated_tokens>O,G.message=`${G.evidence.length} bounded evidence item(s), estimated ${G.budgets.estimated_tokens}/${O} token(s)`,G}function Ob(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function Ab(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function Lb(_){return{ok:!0,scope:_.scope,workspace_home:_.workspaceHome,sqlite_schema_version:0,local_machine_id:_.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function nG(_){let $=_.now??new Date,g=_.source??"search",U=_.purpose??(g==="loops"||g==="runs"?"proposal":"agent_context"),D=(_.query??_.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),I=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),j=Math.max(500,Math.min(_.maxTokens??6000,1e5)),N=`ctx_${AU("sha256").update(["empty",g,U,D,_.topic??"",_.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:g,purpose:U,query:D,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:N,budgets:{max_tokens:j,estimated_tokens:0,max_items:I,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:D?`Context for ${D}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${j} token(s)`}}function Z3(_){let $=_.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return $?`${$}/`:null}function Jb(_,$){let g=v(_);try{let U=g.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all(),W=new Map,X=0,G=0,Y=0,Q=0,q=0,L=0,N=0,R=0,B=0,H=0,V=0,K=0,E=new Map,F=[],w=[],A=[],g=[],v=_.artifact_store.uri_prefix,k=aL(_);for(let U_ of U){if(W.set(U_.kind,(W.get(U_.kind)??0)+1),U_.hash?.startsWith("sha256:"))X+=1;if(typeof U_.size_bytes==="number"&&U_.size_bytes>=0)G+=1,Y+=U_.size_bytes;if(U_.artifact_uri.startsWith(v))Q+=1;else if(F.length<5)F.push(U_.artifact_uri);let F_=j2(U_.metadata_json);if(pL(F_))N+=1;let A2=typeof F_.key==="string"?F_.key:null;if(!A2)q+=1;else if(k&&A2.startsWith(k)){if(L+=1,w.length<5)w.push(A2)}let bB=typeof F_.artifact_modified_at==="string"?F_.artifact_modified_at:null;if(bB)if(Number.isNaN(Date.parse(bB))){if(B+=1,A.length<5)A.push(U_.artifact_uri)}else R+=1;let xW=F_.provenance&&typeof F_.provenance==="object"&&!Array.isArray(F_.provenance)?F_.provenance:null;if(xW){H+=1;let LY=typeof xW.artifact_key==="string"?xW.artifact_key:null,wB=typeof xW.generated_from==="string"?xW.generated_from:"unknown";if(E.set(wB,(E.get(wB)??0)+1),LY){if(V+=1,A2&&LY!==A2){if(K+=1,g.length<5)g.push(`${U_.artifact_uri}:provenance.artifact_key=${LY}:key=${A2}`)}}else if(g.length<5)g.push(`${U_.artifact_uri}:missing_provenance_artifact_key`)}else if(g.length<5)g.push(`${U_.artifact_uri}:missing_provenance`)}let u=U.length-X,W_=U.length-G,c$=U.length-R-B,z_=U.length-H,K_=H-V,E$=U.length-Q,A_=[u>0?`artifact_manifest_missing_hash:${u}`:null,W_>0?`artifact_manifest_missing_size:${W_}`:null,q>0?`artifact_manifest_missing_key:${q}`:null,E$>0?`artifact_manifest_uri_prefix_mismatch:${E$}`:null,L>0?`artifact_manifest_s3_key_contains_storage_prefix:${L}`:null,B>0?`artifact_manifest_invalid_modified_at:${B}`:null,z_>0?`artifact_manifest_missing_provenance:${z_}`:null,K_>0?`artifact_manifest_missing_provenance_artifact_key:${K_}`:null,K>0?`artifact_manifest_provenance_key_mismatch:${K}`:null,N>0?`artifact_manifest_raw_payload_sentinels:${N}`:null].filter((U_)=>Boolean(U_)),D_=A_.length===0;return{ok:D_,read_only:!0,storage_type:_.storage_type,artifact_uri_prefix:v,s3:_.artifact_store.s3,artifacts:{total:U.length,by_kind:[...W.entries()].map(([U_,F_])=>({kind:U_,count:F_})).sort((U_,F_)=>U_.kind.localeCompare(F_.kind)),with_hash:X,missing_hash:u,with_size:G,missing_size:W_,total_size_bytes:Y},modified_time:{with_modified_at:R,missing_modified_at:c$,invalid_modified_at:B,examples:A},provenance:{with_provenance:H,missing_provenance:z_,with_artifact_key:V,missing_artifact_key:K_,artifact_key_mismatches:K,generated_from:[...E.entries()].map(([U_,F_])=>({value:U_,count:F_})).sort((U_,F_)=>U_.value.localeCompare(F_.value)),examples:g},uri_prefix:{matching:Q,mismatched:E$,examples:F},keys:{with_key:U.length-q,missing_key:q,prefixed_with_storage_prefix:L,prefixed_examples:w},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:L===0&&q===0,tracks_modified_time:R>0&&B===0,preserves_provenance:z_===0&&K_===0&&K===0},raw_payload_sentinel_hits:N,warnings:A_,message:D_?`${U.length} generated artifact manifest row(s) ready for ${_.storage_type} sync`:`Generated artifact manifest needs attention: ${A_.join(", ")}`}}finally{J.close()}}function Mc($,_){let J=aL(_);if(!J)return[];let U=m($);try{let W=U.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json + ORDER BY artifact_uri ASC`).all(),D=new Map,I=0,j=0,N=0,O=0,A=0,L=0,z=0,W=0,J=0,P=0,S=0,X=0,G=new Map,R=[],K=[],Q=[],T=[],q=$.artifact_store.uri_prefix,V=Z3($);for(let G_ of U){if(D.set(G_.kind,(D.get(G_.kind)??0)+1),G_.hash?.startsWith("sha256:"))I+=1;if(typeof G_.size_bytes==="number"&&G_.size_bytes>=0)j+=1,N+=G_.size_bytes;if(G_.artifact_uri.startsWith(q))O+=1;else if(R.length<5)R.push(G_.artifact_uri);let H_=c4(G_.metadata_json);if(V3(H_))z+=1;let g0=typeof H_.key==="string"?H_.key:null;if(!g0)A+=1;else if(V&&g0.startsWith(V)){if(L+=1,K.length<5)K.push(g0)}let Az=typeof H_.artifact_modified_at==="string"?H_.artifact_modified_at:null;if(Az)if(Number.isNaN(Date.parse(Az))){if(J+=1,Q.length<5)Q.push(G_.artifact_uri)}else W+=1;let Kg=H_.provenance&&typeof H_.provenance==="object"&&!Array.isArray(H_.provenance)?H_.provenance:null;if(Kg){P+=1;let TN=typeof Kg.artifact_key==="string"?Kg.artifact_key:null,Lz=typeof Kg.generated_from==="string"?Kg.generated_from:"unknown";if(G.set(Lz,(G.get(Lz)??0)+1),TN){if(S+=1,g0&&TN!==g0){if(X+=1,T.length<5)T.push(`${G_.artifact_uri}:provenance.artifact_key=${TN}:key=${g0}`)}}else if(T.length<5)T.push(`${G_.artifact_uri}:missing_provenance_artifact_key`)}else if(T.length<5)T.push(`${G_.artifact_uri}:missing_provenance`)}let Z=U.length-I,a=U.length-j,D_=U.length-W-J,I_=U.length-P,J_=P-S,p=U.length-O,r_=[Z>0?`artifact_manifest_missing_hash:${Z}`:null,a>0?`artifact_manifest_missing_size:${a}`:null,A>0?`artifact_manifest_missing_key:${A}`:null,p>0?`artifact_manifest_uri_prefix_mismatch:${p}`:null,L>0?`artifact_manifest_s3_key_contains_storage_prefix:${L}`:null,J>0?`artifact_manifest_invalid_modified_at:${J}`:null,I_>0?`artifact_manifest_missing_provenance:${I_}`:null,J_>0?`artifact_manifest_missing_provenance_artifact_key:${J_}`:null,X>0?`artifact_manifest_provenance_key_mismatch:${X}`:null,z>0?`artifact_manifest_raw_payload_sentinels:${z}`:null].filter((G_)=>Boolean(G_)),K_=r_.length===0;return{ok:K_,read_only:!0,storage_type:$.storage_type,artifact_uri_prefix:q,s3:$.artifact_store.s3,artifacts:{total:U.length,by_kind:[...D.entries()].map(([G_,H_])=>({kind:G_,count:H_})).sort((G_,H_)=>G_.kind.localeCompare(H_.kind)),with_hash:I,missing_hash:Z,with_size:j,missing_size:a,total_size_bytes:N},modified_time:{with_modified_at:W,missing_modified_at:D_,invalid_modified_at:J,examples:Q},provenance:{with_provenance:P,missing_provenance:I_,with_artifact_key:S,missing_artifact_key:J_,artifact_key_mismatches:X,generated_from:[...G.entries()].map(([G_,H_])=>({value:G_,count:H_})).sort((G_,H_)=>G_.value.localeCompare(H_.value)),examples:T},uri_prefix:{matching:O,mismatched:p,examples:R},keys:{with_key:U.length-A,missing_key:A,prefixed_with_storage_prefix:L,prefixed_examples:K},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:L===0&&A===0,tracks_modified_time:W>0&&J===0,preserves_provenance:I_===0&&J_===0&&X===0},raw_payload_sentinel_hits:z,warnings:r_,message:K_?`${U.length} generated artifact manifest row(s) ready for ${$.storage_type} sync`:`Generated artifact manifest needs attention: ${r_.join(", ")}`}}finally{g.close()}}function Pb(_,$){let g=Z3($);if(!g)return[];let U=v(_);try{let D=U.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all(),X=[];for(let G of W){let Y=j2(G.metadata_json),Q=typeof Y.key==="string"?Y.key:null;if(!Q?.startsWith(J))continue;let q=Q.slice(J.length);if(!q)continue;X.push({id:G.id,artifact_uri:G.artifact_uri,kind:G.kind,current_key:Q,repaired_key:z4(q),hash:G.hash,size_bytes:G.size_bytes})}return X}finally{U.close()}}function Ac($){let _=["--scope",$.scope,"--json"],J=$.tables?.length?["--tables",$.tables.join(",")]:[],U=[aG({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",..._]})];if($.machine&&!vE($.machine))U.push(aG({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",$.machine,...$.peerWorkspace?["--peer-workspace",$.peerWorkspace]:[],...J,..._]}));else if($.peerWorkspace)U.push(aG({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",$.peerWorkspace,...J,..._]}));for(let W of $.resolvedWorkspace?.repair_hints??[])U.push({id:W.id,reason:W.reason,command:W.command,shell_command:W.shell_command});if($.openConflicts>0)U.push(aG({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",..._]}));return U}function bc(){let $=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",_=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!_)return{command:$,argsPrefix:[]};let J;try{J=JSON.parse(_)}catch(U){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${U instanceof Error?U.message:String(U)}`)}if(!Array.isArray(J)||!J.every((U)=>typeof U==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:$,argsPrefix:J}}function TE($,_,J,U){let W=bc(),X=en(W.command,[...W.argsPrefix,U.target,_],{encoding:"utf8",env:process.env,input:J,maxBuffer:67108864});if((X.status??1)!==0){let G=U.source==="open-machines"?` via ${U.route??"resolved"}:${U.target}`:"";throw Error(`ssh ${$}${G} failed: ${(X.stderr||X.stdout||String(X.status)).trim()}`)}return X.stdout||""}function SE($,_,J){try{return JSON.parse(J)}catch(U){let W=J.trim().slice(0,240);throw Error(`Remote knowledge ${_} on ${$} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${W||String(U)}`)}}function wc($,_){if(typeof _!=="object"||_===null||!("format"in _)||_.format!=="knowledge-sync-bundle")throw Error(`Remote knowledge sync export on ${$} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:J,min_protocol_version:U}=_;if(typeof J!=="number"||typeof U!=="number"||Jw0)throw Error(`Remote knowledge sync export on ${$} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function gc($,_){if(typeof _!=="object"||_===null||!("ok"in _)||!("target"in _)||!("tables"in _)||!("artifacts"in _)||!("conflicts_created"in _))throw Error(`Remote knowledge sync import on ${$} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:J,min_protocol_version:U}=_;if(typeof J!=="number"||typeof U!=="number"||Jw0)throw Error(`Remote knowledge sync import on ${$} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function kc($){if(!$)return;let _=$.trim().toLowerCase();if(_==="local"||_==="offline")return"local";if(_==="hosted"||_==="remote"||_==="knowledge.md")return"hosted";throw Error("Invalid setup mode. Use hosted or local.")}class uE{options;ensuredWorkspace;cachedConfig;constructor($={}){this.options=$}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??O9(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=b2(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let $=this.ensureWorkspace();return y9({storePath:$.jsonStorePath,storePathOverridden:!1})}async listItems(){return this.itemStore().listAll()}async getItem($){return this.itemStore().get($)}async createItem($){return this.itemStore().create($)}async updateItem($,_){return this.itemStore().update($,_)}async deleteItem($){return this.itemStore().delete($)}async deleteItems($){return this.itemStore().deleteMany($)}async resolveInventory($={}){if(this.isApiMode())return this.cloudInventory($);return this.inventory($)}config($={}){let _=$.ensure?this.ensureWorkspace():this.workspace;if(!this.cachedConfig||$.ensure||e$(_.configPath))this.cachedConfig=e$(_.configPath)?KY(_.configPath):dW();return this.cachedConfig}safetyPolicy(){return b3(this.config(),this.workspace)}artifactStore(){return AQ(this.config(),this.ensureWorkspace())}storageContract(){return x9(this.config(),this.workspace,this.scope)}validateStorage(){return gQ(this.config(),this.workspace)}assertStorageValid($){let _=this.validateStorage();if(!_.ok)throw Error(`Storage contract invalid before ${$}: ${_.errors.join("; ")}`)}migrateLegacyPath($={}){let _=this.workspace,J=RY(this.options.scope,this.options.cwd),U=KE({scope:this.scope,current:_,legacy:J,approveWrite:$.approveWrite,approvedBy:$.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}mergeLegacyPath($={}){let _=this.workspace,J=RY(this.options.scope,this.options.cwd),U=VE({scope:this.scope,current:_,legacy:J,approveWrite:$.approveWrite,approvedBy:$.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}setup($={}){let _=this.ensureWorkspace(),J=this.config({ensure:!0}),U=kc($.mode)??J.mode,W=$.apiUrl?x4($.apiUrl):J.hosted?.api_url?x4(J.hosted.api_url):null,X={...J,mode:U,hosted:{...J.hosted??{},...W?{api_url:W}:{}},storage:$.canonicalExample?CB():J.storage};PB(_.configPath,X),this.cachedConfig=X;let G=x9(X,_,this.scope);return{ok:!0,mode:U,api_url:X.hosted?.api_url??null,storage_type:X.storage.type,artifact_uri_prefix:G.artifact_store.uri_prefix,canonical_example:G.canonical_example,config_path:_.configPath,next:U==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${U}`}}authStatus($=process.env){return O3(this.config(),$)}saveAuth($,_=process.env){let J=$.apiUrl??this.config().hosted?.api_url;return j3({api_key:$.apiKey,email:$.email,org_id:$.orgId,org_slug:$.orgSlug,user_id:$.userId,api_url:J},_)}clearAuth($=process.env){return D3($)}paths(){let $=this.workspace;return{ok:!0,scope:this.scope,home:$.home,exists:e$($.home),config_path:$.configPath,config_exists:e$($.configPath),json_store_path:$.jsonStorePath,json_store_exists:e$($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:e$($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,runs_dir:$.runsDir,schemas_dir:$.schemasDir,wiki_dir:$.wikiDir,config:this.config(),message:$.home}}initDb(){return a(this.ensureWorkspace().knowledgeDbPath)}dbStats(){h9("reading knowledge.db stats");let $=this.workspace;if(!e$($.knowledgeDbPath))return IE();return FQ($.knowledgeDbPath)}enqueuePromotion($){return IF(this.ensureWorkspace().knowledgeDbPath,$)}promotionInbox($={}){return CF(this.ensureWorkspace().knowledgeDbPath,$)}getPromotion($){return fF(this.ensureWorkspace().knowledgeDbPath,$)}reviewPromotion($,_){return PF(this.ensureWorkspace().knowledgeDbPath,$,_)}promoteCandidate($,_={}){return TF(this.ensureWorkspace().knowledgeDbPath,$,_)}rejectPromotion($,_={}){return SF(this.ensureWorkspace().knowledgeDbPath,$,_)}durableRecords($={}){return ZF(this.ensureWorkspace().knowledgeDbPath,$)}itemOnlyInventory($){let _=this.workspace,{items:J,limit:U,includeArchived:W,storePath:X,storeExists:G,storeReadError:Y}=$,Q=J.filter((R)=>R.archived!==!0),q=W?J:Q,L=IE(),N={legacy_items:J.length,active_items:Q.length,archived_items:J.length-Q.length,schema_version:L.schema_version,sources:L.sources,source_revisions:L.source_revisions,chunks:L.chunks,wiki_pages:L.wiki_pages,citations:L.citations,indexes:L.indexes,runs:L.runs,run_events:L.run_events,storage_objects:L.storage_objects,embeddings:L.embeddings,vector_entries:L.vector_entries,reindex_queue:L.reindex_queue,redaction_findings:L.redaction_findings,audit_events:L.audit_events,approval_gates:L.approval_gates,knowledge_machines:L.knowledge_machines,sync_snapshots:L.sync_snapshots,sync_changes:L.sync_changes,sync_conflicts:L.sync_conflicts,sync_table_clocks:L.sync_table_clocks,sync_imports:L.sync_imports,promotion_candidates:L.promotion_candidates,durable_records:L.durable_records};return{ok:!0,scope:this.scope,home:_.home,limit:U,paths:{json_store_path:_.jsonStorePath,json_store_exists:e$(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:e$(_.knowledgeDbPath),artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,wiki_dir:_.wikiDir},summary:N,legacy_store:{path:X,exists:G,read_error:Y,total_items:J.length,active_items:Q.length,archived_items:J.length-Q.length,items_returned:Math.min(q.length,U)},items:q.slice(0,U).map(kE),sources:[],source_revisions:[],chunks:[],wiki_pages:[],indexes:[],storage_objects:[],runs:[],vector_indexes:[],reindex_queue:[],machines:[],sync_conflicts:[],approval_gates:[],audit_events:[],promotion_candidates:[],durable_records:[],message:`${J.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory($={}){let _=gE($.limit),J=await this.fetchCloudItems(),U=KU();return this.itemOnlyInventory({items:J,limit:_,includeArchived:$.includeArchived??!1,storePath:U?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory($={}){let _=this.workspace,J=gE($.limit),U=$.storePath??_.jsonStorePath,W=Bc(U),X=W.items.filter((L)=>L.archived!==!0),G=$.includeArchived?W.items:X;if(!e$(_.knowledgeDbPath))return this.itemOnlyInventory({items:W.items,limit:J,includeArchived:$.includeArchived??!1,storePath:U,storeExists:W.exists,storeReadError:W.read_error});a(_.knowledgeDbPath);let Q=FQ(_.knowledgeDbPath),q=m(_.knowledgeDbPath);try{let L=K6(l_(q,` + ORDER BY artifact_uri ASC`).all(),I=[];for(let j of D){let N=c4(j.metadata_json),O=typeof N.key==="string"?N.key:null;if(!O?.startsWith(g))continue;let A=O.slice(g.length);if(!A)continue;I.push({id:j.id,artifact_uri:j.artifact_uri,kind:j.kind,current_key:O,repaired_key:f$(A),hash:j.hash,size_bytes:j.size_bytes})}return I}finally{U.close()}}function zb(_){let $=["--scope",_.scope,"--json"],g=_.tables?.length?["--tables",_.tables.join(",")]:[],U=[$N({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",...$]})];if(_.machine&&!lG(_.machine))U.push($N({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",_.machine,..._.peerWorkspace?["--peer-workspace",_.peerWorkspace]:[],...g,...$]}));else if(_.peerWorkspace)U.push($N({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",_.peerWorkspace,...g,...$]}));for(let D of _.resolvedWorkspace?.repair_hints??[])U.push({id:D.id,reason:D.reason,command:D.command,shell_command:D.shell_command});if(_.openConflicts>0)U.push($N({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",...$]}));return U}function Sb(){let _=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",$=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!$)return{command:_,argsPrefix:[]};let g;try{g=JSON.parse($)}catch(U){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${U instanceof Error?U.message:String(U)}`)}if(!Array.isArray(g)||!g.every((U)=>typeof U==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:_,argsPrefix:g}}function dG(_,$,g,U){let D=Sb(),I=nZ(D.command,[...D.argsPrefix,U.target,$],{encoding:"utf8",env:process.env,input:g,maxBuffer:67108864});if((I.status??1)!==0){let j=U.source==="open-machines"?` via ${U.route??"resolved"}:${U.target}`:"";throw Error(`ssh ${_}${j} failed: ${(I.stderr||I.stdout||String(I.status)).trim()}`)}return I.stdout||""}function mG(_,$,g){try{return JSON.parse(g)}catch(U){let D=g.trim().slice(0,240);throw Error(`Remote knowledge ${$} on ${_} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${D||String(U)}`)}}function Wb(_,$){if(typeof $!=="object"||$===null||!("format"in $)||$.format!=="knowledge-sync-bundle")throw Error(`Remote knowledge sync export on ${_} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:g,min_protocol_version:U}=$;if(typeof g!=="number"||typeof U!=="number"||gV6)throw Error(`Remote knowledge sync export on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Xb(_,$){if(typeof $!=="object"||$===null||!("ok"in $)||!("target"in $)||!("tables"in $)||!("artifacts"in $)||!("conflicts_created"in $))throw Error(`Remote knowledge sync import on ${_} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:g,min_protocol_version:U}=$;if(typeof g!=="number"||typeof U!=="number"||gV6)throw Error(`Remote knowledge sync import on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Rb(_){if(!_)return;let $=_.trim().toLowerCase();if($==="local"||$==="offline")return"local";if($==="hosted"||$==="remote"||$==="knowledge.md")return"hosted";throw Error("Invalid setup mode. Use hosted or local.")}class aG{options;ensuredWorkspace;cachedConfig;constructor(_={}){this.options=_}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??ZU(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=D0(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let _=this.ensureWorkspace();return hU({storePath:_.jsonStorePath,storePathOverridden:!1})}async listItems(){return this.itemStore().listAll()}async getItem(_){return this.itemStore().get(_)}async createItem(_){return this.itemStore().create(_)}async updateItem(_,$){return this.itemStore().update(_,$)}async deleteItem(_){return this.itemStore().delete(_)}async deleteItems(_){return this.itemStore().deleteMany(_)}async resolveInventory(_={}){if(this.isApiMode())return this.cloudInventory(_);return this.inventory(_)}config(_={}){let $=_.ensure?this.ensureWorkspace():this.workspace;if(!this.cachedConfig||_.ensure||W_($.configPath))this.cachedConfig=W_($.configPath)?MN($.configPath):Fg();return this.cachedConfig}safetyPolicy(){return fS(this.config(),this.workspace)}artifactStore(){return gE(this.config(),this.ensureWorkspace())}storageContract(){return dU(this.config(),this.workspace,this.scope)}validateStorage(){return IE(this.config(),this.workspace)}assertStorageValid(_){let $=this.validateStorage();if(!$.ok)throw Error(`Storage contract invalid before ${_}: ${$.errors.join("; ")}`)}migrateLegacyPath(_={}){let $=this.workspace,g=FN(this.options.scope,this.options.cwd),U=HG({scope:this.scope,current:$,legacy:g,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}mergeLegacyPath(_={}){let $=this.workspace,g=FN(this.options.scope,this.options.cwd),U=ZG({scope:this.scope,current:$,legacy:g,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}setup(_={}){let $=this.ensureWorkspace(),g=this.config({ensure:!0}),U=Rb(_.mode)??g.mode,D=_.apiUrl?a$(_.apiUrl):g.hosted?.api_url?a$(g.hosted.api_url):null,I={...g,mode:U,hosted:{...g.hosted??{},...D?{api_url:D}:{}},storage:_.canonicalExample?Wz():g.storage};Xz($.configPath,I),this.cachedConfig=I;let j=dU(I,$,this.scope);return{ok:!0,mode:U,api_url:I.hosted?.api_url??null,storage_type:I.storage.type,artifact_uri_prefix:j.artifact_store.uri_prefix,canonical_example:j.canonical_example,config_path:$.configPath,next:U==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${U}`}}authStatus(_=process.env){return BS(this.config(),_)}saveAuth(_,$=process.env){let g=_.apiUrl??this.config().hosted?.api_url;return TS({api_key:_.apiKey,email:_.email,org_id:_.orgId,org_slug:_.orgSlug,user_id:_.userId,api_url:g},$)}clearAuth(_=process.env){return qS(_)}paths(){let _=this.workspace;return{ok:!0,scope:this.scope,home:_.home,exists:W_(_.home),config_path:_.configPath,config_exists:W_(_.configPath),json_store_path:_.jsonStorePath,json_store_exists:W_(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:W_(_.knowledgeDbPath),artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,runs_dir:_.runsDir,schemas_dir:_.schemasDir,wiki_dir:_.wikiDir,config:this.config(),message:_.home}}initDb(){return h(this.ensureWorkspace().knowledgeDbPath)}dbStats(){cU("reading knowledge.db stats");let _=this.workspace;if(!W_(_.knowledgeDbPath))return yG();return sN(_.knowledgeDbPath)}enqueuePromotion(_){return yR(this.ensureWorkspace().knowledgeDbPath,_)}promotionInbox(_={}){return cR(this.ensureWorkspace().knowledgeDbPath,_)}getPromotion(_){return hR(this.ensureWorkspace().knowledgeDbPath,_)}reviewPromotion(_,$){return nR(this.ensureWorkspace().knowledgeDbPath,_,$)}promoteCandidate(_,$={}){return dR(this.ensureWorkspace().knowledgeDbPath,_,$)}rejectPromotion(_,$={}){return mR(this.ensureWorkspace().knowledgeDbPath,_,$)}durableRecords(_={}){return iR(this.ensureWorkspace().knowledgeDbPath,_)}itemOnlyInventory(_){let $=this.workspace,{items:g,limit:U,includeArchived:D,storePath:I,storeExists:j,storeReadError:N}=_,O=g.filter((W)=>W.archived!==!0),A=D?g:O,L=yG(),z={legacy_items:g.length,active_items:O.length,archived_items:g.length-O.length,schema_version:L.schema_version,sources:L.sources,source_revisions:L.source_revisions,chunks:L.chunks,wiki_pages:L.wiki_pages,citations:L.citations,indexes:L.indexes,runs:L.runs,run_events:L.run_events,storage_objects:L.storage_objects,embeddings:L.embeddings,vector_entries:L.vector_entries,reindex_queue:L.reindex_queue,redaction_findings:L.redaction_findings,audit_events:L.audit_events,approval_gates:L.approval_gates,knowledge_machines:L.knowledge_machines,sync_snapshots:L.sync_snapshots,sync_changes:L.sync_changes,sync_conflicts:L.sync_conflicts,sync_table_clocks:L.sync_table_clocks,sync_imports:L.sync_imports,promotion_candidates:L.promotion_candidates,durable_records:L.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:U,paths:{json_store_path:$.jsonStorePath,json_store_exists:W_($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:W_($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:z,legacy_store:{path:I,exists:j,read_error:N,total_items:g.length,active_items:O.length,archived_items:g.length-O.length,items_returned:Math.min(A.length,U)},items:A.slice(0,U).map(xG),sources:[],source_revisions:[],chunks:[],wiki_pages:[],indexes:[],storage_objects:[],runs:[],vector_indexes:[],reindex_queue:[],machines:[],sync_conflicts:[],approval_gates:[],audit_events:[],promotion_candidates:[],durable_records:[],message:`${g.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory(_={}){let $=uG(_.limit),g=await this.fetchCloudItems(),U=fg();return this.itemOnlyInventory({items:g,limit:$,includeArchived:_.includeArchived??!1,storePath:U?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory(_={}){let $=this.workspace,g=uG(_.limit),U=_.storePath??$.jsonStorePath,D=Ib(U),I=D.items.filter((L)=>L.archived!==!0),j=_.includeArchived?D.items:I;if(!W_($.knowledgeDbPath))return this.itemOnlyInventory({items:D.items,limit:g,includeArchived:_.includeArchived??!1,storePath:U,storeExists:D.exists,storeReadError:D.read_error});h($.knowledgeDbPath);let O=sN($.knowledgeDbPath),A=v($.knowledgeDbPath);try{let L=S$(p_(A,` SELECT s.id, s.uri, @@ -1177,7 +1178,7 @@ Pages should be concise, cited, and organized for both humans and agents. GROUP BY s.id ORDER BY s.updated_at DESC, s.created_at DESC LIMIT ? - `,[J]),["metadata_json","acl_json"]),N=K6(l_(q,` + `,[g]),["metadata_json","acl_json"]),z=S$(p_(A,` SELECT sr.id, s.uri AS source_uri, @@ -1190,7 +1191,7 @@ Pages should be concise, cited, and organized for both humans and agents. JOIN sources s ON s.id = sr.source_id ORDER BY sr.created_at DESC LIMIT ? - `,[J])),R=K6(l_(q,` + `,[g])),W=S$(p_(A,` SELECT c.id, c.kind, @@ -1211,22 +1212,22 @@ Pages should be concise, cited, and organized for both humans and agents. LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id ORDER BY c.created_at DESC, c.ordinal ASC LIMIT ? - `,[J])),B=K6(l_(q,` + `,[g])),J=S$(p_(A,` SELECT id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at FROM wiki_pages ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),H=K6(l_(q,` + `,[g])),P=S$(p_(A,` SELECT id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at FROM knowledge_indexes ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),V=K6(l_(q,` + `,[g])),S=S$(p_(A,` SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at FROM storage_objects ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),K=K6(l_(q,` + `,[g])),X=S$(p_(A,` SELECT id, type, @@ -1242,18 +1243,18 @@ Pages should be concise, cited, and organized for both humans and agents. FROM runs ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),E=l_(q,` + `,[g])),G=p_(A,` SELECT provider, model, dimensions, status, COUNT(*) AS entries FROM vector_index_entries GROUP BY provider, model, dimensions, status ORDER BY entries DESC LIMIT ? - `,[J]),F=K6(l_(q,` + `,[g]),R=S$(p_(A,` SELECT id, kind, target_id, source_uri, reason, status, attempts, metadata_json, created_at, updated_at FROM reindex_queue ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),w=K6(l_(q,` + `,[g])),K=S$(p_(A,` SELECT machine_id, hostname, @@ -1271,7 +1272,7 @@ Pages should be concise, cited, and organized for both humans and agents. FROM knowledge_machines ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J]),["tailscale_ips_json","capabilities_json","metadata_json"]),A=K6(l_(q,` + `,[g]),["tailscale_ips_json","capabilities_json","metadata_json"]),Q=S$(p_(A,` SELECT id, entity_kind, @@ -1288,17 +1289,17 @@ Pages should be concise, cited, and organized for both humans and agents. FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ? - `,[J])),g=K6(l_(q,` + `,[g])),T=S$(p_(A,` SELECT id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at FROM approval_gates ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),v=K6(l_(q,` + `,[g])),q=S$(p_(A,` SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT ? - `,[J])),k=l_(q,` + `,[g])),V=p_(A,` SELECT id, record_kind, @@ -1323,7 +1324,7 @@ Pages should be concise, cited, and organized for both humans and agents. FROM knowledge_promotion_candidates ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J]).map(Oc),u=l_(q,` + `,[g]).map(Db),Z=p_(A,` SELECT id, record_kind, @@ -1345,17 +1346,17 @@ Pages should be concise, cited, and organized for both humans and agents. FROM durable_knowledge_records ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J]).map(Lc),W_={legacy_items:W.items.length,active_items:X.length,archived_items:W.items.length-X.length,schema_version:Q.schema_version,sources:Q.sources,source_revisions:Q.source_revisions,chunks:Q.chunks,wiki_pages:Q.wiki_pages,citations:Q.citations,indexes:Q.indexes,runs:Q.runs,run_events:Q.run_events,storage_objects:Q.storage_objects,embeddings:Q.embeddings,vector_entries:Q.vector_entries,reindex_queue:Q.reindex_queue,redaction_findings:Q.redaction_findings,audit_events:Q.audit_events,approval_gates:Q.approval_gates,knowledge_machines:Q.knowledge_machines,sync_snapshots:Q.sync_snapshots,sync_changes:Q.sync_changes,sync_conflicts:Q.sync_conflicts,sync_table_clocks:Q.sync_table_clocks,sync_imports:Q.sync_imports,promotion_candidates:Q.promotion_candidates,durable_records:Q.durable_records};return{ok:!0,scope:this.scope,home:_.home,limit:J,paths:{json_store_path:U,json_store_exists:W.exists,knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,wiki_dir:_.wikiDir},summary:W_,legacy_store:{path:U,exists:W.exists,read_error:W.read_error,total_items:W.items.length,active_items:X.length,archived_items:W.items.length-X.length,items_returned:Math.min(G.length,J)},items:G.slice(0,J).map(kE),sources:L,source_revisions:N,chunks:R,wiki_pages:B,indexes:H,storage_objects:V,runs:K,vector_indexes:E,reindex_queue:F,machines:w,sync_conflicts:A,approval_gates:g,audit_events:v,promotion_candidates:k,durable_records:u,message:`${W.items.length} item(s), ${Q.sources} source(s), ${Q.chunks} chunk(s), ${Q.wiki_pages} wiki page(s), ${Q.storage_objects} artifact(s)`}}finally{q.close()}}assertAppWikiWrite($){FU({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:$})}async initAppWiki($={}){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return n3({scope:this.scope,workspace:_,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal})}async addAppWikiNote($){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return c3({scope:this.scope,workspace:_,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal,title:$.title,content:$.content,tags:$.tags,sourceRefs:$.sourceRefs,path:$.path,metadata:$.metadata})}listAppWikiNotes($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return[];return i3({dbPath:_.knowledgeDbPath,limit:$.limit})}async getAppWikiNote($,_={}){let J=this.workspace;if(!e$(J.knowledgeDbPath))return null;return l3({dbPath:J.knowledgeDbPath,store:this.artifactStore(),id:$,includeContent:_.includeContent})}async addAppWikiSourceRef($){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return r3({scope:this.scope,workspace:_,sourceRef:$.sourceRef,purpose:$.purpose,config:this.config(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal})}async searchAppWiki($){return this.search($)}async queryAppWiki($){return this.retrieveContext($)}async initWiki(){let $=this.ensureWorkspace();a($.knowledgeDbPath);let _=await zE(this.artifactStore()),J=m($.knowledgeDbPath);try{u4(J,_.artifacts),jE(J,_.artifacts)}finally{J.close()}return _}async compileWiki($={}){let _=this.ensureWorkspace();return GE({...$,dbPath:_.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer($){let _=this.ensureWorkspace(),J=await this.retrieveContext({query:$.prompt,limit:$.limit,semantic:$.semantic,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake});return YE({dbPath:_.knowledgeDbPath,store:this.artifactStore(),prompt:$.prompt,answer:$.answer,context:J,approveWrite:$.approveWrite})}lintWiki(){let $=this.ensureWorkspace();return QE({dbPath:$.knowledgeDbPath})}async ingestManifest($){let _=this.ensureWorkspace();return h3({dbPath:_.knowledgeDbPath,input:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource($,_){let J=this.ensureWorkspace();return l9({dbPath:J.knowledgeDbPath,sourceRef:$,purpose:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance($={}){let _=$.dryRun!==!1,J=_?this.workspace:this.ensureWorkspace();return oF({root:$.root??this.options.cwd??process.cwd(),scope:this.scope,owner:$.owner,dryRun:_,deprecateLegacy:$.deprecateLegacy,includeLegacy:$.includeLegacy,legacyStorePath:J.jsonStorePath,dbPath:J.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:$.maxItems,limit:$.limit})}async resolveSource($,_={}){let J=this.ensureWorkspace();return n9({dbPath:J.knowledgeDbPath,sourceRef:$,purpose:_.purpose,limit:_.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox($){let _=this.ensureWorkspace();return YF({dbPath:_.knowledgeDbPath,input:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return Rc();return hF({...$,dbPath:_.knowledgeDbPath,config:this.config()})}enqueueReindex($={}){let _=this.ensureWorkspace();return wL({...$,dbPath:_.knowledgeDbPath,config:this.config()})}async refreshEmbeddings($={}){let _=this.ensureWorkspace();return mF({...$,dbPath:_.knowledgeDbPath,config:this.config()})}providerStatus($=process.env){return s3(this.config(),$)}modelRegistry(){return hQ(this.config())}embeddingStatus(){let $=this.workspace;if(!e$($.knowledgeDbPath))return Kc();return UV($.knowledgeDbPath)}async indexEmbeddings($={}){let _=this.ensureWorkspace();return o9({...$,dbPath:_.knowledgeDbPath,config:this.config()})}isApiMode(){return K0()}async fetchCloudItems(){let $=KU();if(!$)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return v9($)}async semanticSearch($){let _=this.workspace;if(this.isApiMode()){let J=await this.fetchCloudItems(),U=await I1(J,{...$},["semantic_search_requires_local_catalog"]);return{provider:"openai",model:"text-embedding-3-small",dimensions:$.dimensions??1536,query:$.query,results:U.results}}if(!e$(_.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:$.dimensions??1536,query:$.query,results:[]};return t9({...$,dbPath:_.knowledgeDbPath,config:this.config()})}async search($){let _=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return I1(U,$)}let J=lL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){if(e$(J))return $8({...$,legacyStorePath:J,config:this.config()});return xE($.query,Math.max(1,Math.min($.limit??10,100)),$.semantic===!0||$.fake===!0||Boolean($.modelRef))}return e9({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async retrieveContext($){let _=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return J8(U,$)}let J=lL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){if(e$(J)){let U=await $8({...$,legacyStorePath:J,config:this.config()});return vJ(U,{contextChars:$.contextChars})}return Nc($.query,Math.max(1,Math.min($.limit??10,100)),$.semantic===!0||$.fake===!0||Boolean($.modelRef))}return yJ({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async contextPack($){let _=this.workspace;if(this.isApiMode()){let U=($.query??$.topic??"").trim();if(U&&$.source!=="loops"&&$.source!=="runs"){let W=await this.fetchCloudItems(),X=await I1(W,{...$,query:U}),G=vJ(X,{contextChars:$.contextChars});return CE($,G,this.safetyPolicy())}return PE($)}let J=lL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){let U=($.query??$.topic??"").trim();if(U&&$.source!=="loops"&&$.source!=="runs"&&e$(J)){let W=await $8({...$,query:U,legacyStorePath:J,config:this.config()}),X=vJ(W,{contextChars:$.contextChars});return CE($,X,this.safetyPolicy())}return PE($)}return SV({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt($){if(this.isApiMode()){let U=await this.fetchCloudItems();return bV(U,{...$,config:this.config()})}let _=this.ensureWorkspace(),J=$.legacyStorePath??_.jsonStorePath;if(!$.legacyStorePath)lW(J);return AV({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async webSearch($){let _=this.ensureWorkspace();return eF({...$,dbPath:_.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology($={}){let _=this.workspace;return EF({...$,knowledge:{scope:this.scope,workspace_home:_.home}})}async machinePreflight($={}){let _=this.workspace;return bF({...$,knowledge:{scope:this.scope,workspace_home:_.home}})}syncStatus(){let $=this.workspace;if(!e$($.knowledgeDbPath))return Fc({scope:this.scope,workspaceHome:$.home});return WR({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home})}async syncDoctor($={}){let _=this.ensureWorkspace();a(_.knowledgeDbPath);let J=this.syncStatus(),U=this.storageContract(),W=this.validateStorage(),X=Ec(_.knowledgeDbPath,U),G=$.machine?.trim()||null,Y=$.peerWorkspace?.trim()||null,Q=[],q=null,L=null;if(G&&!vE(G)){let V=await FL({machineId:G,includeTailscale:$.includeTailscale});q=iL(V),Q.push(...V.warnings)}if(G||Y){let V=await dG({machineId:G??cL(_),peerWorkspace:Y,includeTailscale:$.includeTailscale});if(G&&!Y&&(q?.source==="raw"||!V.ok||!V.project_root)){let K=ME(_.knowledgeDbPath,G);if(K){if(q?.source==="raw"&&K.ssh_target)q=iL(AE(K,G,{target:q.target,route:q.route,targetKind:q.target_kind,confidence:q.confidence,source:q.source,adapter:q.adapter,evidence:q.evidence,cacheability:q.cacheability,warnings:[]}));if(!V.ok||!V.project_root){let E=bE(K,G,V);if(E)L=rX(E,E.project_root),Q.push(...E.warnings)}}}L=V.ok&&V.project_root?rX(V,V.project_root):L??{...rX(V,Y??""),project_root:V.project_root??Y??""},Q.push(...V.warnings)}if(!W.ok)Q.push(...W.errors.map((V)=>`storage:${V}`));let N=zc(_.knowledgeDbPath,L);if(!N.ok)Q.push("open_files_boundary_raw_payload_sentinels");if(!X.ok)Q.push(...X.warnings);let R=L?.diagnostics.filter((V)=>V.severity==="fail")??[],B=W.ok&&X.ok&&N.ok&&R.length===0&&(L?.project_root!==""||!L),H=Ac({scope:this.scope,machine:G,peerWorkspace:Y,tables:$.tables,resolvedWorkspace:L,openConflicts:J.conflicts.open});return{ok:B,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:_.home,database:{sqlite_schema_version:J.sqlite_schema_version,table_counts:J.table_counts},storage:{contract:U,validation:W,artifact_manifest:X},sync:{machines:J.machines.total,snapshots:J.snapshots.total,clocks:J.clocks.total,imports:J.imports.total,open_conflicts:J.conflicts.open,table_clocks:J.clocks.rows},open_files:N,resolved_route:q,resolved_workspace:L,recommended_commands:H,warnings:[...new Set(Q)],message:B?`Sync readiness ok: ${J.clocks.total} table clock(s), ${J.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(Q)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys($={}){let _=this.ensureWorkspace();a(_.knowledgeDbPath);let J=this.storageContract(),U=aL(J),W=Mc(_.knowledgeDbPath,J),X=$.dryRun===!0||$.approveWrite!==!0;if(W.length===0)return{ok:!0,dry_run:X,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:"No legacy S3 artifact manifest keys found"};if($.dryRun===!0)return{ok:!0,dry_run:!0,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:`Would repair ${W.length} legacy S3 artifact manifest key(s)`};if($.approveWrite!==!0||!$.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let G=m(_.knowledgeDbPath);try{let Y=new Date().toISOString();G.transaction((L)=>{let N=G.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),R=G.query("SELECT id, metadata_json FROM storage_objects").all(),B=new Map(R.map((H)=>[H.id,j2(H.metadata_json)]));for(let H of L){let V=B.get(H.id)??{};V.key=H.repaired_key,N.run(JSON.stringify(V),Y,H.id)}})(W);let q=__(G,{event_type:"artifact_manifest_key_repair",action:"storage.artifact_manifest.repair_keys",target_uri:`knowledge-storage://${_.home}/storage_objects`,decision:"allow",metadata:{approved_by:$.approvedBy,repaired:W.length,storage_type:J.storage_type,storage_prefix:U,artifact_uris:W.map((L)=>L.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:W.length,audit_event_id:q,message:`Repaired ${W.length} legacy S3 artifact manifest key(s)`}}finally{G.close()}}async createSyncSnapshot($={}){let _=this.ensureWorkspace(),J=await this.machineTopology({includeTailscale:$.includeTailscale!==!1});return JR({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home,storage:this.storageContract(),topology:J,machineId:$.machineId})}syncConflicts($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return[];return UR(_.knowledgeDbPath,$)}syncConflict($){let _=this.ensureWorkspace(),J=D8(_.knowledgeDbPath,$);if(!J)throw Error(`Sync conflict not found: ${$}`);return J}proposeSyncConflictResolution($){let _=this.ensureWorkspace();return CU(_.knowledgeDbPath,$)}async proposeSyncConflictResolutionWithAi($){let _=this.ensureWorkspace();return XF({dbPath:_.knowledgeDbPath,id:$.id,config:this.config(),modelRef:$.modelRef,fake:$.fake,env:$.env})}resolveSyncConflict($){let _=this.ensureWorkspace(),J=CU(_.knowledgeDbPath,$.id);if($.approveWrite!==!0||!$.approvedBy)return{ok:!1,approval_required:!0,conflict:J.conflict,proposal:J,message:"Sync conflict resolution requires --approve-write and --approved-by "};let U=YR(_.knowledgeDbPath,{id:$.id,strategy:$.strategy??J.proposed_strategy,approvedBy:$.approvedBy,proposedPatchUri:$.proposedPatchUri}),W=m(_.knowledgeDbPath);try{let X=__(W,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${$.id}`,decision:"allow",metadata:{conflict_id:$.id,entity_kind:U.entity_kind,entity_id:U.entity_id,strategy:U.resolution_strategy,approved_by:U.approved_by,proposed_patch_uri:U.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:U,audit_event_id:X,message:`Resolved sync conflict ${$.id}`}}finally{W.close()}}syncMachines(){let $=this.workspace;if(!e$($.knowledgeDbPath))return[];return Wq($.knowledgeDbPath)}exportSyncBundle($={}){let _=this.ensureWorkspace();return this.assertStorageValid("sync export"),a(_.knowledgeDbPath),fU({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home,storage:this.storageContract(),machineId:$.machineId??null,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.recordClocks!==!1})}async importSyncBundle($){let _=this.ensureWorkspace();return this.assertStorageValid("sync import"),a(_.knowledgeDbPath),j8({targetDbPath:_.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:_.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:$.bundle,direction:$.direction??"import",dryRun:$.dryRun,localMachineId:$.machineId??null})}async syncRemotePeer($){let _=$.direction??"both",J=$.dryRun===!0,U=this.ensureWorkspace();a(U.knowledgeDbPath);let W=$.tables?.length?["--tables",$.tables.join(",")]:[],X=$.includeArtifactContent===!1?["--no-artifact-content"]:[],G=["--scope",this.scope,"--json"],Y=await FL({machineId:$.machine,includeTailscale:$.includeTailscale}),Q=await dG({machineId:$.machine,peerWorkspace:$.peerWorkspace,includeTailscale:$.includeTailscale});if(!$.peerWorkspace&&Y.source==="raw"||!Q.ok||!Q.project_root){let B=ME(U.knowledgeDbPath,$.machine);if(B){if(!$.peerWorkspace&&Y.source==="raw"&&B.ssh_target)Y=AE(B,$.machine,Y);if(!Q.ok||!Q.project_root){let H=bE(B,$.machine,Q);if(H)Q=H}}}if(!Q.ok||!Q.project_root)throw Error([`Unable to resolve peer workspace for ${$.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",Q.warnings.length?`Warnings: ${Q.warnings.join(", ")}`:null].filter(Boolean).join(" "));let q=Q.project_root,L={ok:!0,dry_run:J,direction:_,transport:"ssh",machine:$.machine,resolved_machine:Y.target,resolved_route:iL(Y),resolved_workspace:rX(Q,Q.project_root),peer_workspace:q,message:""},N=!1,R=()=>{if(J||N)return;eV(U.knowledgeDbPath,{machineId:$.machine,route:Y,workspace:Q}),N=!0};if(_==="pull"||_==="both"){let B=EE(q,["sync","export",...G,...W,...X]),H=TE($.machine,B,void 0,Y),V=SE($.machine,"sync export",H);wc($.machine,V),L.pull=await this.importSyncBundle({bundle:V,dryRun:J,direction:"pull",machineId:$.machineId??null})}if(_==="push"||_==="both"){R();let B=this.exportSyncBundle({machineId:$.machineId??null,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:!J}),H=EE(q,["sync","import",...G,...J?["--dry-run"]:[]]),V=SE($.machine,"sync import",TE($.machine,H,JSON.stringify(B),Y));gc($.machine,V),L.push=V}return L.ok=(L.pull?.ok??!0)&&(L.push?.ok??!0),R(),L.message=[wE(L.resolved_workspace),L.pull?`pull: ${L.pull.message}`:null,L.push?`push: ${L.push.message}`:null].filter(Boolean).join("; "),L}async syncPeer($){let _=$.direction??"both",J=this.ensureWorkspace();a(J.knowledgeDbPath);let U=ZE($.peerWorkspace),W=Jc(U);a(W.knowledgeDbPath);let X=KY(W.configPath),G=x9(X,W,this.scope),Y=AQ(X,W),Q=$.machineId??cL(J),q=cL(W),L=await dG({machineId:$.machineId??q,peerWorkspace:U,includeTailscale:!1}),N=()=>fU({dbPath:J.knowledgeDbPath,scope:this.scope,workspaceHome:J.home,storage:this.storageContract(),machineId:Q,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.dryRun!==!0}),R=()=>fU({dbPath:W.knowledgeDbPath,scope:this.scope,workspaceHome:W.home,storage:G,machineId:q,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.dryRun!==!0}),B={ok:!0,dry_run:$.dryRun===!0,direction:_,resolved_workspace:rX(L,L.project_root??U),message:""};if(_==="pull"||_==="both")B.pull=await j8({targetDbPath:J.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:J.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:R(),targetBundle:N(),direction:"pull",dryRun:$.dryRun,localMachineId:Q});if(_==="push"||_==="both")B.push=await j8({targetDbPath:W.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:W.home,targetStorage:G,targetStore:Y,bundle:N(),targetBundle:R(),direction:"push",dryRun:$.dryRun,localMachineId:q});return B.ok=(B.pull?.ok??!0)&&(B.push?.ok??!0),B.message=[wE(B.resolved_workspace),B.pull?`pull: ${B.pull.message}`:null,B.push?`push: ${B.push.message}`:null].filter(Boolean).join("; "),B}}function $Y($={}){return new uE($)}var Ic=Object.defineProperty,fc=($)=>$;function Cc($,_){this[$]=fc.bind(null,_)}var Pc=($,_)=>{for(var J in _)Ic($,J,{get:_[J],enumerable:!0,configurable:!0,set:Cc.bind(_,J)})},O={};Pc(O,{void:()=>Hi,util:()=>x$,unknown:()=>Li,union:()=>Ki,undefined:()=>ji,tuple:()=>Mi,transformer:()=>cE,symbol:()=>zi,string:()=>$M,strictObject:()=>Ri,setErrorMap:()=>Zc,set:()=>wi,record:()=>Ai,quotelessJson:()=>Tc,promise:()=>Pi,preprocess:()=>Zi,pipeline:()=>vi,ostring:()=>yi,optional:()=>Ti,onumber:()=>hi,oboolean:()=>mi,objectUtil:()=>_B,object:()=>Vi,number:()=>_M,nullable:()=>Si,null:()=>Di,never:()=>Bi,nativeEnum:()=>Ci,nan:()=>Yi,map:()=>bi,makeIssue:()=>JY,literal:()=>Ii,lazy:()=>ki,late:()=>Xi,isValid:()=>D2,isDirty:()=>WB,isAsync:()=>aX,isAborted:()=>JB,intersection:()=>Ei,instanceof:()=>Gi,getParsedType:()=>_0,getErrorMap:()=>_Y,function:()=>gi,enum:()=>fi,effect:()=>cE,discriminatedUnion:()=>Fi,defaultErrorMap:()=>MW,datetimeRegex:()=>aE,date:()=>qi,custom:()=>eE,coerce:()=>xi,boolean:()=>JM,bigint:()=>Qi,array:()=>Ni,any:()=>Oi,addIssueToContext:()=>l,ZodVoid:()=>eX,ZodUnknown:()=>i0,ZodUnion:()=>gW,ZodUndefined:()=>bW,ZodType:()=>S$,ZodTuple:()=>N4,ZodTransformer:()=>F6,ZodSymbol:()=>sX,ZodString:()=>l6,ZodSet:()=>B2,ZodSchema:()=>S$,ZodRecord:()=>$9,ZodReadonly:()=>SW,ZodPromise:()=>H2,ZodPipeline:()=>W9,ZodParsedType:()=>t,ZodOptional:()=>p6,ZodObject:()=>R_,ZodNumber:()=>l0,ZodNullable:()=>J0,ZodNull:()=>wW,ZodNever:()=>H4,ZodNativeEnum:()=>CW,ZodNaN:()=>J9,ZodMap:()=>_9,ZodLiteral:()=>fW,ZodLazy:()=>IW,ZodIssueCode:()=>Z,ZodIntersection:()=>kW,ZodFunction:()=>EW,ZodFirstPartyTypeKind:()=>B$,ZodError:()=>z6,ZodEnum:()=>p0,ZodEffects:()=>F6,ZodDiscriminatedUnion:()=>WY,ZodDefault:()=>PW,ZodDate:()=>O2,ZodCatch:()=>TW,ZodBranded:()=>UY,ZodBoolean:()=>AW,ZodBigInt:()=>r0,ZodArray:()=>r6,ZodAny:()=>L2,Schema:()=>S$,ParseStatus:()=>h_,OK:()=>r_,NEVER:()=>ui,INVALID:()=>j$,EMPTY_PATH:()=>vc,DIRTY:()=>FW,BRAND:()=>Ui});var x$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(x$||(x$={}));var _B;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(_B||(_B={}));var t=x$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),_0=($)=>{switch(typeof $){case"undefined":return t.undefined;case"string":return t.string;case"number":return Number.isNaN($)?t.nan:t.number;case"boolean":return t.boolean;case"function":return t.function;case"bigint":return t.bigint;case"symbol":return t.symbol;case"object":if(Array.isArray($))return t.array;if($===null)return t.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return t.promise;if(typeof Map<"u"&&$ instanceof Map)return t.map;if(typeof Set<"u"&&$ instanceof Set)return t.set;if(typeof Date<"u"&&$ instanceof Date)return t.date;return t.object;default:return t.unknown}},Z=x$.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Tc=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class z6 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}z6.create=($)=>{return new z6($)};var Sc=($,_)=>{let J;switch($.code){case Z.invalid_type:if($.received===t.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case Z.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,x$.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:J=`Unrecognized key(s) in object: ${x$.joinValues($.keys,", ")}`;break;case Z.invalid_union:J="Invalid input";break;case Z.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${x$.joinValues($.options)}`;break;case Z.invalid_enum_value:J=`Invalid enum value. Expected ${x$.joinValues($.options)}, received '${$.received}'`;break;case Z.invalid_arguments:J="Invalid function arguments";break;case Z.invalid_return_type:J="Invalid function return type";break;case Z.invalid_date:J="Invalid date";break;case Z.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else x$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case Z.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case Z.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case Z.custom:J="Invalid input";break;case Z.invalid_intersection_types:J="Intersection results could not be merged";break;case Z.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case Z.not_finite:J="Number must be finite";break;default:J=_.defaultError,x$.assertNever($)}return{message:J}},MW=Sc,pE=MW;function Zc($){pE=$}function _Y(){return pE}var JY=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},vc=[];function l($,_){let J=_Y(),U=JY({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===MW?void 0:MW].filter((W)=>!!W)});$.common.issues.push(U)}class h_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return j$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return h_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return j$;if(X.status==="aborted")return j$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var j$=Object.freeze({status:"aborted"}),FW=($)=>({status:"dirty",value:$}),r_=($)=>({status:"valid",value:$}),JB=($)=>$.status==="aborted",WB=($)=>$.status==="dirty",D2=($)=>$.status==="valid",aX=($)=>typeof Promise<"u"&&$ instanceof Promise,G$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(G$||(G$={}));class o6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var dE=($,_)=>{if(D2(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new z6($.common.issues);return this._error=J,this._error}}}};function w$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class S${get description(){return this._def.description}_getType($){return _0($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:_0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new h_,ctx:{common:$.parent.common,data:$.data,parsedType:_0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(aX(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:_0($)},U=this._parseSync({data:$,path:J.path,parent:J});return dE(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:_0($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return D2(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>D2(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:_0($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(aX(U)?U:Promise.resolve(U));return dE(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:Z.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new F6({schema:this,typeName:B$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(_)=>this["~validate"](_)}}optional(){return p6.create(this,this._def)}nullable(){return J0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return r6.create(this)}promise(){return H2.create(this,this._def)}or($){return gW.create([this,$],this._def)}and($){return kW.create(this,$,this._def)}transform($){return new F6({...w$(this._def),schema:this,typeName:B$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new PW({...w$(this._def),innerType:this,defaultValue:_,typeName:B$.ZodDefault})}brand(){return new UY({typeName:B$.ZodBranded,type:this,...w$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new TW({...w$(this._def),innerType:this,catchValue:_,typeName:B$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return W9.create(this,$)}readonly(){return SW.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var yc=/^c[^\s-]{8,}$/i,hc=/^[0-9a-z]+$/,mc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xc=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,uc=/^[a-z0-9_-]{21}$/i,dc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nc=/^[-+]?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)?)??$/,cc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ic="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",sL,lc=/^(?:(?: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])$/,rc=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,pc=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,oc=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ac=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oE="((\\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])))",sc=new RegExp(`^${oE}$`);function tE($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function ec($){return new RegExp(`^${tE($)}$`)}function aE($){let _=`${oE}T${tE($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function $i($,_){if((_==="v4"||!_)&&lc.test($))return!0;if((_==="v6"||!_)&&pc.test($))return!0;return!1}function _i($,_){if(!dc.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function Ji($,_){if((_==="v4"||!_)&&rc.test($))return!0;if((_==="v6"||!_)&&oc.test($))return!0;return!1}class l6 extends S${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==t.string){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_type,expected:t.string,received:W.parsedType}),j$}let J=new h_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),l(U,{code:Z.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:Z.invalid_string,...G$.errToObj(J)})}_addCheck($){return new l6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...G$.errToObj($)})}url($){return this._addCheck({kind:"url",...G$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...G$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...G$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...G$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...G$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...G$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...G$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...G$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...G$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...G$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...G$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...G$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...G$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...G$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...G$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...G$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...G$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...G$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...G$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...G$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...G$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...G$.errToObj(_)})}nonempty($){return this.min(1,G$.errToObj($))}trim(){return new l6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new l6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new l6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}l6.create=($)=>{return new l6({checks:[],typeName:B$.ZodString,coerce:$?.coerce??!1,...w$($)})};function Wi($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class l0 extends S${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==t.number){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_type,expected:t.number,received:W.parsedType}),j$}let J=void 0,U=new h_;for(let W of this._def.checks)if(W.kind==="int"){if(!x$.isInteger($.data))J=this._getOrReturnCtx($,J),l(J,{code:Z.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),l(J,{code:Z.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(Wi($.data,W.value)!==0)J=this._getOrReturnCtx($,J),l(J,{code:Z.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),l(J,{code:Z.not_finite,message:W.message}),U.dirty()}else x$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,G$.toString(_))}gt($,_){return this.setLimit("min",$,!1,G$.toString(_))}lte($,_){return this.setLimit("max",$,!0,G$.toString(_))}lt($,_){return this.setLimit("max",$,!1,G$.toString(_))}setLimit($,_,J,U){return new l0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:G$.toString(U)}]})}_addCheck($){return new l0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:G$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:G$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:G$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&x$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}l0.create=($)=>{return new l0({checks:[],typeName:B$.ZodNumber,coerce:$?.coerce||!1,...w$($)})};class r0 extends S${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==t.bigint)return this._getInvalidInput($);let J=void 0,U=new h_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),l(J,{code:Z.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),l(J,{code:Z.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else x$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return l(_,{code:Z.invalid_type,expected:t.bigint,received:_.parsedType}),j$}gte($,_){return this.setLimit("min",$,!0,G$.toString(_))}gt($,_){return this.setLimit("min",$,!1,G$.toString(_))}lte($,_){return this.setLimit("max",$,!0,G$.toString(_))}lt($,_){return this.setLimit("max",$,!1,G$.toString(_))}setLimit($,_,J,U){return new r0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:G$.toString(U)}]})}_addCheck($){return new r0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:G$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}r0.create=($)=>{return new r0({checks:[],typeName:B$.ZodBigInt,coerce:$?.coerce??!1,...w$($)})};class AW extends S${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==t.boolean){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.boolean,received:J.parsedType}),j$}return r_($.data)}}AW.create=($)=>{return new AW({typeName:B$.ZodBoolean,coerce:$?.coerce||!1,...w$($)})};class O2 extends S${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==t.date){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_type,expected:t.date,received:W.parsedType}),j$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_date}),j$}let J=new h_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),l(U,{code:Z.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else x$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new O2({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:G$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:G$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}O2.create=($)=>{return new O2({checks:[],coerce:$?.coerce||!1,typeName:B$.ZodDate,...w$($)})};class sX extends S${_parse($){if(this._getType($)!==t.symbol){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.symbol,received:J.parsedType}),j$}return r_($.data)}}sX.create=($)=>{return new sX({typeName:B$.ZodSymbol,...w$($)})};class bW extends S${_parse($){if(this._getType($)!==t.undefined){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.undefined,received:J.parsedType}),j$}return r_($.data)}}bW.create=($)=>{return new bW({typeName:B$.ZodUndefined,...w$($)})};class wW extends S${_parse($){if(this._getType($)!==t.null){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.null,received:J.parsedType}),j$}return r_($.data)}}wW.create=($)=>{return new wW({typeName:B$.ZodNull,...w$($)})};class L2 extends S${constructor(){super(...arguments);this._any=!0}_parse($){return r_($.data)}}L2.create=($)=>{return new L2({typeName:B$.ZodAny,...w$($)})};class i0 extends S${constructor(){super(...arguments);this._unknown=!0}_parse($){return r_($.data)}}i0.create=($)=>{return new i0({typeName:B$.ZodUnknown,...w$($)})};class H4 extends S${_parse($){let _=this._getOrReturnCtx($);return l(_,{code:Z.invalid_type,expected:t.never,received:_.parsedType}),j$}}H4.create=($)=>{return new H4({typeName:B$.ZodNever,...w$($)})};class eX extends S${_parse($){if(this._getType($)!==t.undefined){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.void,received:J.parsedType}),j$}return r_($.data)}}eX.create=($)=>{return new eX({typeName:B$.ZodVoid,...w$($)})};class r6 extends S${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==t.array)return l(_,{code:Z.invalid_type,expected:t.array,received:_.parsedType}),j$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)l(_,{code:Z.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new o6(_,X,_.path,G))})).then((X)=>{return h_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new o6(_,X,_.path,G))});return h_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new r6({...this._def,minLength:{value:$,message:G$.toString(_)}})}max($,_){return new r6({...this._def,maxLength:{value:$,message:G$.toString(_)}})}length($,_){return new r6({...this._def,exactLength:{value:$,message:G$.toString(_)}})}nonempty($){return this.min(1,$)}}r6.create=($,_)=>{return new r6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:B$.ZodArray,...w$(_)})};function KW($){if($ instanceof R_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=p6.create(KW(U))}return new R_({...$._def,shape:()=>_})}else if($ instanceof r6)return new r6({...$._def,type:KW($.element)});else if($ instanceof p6)return p6.create(KW($.unwrap()));else if($ instanceof J0)return J0.create(KW($.unwrap()));else if($ instanceof N4)return N4.create($.items.map((_)=>KW(_)));else return $}class R_ extends S${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=x$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==t.object){let Q=this._getOrReturnCtx($);return l(Q,{code:Z.invalid_type,expected:t.object,received:Q.parsedType}),j$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof H4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new o6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof H4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)l(U,{code:Z.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new o6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return h_.mergeObjectSync(J,Q)});else return h_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return G$.errToObj,new R_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:G$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new R_({...this._def,unknownKeys:"strip"})}passthrough(){return new R_({...this._def,unknownKeys:"passthrough"})}extend($){return new R_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new R_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:B$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new R_({...this._def,catchall:$})}pick($){let _={};for(let J of x$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new R_({...this._def,shape:()=>_})}omit($){let _={};for(let J of x$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new R_({...this._def,shape:()=>_})}deepPartial(){return KW(this)}partial($){let _={};for(let J of x$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new R_({...this._def,shape:()=>_})}required($){let _={};for(let J of x$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof p6)W=W._def.innerType;_[J]=W}return new R_({...this._def,shape:()=>_})}keyof(){return sE(x$.objectKeys(this.shape))}}R_.create=($,_)=>{return new R_({shape:()=>$,unknownKeys:"strip",catchall:H4.create(),typeName:B$.ZodObject,...w$(_)})};R_.strictCreate=($,_)=>{return new R_({shape:()=>$,unknownKeys:"strict",catchall:H4.create(),typeName:B$.ZodObject,...w$(_)})};R_.lazycreate=($,_)=>{return new R_({shape:$,unknownKeys:"strip",catchall:H4.create(),typeName:B$.ZodObject,...w$(_)})};class gW extends S${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new z6(G.ctx.common.issues));return l(_,{code:Z.invalid_union,unionErrors:X}),j$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new z6(Y));return l(_,{code:Z.invalid_union,unionErrors:G}),j$}}get options(){return this._def.options}}gW.create=($,_)=>{return new gW({options:$,typeName:B$.ZodUnion,...w$(_)})};var $0=($)=>{if($ instanceof IW)return $0($.schema);else if($ instanceof F6)return $0($.innerType());else if($ instanceof fW)return[$.value];else if($ instanceof p0)return $.options;else if($ instanceof CW)return x$.objectValues($.enum);else if($ instanceof PW)return $0($._def.innerType);else if($ instanceof bW)return[void 0];else if($ instanceof wW)return[null];else if($ instanceof p6)return[void 0,...$0($.unwrap())];else if($ instanceof J0)return[null,...$0($.unwrap())];else if($ instanceof UY)return $0($.unwrap());else if($ instanceof SW)return $0($.unwrap());else if($ instanceof TW)return $0($._def.innerType);else return[]};class WY extends S${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.object)return l(_,{code:Z.invalid_type,expected:t.object,received:_.parsedType}),j$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return l(_,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),j$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=$0(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new WY({typeName:B$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...w$(J)})}}function UB($,_){let J=_0($),U=_0(_);if($===_)return{valid:!0,data:$};else if(J===t.object&&U===t.object){let W=x$.objectKeys(_),X=x$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=UB($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===t.array&&U===t.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=UB(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===t.date&&U===t.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class kW extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(JB(W)||JB(X))return j$;let G=UB(W.value,X.value);if(!G.valid)return l(J,{code:Z.invalid_intersection_types}),j$;if(WB(W)||WB(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}kW.create=($,_,J)=>{return new kW({left:$,right:_,typeName:B$.ZodIntersection,...w$(J)})};class N4 extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.array)return l(J,{code:Z.invalid_type,expected:t.array,received:J.parsedType}),j$;if(J.data.lengththis._def.items.length)l(J,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new o6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return h_.mergeArray(_,X)});else return h_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new N4({...this._def,rest:$})}}N4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new N4({items:$,typeName:B$.ZodTuple,rest:null,...w$(_)})};class $9 extends S${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.object)return l(J,{code:Z.invalid_type,expected:t.object,received:J.parsedType}),j$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new o6(J,G,J.path,G)),value:X._parse(new o6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return h_.mergeObjectAsync(_,U);else return h_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof S$)return new $9({keyType:$,valueType:_,typeName:B$.ZodRecord,...w$(J)});return new $9({keyType:l6.create(),valueType:$,typeName:B$.ZodRecord,...w$(_)})}}class _9 extends S${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.map)return l(J,{code:Z.invalid_type,expected:t.map,received:J.parsedType}),j$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new o6(J,G,J.path,[Q,"key"])),value:W._parse(new o6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return j$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return j$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}_9.create=($,_,J)=>{return new _9({valueType:_,keyType:$,typeName:B$.ZodMap,...w$(J)})};class B2 extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.set)return l(J,{code:Z.invalid_type,expected:t.set,received:J.parsedType}),j$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)l(J,{code:Z.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return j$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new o6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new B2({...this._def,minSize:{value:$,message:G$.toString(_)}})}max($,_){return new B2({...this._def,maxSize:{value:$,message:G$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}B2.create=($,_)=>{return new B2({valueType:$,minSize:null,maxSize:null,typeName:B$.ZodSet,...w$(_)})};class EW extends S${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.function)return l(_,{code:Z.invalid_type,expected:t.function,received:_.parsedType}),j$;function J(G,Y){return JY({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,_Y(),MW].filter((Q)=>!!Q),issueData:{code:Z.invalid_arguments,argumentsError:Y}})}function U(G,Y){return JY({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,_Y(),MW].filter((Q)=>!!Q),issueData:{code:Z.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof H2){let G=this;return r_(async function(...Y){let Q=new z6([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return r_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new z6([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new z6([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new EW({...this._def,args:N4.create($).rest(i0.create())})}returns($){return new EW({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new EW({args:$?$:N4.create([]).rest(i0.create()),returns:_||i0.create(),typeName:B$.ZodFunction,...w$(J)})}}class IW extends S${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}IW.create=($,_)=>{return new IW({getter:$,typeName:B$.ZodLazy,...w$(_)})};class fW extends S${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return l(_,{received:_.data,code:Z.invalid_literal,expected:this._def.value}),j$}return{status:"valid",value:$.data}}get value(){return this._def.value}}fW.create=($,_)=>{return new fW({value:$,typeName:B$.ZodLiteral,...w$(_)})};function sE($,_){return new p0({values:$,typeName:B$.ZodEnum,...w$(_)})}class p0 extends S${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return l(_,{expected:x$.joinValues(J),received:_.parsedType,code:Z.invalid_type}),j$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return l(_,{received:_.data,code:Z.invalid_enum_value,options:J}),j$}return r_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return p0.create($,{...this._def,..._})}exclude($,_=this._def){return p0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}p0.create=sE;class CW extends S${_parse($){let _=x$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==t.string&&J.parsedType!==t.number){let U=x$.objectValues(_);return l(J,{expected:x$.joinValues(U),received:J.parsedType,code:Z.invalid_type}),j$}if(!this._cache)this._cache=new Set(x$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=x$.objectValues(_);return l(J,{received:J.data,code:Z.invalid_enum_value,options:U}),j$}return r_($.data)}get enum(){return this._def.values}}CW.create=($,_)=>{return new CW({values:$,typeName:B$.ZodNativeEnum,...w$(_)})};class H2 extends S${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.promise&&_.common.async===!1)return l(_,{code:Z.invalid_type,expected:t.promise,received:_.parsedType}),j$;let J=_.parsedType===t.promise?_.data:Promise.resolve(_.data);return r_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}H2.create=($,_)=>{return new H2({type:$,typeName:B$.ZodPromise,...w$(_)})};class F6 extends S${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(l(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return j$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return j$;if(Y.status==="dirty")return FW(Y.value);if(_.value==="dirty")return FW(Y.value);return Y});else{if(_.value==="aborted")return j$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return j$;if(G.status==="dirty")return FW(G.value);if(_.value==="dirty")return FW(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return j$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return j$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!D2(X))return j$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!D2(X))return j$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});x$.assertNever(U)}}F6.create=($,_,J)=>{return new F6({schema:$,typeName:B$.ZodEffects,effect:_,...w$(J)})};F6.createWithPreprocess=($,_,J)=>{return new F6({schema:_,effect:{type:"preprocess",transform:$},typeName:B$.ZodEffects,...w$(J)})};class p6 extends S${_parse($){if(this._getType($)===t.undefined)return r_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}p6.create=($,_)=>{return new p6({innerType:$,typeName:B$.ZodOptional,...w$(_)})};class J0 extends S${_parse($){if(this._getType($)===t.null)return r_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}J0.create=($,_)=>{return new J0({innerType:$,typeName:B$.ZodNullable,...w$(_)})};class PW extends S${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===t.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}PW.create=($,_)=>{return new PW({innerType:$,typeName:B$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...w$(_)})};class TW extends S${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(aX(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new z6(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new z6(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}TW.create=($,_)=>{return new TW({innerType:$,typeName:B$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...w$(_)})};class J9 extends S${_parse($){if(this._getType($)!==t.nan){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.nan,received:J.parsedType}),j$}return{status:"valid",value:$.data}}}J9.create=($)=>{return new J9({typeName:B$.ZodNaN,...w$($)})};var Ui=Symbol("zod_brand");class UY extends S${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class W9 extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return j$;if(W.status==="dirty")return _.dirty(),FW(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return j$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new W9({in:$,out:_,typeName:B$.ZodPipeline})}}class SW extends S${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(D2(U))U.value=Object.freeze(U.value);return U};return aX(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}SW.create=($,_)=>{return new SW({innerType:$,typeName:B$.ZodReadonly,...w$(_)})};function nE($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function eE($,_={},J){if($)return L2.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=nE(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=nE(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return L2.create()}var Xi={object:R_.lazycreate},B$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(B$||(B$={}));var Gi=($,_={message:`Input not instance of ${$.name}`})=>eE((J)=>J instanceof $,_),$M=l6.create,_M=l0.create,Yi=J9.create,Qi=r0.create,JM=AW.create,qi=O2.create,zi=sX.create,ji=bW.create,Di=wW.create,Oi=L2.create,Li=i0.create,Bi=H4.create,Hi=eX.create,Ni=r6.create,Vi=R_.create,Ri=R_.strictCreate,Ki=gW.create,Fi=WY.create,Ei=kW.create,Mi=N4.create,Ai=$9.create,bi=_9.create,wi=B2.create,gi=EW.create,ki=IW.create,Ii=fW.create,fi=p0.create,Ci=CW.create,Pi=H2.create,cE=F6.create,Ti=p6.create,Si=J0.create,Zi=F6.createWithPreprocess,vi=W9.create,yi=()=>$M().optional(),hi=()=>_M().optional(),mi=()=>JM().optional(),xi={string:($)=>l6.create({...$,coerce:!0}),number:($)=>l0.create({...$,coerce:!0}),boolean:($)=>AW.create({...$,coerce:!0}),bigint:($)=>r0.create({...$,coerce:!0}),date:($)=>O2.create({...$,coerce:!0})},ui=j$;var s={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},WM=O.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),j6=O.string().datetime(),K$=O.string().trim().min(1),t6=K$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),UM=O.string().regex(/^[a-fA-F0-9]{64}$/),XM=O.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),W0=O.record(O.unknown()),yW=O.array(O.string().min(1)).default([]),N2=j6.nullable().optional(),di=new Set(["succeeded","failed","cancelled","blocked","skipped"]),R2=O.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function $_($){return O.object({schema:O.literal($),id:O.string().min(1),createdAt:j6,updatedAt:N2,metadata:W0.optional()}).strict()}var T4$=O.object({schema:WM,id:O.string().min(1),createdAt:j6,updatedAt:N2,metadata:W0.optional()}).strict(),GM=O.enum(["agent","human","service","model","workflow","system"]),ni=$_(s.actorRef).extend({kind:GM,name:O.string().min(1).optional(),provider:O.string().min(1).optional(),accountId:O.string().min(1).optional(),machineId:O.string().min(1).optional(),capabilities:O.array(O.string().min(1)).default([])}).strict(),V4=O.object({kind:GM,id:O.string().min(1),name:O.string().min(1).optional(),provider:O.string().min(1).optional(),accountId:O.string().min(1).optional(),machineId:O.string().min(1).optional()}).strict(),YM=O.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),ci=$_(s.resourceRef).extend({kind:YM,name:O.string().min(1).optional(),uri:t6.optional(),externalId:K$.optional(),sourcePackage:K$.optional(),tags:yW}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:O.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),T$=O.object({kind:YM,id:O.string().min(1),name:O.string().min(1).optional(),uri:t6.optional(),externalId:K$.optional(),sourcePackage:K$.optional(),tags:yW}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:O.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),XB=O.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),ii=O.enum(["none","partial","full","unknown"]),li=$_(s.evidenceRef).extend({kind:XB,uri:t6,sha256:UM.optional(),summary:O.string().min(1).optional(),contentType:O.string().min(1).optional(),sizeBytes:O.number().int().nonnegative().optional(),redaction:ii.default("unknown"),producer:V4.optional(),resourceRefs:O.array(T$).default([]),tags:yW}).strict(),q_=O.object({id:O.string().min(1),kind:XB.optional(),uri:t6.optional(),sha256:UM.optional(),summary:O.string().min(1).optional()}).strict(),U9=$_(s.costEstimate).extend({currency:O.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:O.number().int().nonnegative(),provider:O.string().min(1).optional(),model:O.string().min(1).optional(),accountId:O.string().min(1).optional(),promptTokens:O.number().int().nonnegative().optional(),completionTokens:O.number().int().nonnegative().optional(),totalTokens:O.number().int().nonnegative().optional(),basis:O.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:O.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),ri=O.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),QM=$_(s.decisionEnvelope).extend({decisionType:O.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:ri,actor:V4.optional(),traceId:O.string().min(1).optional(),inputHash:XM.optional(),policyBundleId:O.string().min(1).optional(),selected:O.array(T$).default([]),skipped:O.array(T$).default([]),reason:O.string().min(1),obligations:O.array(O.string().min(1)).default([]),redactions:O.array(O.string().min(1)).default([]),costEstimate:U9.optional(),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),pi=$_(s.capabilityCard).extend({kind:O.enum(["model","tool","machine","agent","lane","connector","service"]),name:O.string().min(1),version:O.string().min(1).optional(),status:O.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:O.array(O.string().min(1)).default([]),limitations:O.array(O.string().min(1)).default([]),riskLevel:O.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:U9.optional(),evidenceRefs:O.array(q_).default([])}).strict(),ZW=O.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),oi=O.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),ti=O.object({refName:K$,requiredForModes:O.array(ZW).min(1),allowedSecretInputs:O.array(O.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:K$,revocationCheck:O.boolean().default(!0)}).strict(),ai=O.object({operation:K$,supportedModes:O.array(ZW).min(1),sideEffectClass:oi,requiresApproval:O.boolean().default(!1),requiresIdempotencyKey:O.boolean().default(!1),requiresSandboxEvidence:O.boolean().default(!1),requiresRollbackOrRevocation:O.boolean().default(!1),rollbackOrRevocation:K$.optional(),noSideEffectSmoke:K$.optional(),reconciliation:K$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),si=O.object({providerId:K$,appId:K$,adapterId:K$,ownerPackage:K$,modes:O.array(ZW).min(1),defaultMode:ZW,credentialRequirements:O.array(ti).default([]),operations:O.array(ai).min(1),rateLimitPosture:K$,costPosture:K$.optional(),auditEvents:O.array(K$).default([]),redactionRules:O.array(K$).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:O.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),ei=O.object({appId:K$,repo:K$,priority:O.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:O.array(K$).min(1),firstOperations:O.array(K$).min(1),blockedUntil:O.array(K$).default([])}).strict(),$l=$_(s.providerLiveModeStandard).extend({name:K$,version:K$,modes:O.array(ZW).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:O.array(K$).min(1),liveMutationGate:O.object({requiredMode:O.literal("live_mutating"),requiredChecks:O.array(K$).min(1),forbiddenBypassSignals:O.array(K$).min(1),disabledLiveSmoke:K$}).strict(),noSideEffectSmoke:O.object({requiredForModes:O.array(ZW).min(1),commandEvidence:O.array(K$).min(1),secretOutputScan:O.boolean().default(!0)}).strict(),credentialPolicy:O.object({acceptedInputs:O.array(O.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:O.literal(!1),missingCredentialBehavior:O.literal("fail_closed"),revocationCheckRequired:O.boolean().default(!0)}).strict(),operationCards:O.array(si).min(1),firstAdoptionTargets:O.array(ei).min(1),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:O.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),_l=O.object({id:O.string().min(1),title:O.string().min(1).optional(),summary:O.string().min(1),text:O.string().optional(),tokens:O.number().int().nonnegative().optional(),source:q_,resourceRefs:O.array(T$).default([])}).strict(),qM=$_(s.contextPack).extend({objective:O.string().min(1),budget:O.object({maxTokens:O.number().int().positive().optional(),maxBytes:O.number().int().positive().optional()}).strict().optional(),items:O.array(_l).default([]),citations:O.array(q_).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),permissions:O.array(O.string().min(1)).default([]),redactions:O.array(O.string().min(1)).default([]),conflicts:O.array(O.string().min(1)).default([]),uncertainty:O.string().min(1).optional()}).strict(),i6=K$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),V2=O.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),Jl=O.enum(["public","internal","private","sensitive"]),Wl=O.enum(["draft","active","paused","archived"]),GB=O.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),zM=$_(s.integrationRef).extend({kind:GB,name:O.string().min(1),projectId:V2.optional(),sourcePackage:K$.optional(),externalId:K$.optional(),uri:t6.optional(),enabled:O.boolean().default(!0),readOnly:O.boolean().default(!0),capabilities:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:T$.optional(),evidenceRefs:O.array(q_).default([]),config:W0.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:O.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),Ul=O.object({schemaRoot:i6.default(".hasna/project"),dashboardManifest:i6.default(".hasna/project/dashboard.render.json"),snapshotsDir:i6.default(".hasna/project/snapshots"),documentsDir:i6.default("documents"),reportsDir:i6.default("reports"),evidenceDir:i6.default(".hasna/project/evidence"),privateDir:i6.default(".hasna/project/private")}).strict(),Xl=$_(s.projectManifest).extend({projectId:V2,slug:V2,name:O.string().min(1),summary:O.string().min(1).optional(),status:Wl.default("active"),classification:Jl.default("private"),owner:V4.optional(),layout:Ul.default({}),integrations:O.array(zM).default([]),renderManifests:O.array(T$).default([]),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),tags:yW}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:O.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:O.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:O.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),Gl=O.enum(["local","package","provider","url"]),YB=O.object({id:O.string().min(1),kind:Gl,specifier:O.string().min(1),path:i6.optional(),packageName:O.string().min(1).optional(),uri:t6.optional(),provider:GB.optional(),schemaId:WM.optional(),integrity:XM.optional(),resourceRef:T$.optional(),optional:O.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:O.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:O.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:O.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:O.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),Yl=O.enum(["dashboard","canvas","panel","report","document","custom"]),Ql=O.object({id:O.string().min(1),title:O.string().min(1),kind:Yl,default:O.boolean().default(!1),entry:i6.optional(),imports:O.array(YB).default([]),panelRefs:O.array(T$).default([]),dataRefs:O.array(T$).default([]),layout:W0.optional()}).strict(),ql=$_(s.renderManifest).extend({projectId:V2,name:O.string().min(1),version:O.string().min(1),manifestPath:i6.default(".hasna/project/dashboard.render.json"),renderer:O.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:O.array(Ql).min(1),imports:O.array(YB).default([]),theme:W0.optional(),compatibility:O.object({minProjectsVersion:O.string().min(1).optional(),minContractsVersion:O.string().min(1).optional()}).strict().optional(),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:O.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),zl=O.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),jl=O.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Dl=O.object({id:O.string().min(1),label:O.string().min(1),value:O.union([O.string(),O.number(),O.boolean()]),unit:O.string().min(1).optional(),status:O.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:O.array(T$).default([])}).strict(),Ol=O.object({id:O.string().min(1),title:O.string().min(1),summary:O.string().min(1).optional(),status:O.string().min(1).optional(),priority:O.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:j6.optional(),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),metadata:W0.optional()}).strict(),Ll=O.object({renderer:O.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:O.string().min(1).optional(),entry:i6.optional(),imports:O.array(YB).default([]),spec:W0.default({})}).strict(),jM=$_(s.projectPanel).extend({projectId:V2,provider:O.object({kind:GB,id:O.string().min(1),name:O.string().min(1).optional(),sourcePackage:K$.optional(),externalId:K$.optional()}).strict(),kind:jl,title:O.string().min(1),summary:O.string().min(1).optional(),state:zl.default("ready"),stateReason:O.string().min(1).optional(),generatedAt:j6,freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),metrics:O.array(Dl).default([]),items:O.array(Ol).default([]),actions:O.array(T$).default([]),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),renderFragment:Ll.optional(),warnings:O.array(O.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:O.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:O.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),Bl=$_(s.projectSnapshot).extend({projectId:V2,generatedAt:j6,status:R2.default("unknown"),manifestRef:T$,renderManifestRef:T$.optional(),panels:O.array(jM).default([]),contextPacks:O.array(qM).default([]),proofBundleRefs:O.array(T$).default([]),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),warnings:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:O.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),DM=O.object({id:O.string().min(1),kind:O.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:O.boolean().default(!0),command:O.string().min(1).optional(),expected:O.string().min(1).optional(),timeoutMs:O.number().int().positive().optional(),resourceRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:O.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),Hl=$_(s.validationPlan).extend({objective:O.string().min(1),subject:T$.optional(),checks:O.array(DM).min(1),verifier:V4.optional(),requiredEvidenceKinds:O.array(XB).default([])}).strict(),Nl=O.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),Vl=O.enum(["draft","active","deprecated","archived"]),Rl=O.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Kl=O.object({key:O.string().regex(/^[A-Z][A-Z0-9_]*$/),description:O.string().min(1),required:O.boolean().default(!1),["secret"]:O.boolean().default(!1),group:O.string().min(1).optional(),default:O.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Fl=O.object({name:O.string().min(1),command:O.string().min(1),description:O.string().min(1).optional(),required:O.boolean().default(!1)}).strict(),El=O.object({packageManager:O.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:O.array(O.string().min(1)).default([]),requiredFiles:O.array(O.string().min(1)).default([]),requiredDirectories:O.array(O.string().min(1)).default([]),optionalDirectories:O.array(O.string().min(1)).default([])}).strict(),Ml=$_(s.scaffoldManifest).extend({name:O.string().min(1),version:O.string().min(1),summary:O.string().min(1),type:Nl,status:Vl.default("draft"),capabilities:O.array(Rl).default([]),techStack:O.array(O.string().min(1)).default([]),tags:yW,source:T$.optional(),output:El,env:O.array(Kl).default([]),scripts:O.array(Fl).default([]),validationChecks:O.array(DM).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:O.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),Al=O.enum(["installed","failed","cancelled","partial","unknown"]),bl=$_(s.scaffoldInstallRecord).extend({scaffoldId:O.string().min(1),scaffoldVersion:O.string().min(1).optional(),manifestRef:T$.optional(),target:T$,status:Al,installedAt:j6.optional(),installer:V4.optional(),packageManager:O.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:W0.optional(),generatedFiles:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),proofBundleRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:O.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),vW=O.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),QB=O.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),OM=O.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),wl=O.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),gl=K$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),kl=O.enum(["active","stub","deprecated","archived"]),Il=O.enum(["stable","beta","canary","internal"]),fl=O.object({transport:O.enum(["http","stdio"]).default("http"),bin:O.string().min(1).optional(),url:t6.optional()}).strict(),Cl=O.object({healthPath:O.string().min(1).default("/health"),port:O.number().int().positive().optional(),baseUrl:t6.optional()}).strict(),Pl=O.object({bins:O.array(O.string().min(1)).default([]),mcp:fl.optional(),http:Cl.optional()}).strict(),Tl=$_(s.app).extend({appId:vW,npmName:QB,repoFolder:vW,githubUrl:gl,projectSlug:V2,surfaces:Pl.default({}),lifecycle:kl,releaseChannel:Il.default("stable"),summary:O.string().min(1).optional(),tags:yW}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:O.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),Sl=O.enum(["skill","ci","backfilled"]),Zl=$_(s.release).extend({appId:vW,package:QB,version:OM,gitSha:wl,publishedAt:j6,publishPath:Sl,changelogRef:T$.optional(),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),vl=O.enum(["install","update","rollback","freeze-blocked"]),yl=O.object({cliVersion:O.string().min(1).optional(),mcpHealth:O.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),hl=$_(s.rolloutRecord).extend({appId:vW,package:QB,version:OM,machine:K$,action:vl,result:R2,verifiedBy:yl.optional(),at:j6,evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:O.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),ml=O.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),xl=O.enum(["pending","queued","sent","failed","skipped","suppressed"]),ul=O.object({channel:ml,status:xl,deliveredAt:j6.optional(),detail:O.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:O.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),dl=$_(s.announcement).extend({campaignId:K$,appId:vW.optional(),releaseRef:T$.optional(),channels:O.array(ul).min(1),audienceRef:T$,sentAt:j6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:O.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:O.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),nl=O.enum(["tag","attribute","group"]),cl=O.enum(["eq","neq","in","not_in","exists","not_exists"]),iE=O.union([O.string(),O.number(),O.boolean()]),il=O.object({kind:nl,key:O.string().min(1).optional(),op:cl.default("eq"),value:iE.optional(),values:O.array(iE).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:O.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),ll=O.object({match:O.enum(["all","any"]).default("all"),predicates:O.array(il).min(1)}).strict(),rl=O.enum(["opt_in","opt_out","transactional","none"]),pl=$_(s.audience).extend({audienceId:vW,name:K$,definition:ll,consentPolicy:rl,suppressionSyncedAt:N2}).strict(),eL=["@hasna/cloud","open-cloud"],ol=O.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),tl=O.object({id:O.string().min(1),provider:ol,kind:O.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:O.string().min(1),region:O.string().min(1).optional(),accountId:O.string().min(1).optional(),uri:t6.optional(),machineScoped:O.boolean().default(!1)}).strict(),LM=$_(s.appCloudManifest).extend({packageName:O.string().min(1),packageVersion:O.string().min(1).optional(),appId:O.string().min(1),repository:T$.optional(),storageMode:O.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:O.enum(["none","app_owned","external_service","local_cache"]),cloudResources:O.array(tl).default([]),localCache:O.object({path:O.string().min(1).optional(),pullMode:O.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:O.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:O.array(O.string().min(1)).default([...eL]),dependencies:O.array(O.string().min(1)).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...eL,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:O.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of eL)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:O.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:O.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:O.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:O.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:O.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:O.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),BM=O.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),al=O.enum(["low","medium","high","critical"]),HM=O.object({id:O.string().min(1),kind:BM,severity:al,path:O.string().min(1).optional(),packageName:O.string().min(1).optional(),pattern:O.string().min(1),message:O.string().min(1),evidenceRefs:O.array(q_).default([])}).strict(),sl=O.object({id:O.string().min(1),kind:BM,status:R2,target:O.string().min(1),command:O.string().min(1).optional(),evidenceRefs:O.array(q_).default([]),findings:O.array(HM).default([])}).strict(),el=$_(s.noCloudEvidencePack).extend({subject:T$,packageName:O.string().min(1).optional(),packageVersion:O.string().min(1).optional(),generatedBy:V4.optional(),scanMode:O.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:R2,verdict:O.enum(["passed","failed","warning","not_run"]),appCloudManifest:LM.optional(),checks:O.array(sl).min(1),findings:O.array(HM).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),$r=O.object({checkId:O.string().min(1),status:R2,summary:O.string().min(1).optional(),startedAt:N2,finishedAt:N2,evidenceRefs:O.array(q_).default([])}).strict(),_r=$_(s.proofBundle).extend({subject:T$,validationPlanRef:T$.optional(),status:R2,verdict:O.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:O.array($r).default([]),verifier:V4.optional(),evidenceRefs:O.array(q_).default([]),residualRisks:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),Jr=$_(s.workRun).extend({objective:O.string().min(1),status:R2,actor:V4,traceId:O.string().min(1).optional(),startedAt:N2,finishedAt:N2,constraints:O.array(O.string().min(1)).default([]),resourceRefs:O.array(T$).default([]),decisions:O.array(QM).default([]),costEstimates:O.array(U9).default([]),evidenceRefs:O.array(q_).default([]),validationPlanRefs:O.array(T$).default([]),proofBundleRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),Wr=O.object({id:O.string().min(1),at:j6,kind:O.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:O.string().min(1),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),costEstimate:U9.optional()}).strict(),Ur=$_(s.agentTrajectory).extend({actor:V4,workRunRef:T$.optional(),events:O.array(Wr).default([]),outcome:O.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:T$.optional()}).strict(),Xr="v1",Gr=O.enum(["library","cli-with-store","service","saas"]),Yr=["local","self-hosted","cloud"],NM=O.enum(Yr),Qr=O.enum(["supported","deferred","unsupported"]),qr=O.enum(["none","local-only","api-key","session","service-token","custom"]),$B=O.object({method:O.enum(["GET","POST","PUT","PATCH","DELETE"]),path:O.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:O.boolean().default(!1),description:O.string().min(1).optional()}).strict(),zr=O.object({id:O.string().min(1),kind:O.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:O.boolean().default(!0),command:O.string().min(1).optional(),evidenceRef:q_.optional(),status:O.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:O.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:O.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),jr=O.object({name:O.string().min(1),status:Qr,bin:O.string().min(1).optional(),mcpBin:O.string().min(1).optional(),authMode:qr,deploymentModes:O.array(NM).min(1),health:$B.optional(),readiness:$B.optional(),version:$B.optional(),apiBasePath:O.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:O.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:O.string().min(1).optional(),readinessGates:O.array(zr).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:O.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:O.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:O.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:O.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),Dr=["local","cloud"],VM=O.enum(Dr);var Or=O.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),Lr=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function Br($){return Lr.map((_)=>`${$}${_}`)}function lE($){return`hasna/oss/${$}/database-url`}var Hr=O.object({mode:VM,envPrefix:O.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:O.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:O.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:O.string().min(1).optional()}).strict(),Nr=O.object({$schema:O.string().min(1).optional(),schema:O.literal(s.serviceContract),name:Or,class:Gr,contractVersion:O.literal(Xr),kitVersion:O.string().min(1),description:O.string().min(1).optional(),bins:O.array(O.string().min(1)).default([]),storage:Hr.optional(),deploymentModes:O.array(NM).default(["local"]),serviceSurfaces:O.array(jr).default([]),metadata:W0.optional()}).strict().superRefine(($,_)=>{let J=new Set(Br($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:O.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:O.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:O.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==lE($.name))_.addIssue({code:O.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${lE($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:O.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:O.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:O.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:O.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:O.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:O.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),S4$=O.object({status:O.enum(["ok","degraded","unavailable"]),version:O.string().min(1),mode:VM}).strict(),Z4$=O.object({ready:O.boolean(),reason:O.string().min(1).optional()}).strict(),v4$=O.object({version:O.string().min(1)}).strict(),Vr=O.enum(["info","notice","breaking","critical"]),Rr=O.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),Kr=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],Fr=O.enum(Kr);var Er=O.enum(["fleet","package","machine"]),RM=$_(s.commsEventEnvelope).extend({type:Rr,severity:Vr,scope:Er,summary:O.string().min(1).optional(),source:V4.optional(),affected_packages:O.array(K$).default([]),affected_machines:O.array(K$).default([]),action_required:O.boolean().default(!1),ack_by:j6.optional(),dedupe_key:K$,resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:O.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),Mr=O.enum(["fleet","package","product","loop-lane","initiative","personal"]),Ar=O.enum(["quiet","work","firehose"]),br=K$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),wr=$_(s.commsChannelMetadata).extend({class:Mr,noise:Ar.optional(),owner:K$.optional(),until:br.optional(),successor:K$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:O.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:O.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),rE={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},gr=$_(s.commsMessageMetadata).extend({tag:Fr,envelope:RM}).strict().superRefine(($,_)=>{let J=rE[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:O.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:O.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(rE))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:O.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var kr={[s.actorRef]:ni,[s.resourceRef]:ci,[s.evidenceRef]:li,[s.workRun]:Jr,[s.decisionEnvelope]:QM,[s.costEstimate]:U9,[s.capabilityCard]:pi,[s.providerLiveModeStandard]:$l,[s.contextPack]:qM,[s.integrationRef]:zM,[s.projectManifest]:Xl,[s.projectPanel]:jM,[s.projectSnapshot]:Bl,[s.renderManifest]:ql,[s.agentTrajectory]:Ur,[s.validationPlan]:Hl,[s.proofBundle]:_r,[s.scaffoldManifest]:Ml,[s.scaffoldInstallRecord]:bl,[s.appCloudManifest]:LM,[s.noCloudEvidencePack]:el,[s.serviceContract]:Nr,[s.commsEventEnvelope]:RM,[s.commsChannelMetadata]:wr,[s.commsMessageMetadata]:gr,[s.app]:Tl,[s.release]:Zl,[s.rolloutRecord]:hl,[s.announcement]:dl,[s.audience]:pl};class KM extends Error{schemaId;issues;constructor($,_){super(`Contract validation failed for ${$}`);this.name="ContractValidationError",this.schemaId=$,this.issues=_}}function FM($,_){let U=kr[$].safeParse(_);if(!U.success)throw new KM($,U.error.issues);return U.data}var y4$={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/hasna/contracts/schema/hasna.service_contract.v1.json",title:"Hasna Service Contract v1",description:"Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Storage runtime enum is local|cloud ONLY per Amendment A1 (PURE REMOTE).",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:s.serviceContract},name:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",description:"Lowercase dashed app short-name, e.g. todos, mailery, loops."},class:{enum:["library","cli-with-store","service","saas"]},contractVersion:{const:"v1"},kitVersion:{type:"string",minLength:1,description:"Version of @hasna/contracts (the contract kit) the repo tracks."},description:{type:"string",minLength:1},bins:{type:"array",items:{type:"string",minLength:1},description:"Declared bins. Allowlisted: , -cli, -mcp, -serve, -worker, -runner, -daemon, -migrate, -doctor."},deploymentModes:{type:"array",items:{enum:["local","self-hosted","cloud"]},description:"Supported deployment modes. local = this machine, self-hosted = Hasna-owned AWS, cloud = multi-tenant SaaS for outside users."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode","deploymentModes"],properties:{name:{type:"string",minLength:1},status:{enum:["supported","deferred","unsupported"]},bin:{type:"string",minLength:1},mcpBin:{type:"string",minLength:1},authMode:{enum:["none","local-only","api-key","session","service-token","custom"]},deploymentModes:{type:"array",items:{enum:["local","self-hosted","cloud"]},minItems:1},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},readiness:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},version:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},apiBasePath:{type:"string",pattern:"^/v[0-9]+$"},openApiPath:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$"},deferReason:{type:"string",minLength:1},readinessGates:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1},kind:{enum:["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]},required:{type:"boolean"},command:{type:"string",minLength:1},evidenceRef:{type:"object"},status:{enum:["pending","passed","failed","blocked","deferred"]},summary:{type:"string",minLength:1}}}}}},description:"Declared HTTP/MCP service surfaces. Supported surfaces name lifecycle endpoints; unsafe or unfinished surfaces use deferred/unsupported with a reason."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["local","cloud"],description:"Runtime storage enum. local|cloud ONLY (Amendment A1: PURE REMOTE)."},envPrefix:{type:"string",pattern:"^HASNA_[A-Z][A-Z0-9]*_$",description:"Primary env prefix, e.g. HASNA_TODOS_."},aliasEnvPrefix:{type:"string",pattern:"^[A-Z][A-Z0-9]*_$",description:"Optional short alias env prefix, e.g. TODOS_."},databaseUrlSecretRef:{type:"string",pattern:"^hasna/oss/[a-z0-9-]+/database-url$",description:"Secret Manager ref for the cloud database URL."},sqlitePath:{type:"string",minLength:1,description:"Local sqlite path (~/.hasna//.db)."}}},metadata:{type:"object"}}};var EM="@hasna/knowledge";function Ir($){if(!Number.isFinite($??0))return 20;return Math.max(1,Math.min(100,Math.trunc($??20)))}function fr($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function X9($,_=180){let J=String($??"").replace(/\s+/g," ").trim();if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-3))}...`}function M_($,_=""){return typeof $==="string"&&$.length>0?$:_}function G9($){return typeof $==="number"&&Number.isFinite($)?$:0}function hW($){if(typeof $!=="string"||$.length===0)return;let _=$.includes("T")?$:`${$.replace(" ","T")}Z`,J=new Date(_);return Number.isNaN(J.valueOf())?void 0:J.toISOString()}function XY($){return t6.safeParse($).success}function a6($,_,J,U,W=[]){return{kind:$,id:_,name:J,uri:U&&XY(U)?U:void 0,externalId:_,sourcePackage:EM,tags:W}}function Cr($){return[...$.items.flatMap((J)=>[J.updated_at,J.created_at]),...$.sources.flatMap((J)=>[J.updated_at,J.created_at]),...$.chunks.map((J)=>J.created_at),...$.wiki_pages.flatMap((J)=>[J.updated_at,J.created_at]),...$.storage_objects.flatMap((J)=>[J.updated_at,J.created_at]),...$.runs.flatMap((J)=>[J.updated_at,J.created_at]),...$.reindex_queue.flatMap((J)=>[J.updated_at,J.created_at]),...$.sync_conflicts.map((J)=>J.created_at),...$.approval_gates.flatMap((J)=>[J.updated_at,J.created_at])].map(hW).filter(Boolean).sort((J,U)=>U.localeCompare(J))[0]}function Pr($){if(!$)return"unknown";let _=Date.now()-new Date($).valueOf();if(!Number.isFinite(_))return"unknown";return _>2592000000?"stale":"fresh"}function Tr($){let _=(J)=>{let U=String(J??"").toLowerCase();return U!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(U)};return $.reindex_queue.filter((J)=>_(J.status)).length+$.sync_conflicts.filter((J)=>_(J.status)).length+$.approval_gates.filter((J)=>_(J.status)).length}function Sr($,_){let J=[];for(let U of $.items.slice(0,_))J.push({id:`item_${U.id}`,title:U.title,summary:X9(U.content_preview),status:U.archived?"archived":"active",priority:"medium",timestamp:hW(U.updated_at??U.created_at),resourceRefs:[a6("knowledge",U.id,U.title,`knowledge://item/${encodeURIComponent(U.id)}`,U.tags)],evidenceRefs:U.url&&XY(U.url)?[{id:`url_${U.id}`,kind:"url",uri:U.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:U.archived,tags:U.tags,url:U.url||void 0}});for(let U of $.sources.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,M_(U.uri,"source")),X=M_(U.title,M_(U.uri,W)),G=M_(U.uri,`knowledge://source/${encodeURIComponent(W)}`);J.push({id:`source_${W}`,title:X,summary:X9(`${G9(U.chunks)} chunk(s), ${G9(U.revisions)} revision(s)`),status:G9(U.chunks)>0?"indexed":"source",priority:"medium",timestamp:hW(U.updated_at??U.created_at),resourceRefs:[a6("document",W,X,G)],evidenceRefs:XY(G)?[{id:`source_${W}`,kind:"url",uri:G,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:U.kind,chunks:G9(U.chunks),revisions:G9(U.revisions)}})}for(let U of $.chunks.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,"chunk"),X=M_(U.source_uri);J.push({id:`chunk_${W}`,title:M_(U.wiki_title,X?`Chunk from ${X}`:`Knowledge chunk ${W}`),summary:X9(U.text_preview),status:"chunk",priority:"low",timestamp:hW(U.created_at),resourceRefs:[a6("context_pack",W,M_(U.wiki_title,W),`knowledge://chunk/${encodeURIComponent(W)}`)],evidenceRefs:X&&XY(X)?[{id:`chunk_source_${W}`,kind:"url",uri:X,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:X||void 0,token_count:U.token_count,ordinal:U.ordinal}})}for(let U of $.sync_conflicts.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,"sync_conflict");J.push({id:`sync_conflict_${W}`,title:`Sync conflict: ${M_(U.entity_kind,"entity")}/${M_(U.entity_id,W)}`,summary:X9(`Status ${M_(U.status,"unknown")}; strategy ${M_(U.resolution_strategy,"none")}.`),status:M_(U.status,"unknown"),priority:"critical",timestamp:hW(U.created_at),resourceRefs:[a6("finding",W,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(W)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:U.local_machine_id,remote_machine_id:U.remote_machine_id}})}for(let U of $.reindex_queue.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,"reindex");J.push({id:`reindex_${W}`,title:`Reindex ${M_(U.kind,"item")}: ${M_(U.target_id,W)}`,summary:X9(U.reason),status:M_(U.status,"unknown"),priority:M_(U.status).toLowerCase()==="failed"?"high":"medium",timestamp:hW(U.updated_at??U.created_at),resourceRefs:[a6("action",W,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(W)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:U.attempts,source_uri:U.source_uri}})}return J.slice(0,_)}async function MM($,_={}){let J=Ir(_.limit),U=new Date().toISOString(),W=fr($),G=await(_.service??$Y({scope:_.scope??"project",cwd:_.cwd})).resolveInventory({limit:J,storePath:_.storePath,includeArchived:_.includeArchived}),Y=Cr(G),Q=Pr(Y),q=G.summary.active_items+G.summary.sources+G.summary.chunks+G.summary.wiki_pages+G.summary.storage_objects,L=Tr(G),N=q===0?"empty":Q==="stale"?"stale":"ready",R=Sr(G,J),B={schema:s.projectPanel,id:`knowledge_panel_${W}`,createdAt:U,projectId:W,provider:{kind:"knowledge",id:`knowledge_${W}`,name:"Knowledge",sourcePackage:EM,externalId:G.home},kind:"knowledge",title:"Knowledge",summary:N==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${G.summary.active_items} active note(s), ${G.summary.sources} source(s), ${G.summary.chunks} chunk(s), and ${G.summary.wiki_pages} wiki page(s).`,state:N,stateReason:N==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:U,freshness:Q,metrics:[{id:"active_items",label:"Active notes",value:G.summary.active_items,status:G.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:G.summary.sources,status:G.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:G.summary.chunks,status:G.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:G.summary.wiki_pages,status:G.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:G.summary.storage_objects,status:G.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:G.summary.vector_entries,status:G.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:L,status:L>0?"warning":"good"}],items:R,actions:[a6("action","knowledge:inventory","Inspect knowledge inventory"),a6("action","knowledge:context-pack","Build cited context pack"),a6("action","knowledge:ingest","Ingest project source")],resourceRefs:[a6("project",W,$,`project://${W}`),a6("knowledge",`home_${W}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(W)}`),a6("artifact",`db_${W}`,"Knowledge database",`knowledge://db/${encodeURIComponent(W)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:J}},metadata:{scope:G.scope,home:G.home,json_store_exists:G.paths.json_store_exists,latest_activity_at:Y}};return FM(s.projectPanel,B)}function AM($){let _=[`${$.title}: ${$.state}`,$.summary??"",...$.metrics.map((J)=>`${J.label}: ${J.value}`)].filter(Boolean);if($.items.length>0){_.push("Items:");for(let J of $.items.slice(0,10))if(_.push(`- ${J.title}${J.status?` [${J.status}]`:""}`),J.summary)_.push(` ${J.summary}`)}return _.join(` -`)}var gM=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"];var Zr=["remote","hybrid","self_hosted"],kM="HASNA_KNOWLEDGE_STORAGE_MODE",IM="KNOWLEDGE_STORAGE_MODE";function bM($){return process.env[$]?.trim()||void 0}function wM($){let _=$?.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return"local";if(_==="cloud")return"cloud";if(_&&Zr.includes(_))return"cloud";return}function vr($={}){let _=b2(O9($.scope,$.cwd).home);return a(_.knowledgeDbPath),{db:m(_.knowledgeDbPath),path:_.knowledgeDbPath,scope:$.scope??"global"}}function fM(){let $=wM(bM(kM))??wM(bM(IM));if($)return $;return"local"}function qB($={}){let _=vr($);try{yr(_.db);let J=_.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all();return{mode:fM(),service:"knowledge",scope:_.scope,databasePath:_.path,tables:gM,sync:J}}finally{_.db.close()}}function yr($){$.exec(` + `,[g]).map(Ub),a={legacy_items:D.items.length,active_items:I.length,archived_items:D.items.length-I.length,schema_version:O.schema_version,sources:O.sources,source_revisions:O.source_revisions,chunks:O.chunks,wiki_pages:O.wiki_pages,citations:O.citations,indexes:O.indexes,runs:O.runs,run_events:O.run_events,storage_objects:O.storage_objects,embeddings:O.embeddings,vector_entries:O.vector_entries,reindex_queue:O.reindex_queue,redaction_findings:O.redaction_findings,audit_events:O.audit_events,approval_gates:O.approval_gates,knowledge_machines:O.knowledge_machines,sync_snapshots:O.sync_snapshots,sync_changes:O.sync_changes,sync_conflicts:O.sync_conflicts,sync_table_clocks:O.sync_table_clocks,sync_imports:O.sync_imports,promotion_candidates:O.promotion_candidates,durable_records:O.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:g,paths:{json_store_path:U,json_store_exists:D.exists,knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:a,legacy_store:{path:U,exists:D.exists,read_error:D.read_error,total_items:D.items.length,active_items:I.length,archived_items:D.items.length-I.length,items_returned:Math.min(j.length,g)},items:j.slice(0,g).map(xG),sources:L,source_revisions:z,chunks:W,wiki_pages:J,indexes:P,storage_objects:S,runs:X,vector_indexes:G,reindex_queue:R,machines:K,sync_conflicts:Q,approval_gates:T,audit_events:q,promotion_candidates:V,durable_records:Z,message:`${D.items.length} item(s), ${O.sources} source(s), ${O.chunks} chunk(s), ${O.wiki_pages} wiki page(s), ${O.storage_objects} artifact(s)`}}finally{A.close()}}assertAppWikiWrite(_){wg({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:_})}async initAppWiki(_={}){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return _W({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async addAppWikiNote(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return $W({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal,title:_.title,content:_.content,tags:_.tags,sourceRefs:_.sourceRefs,path:_.path,metadata:_.metadata})}listAppWikiNotes(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return[];return gW({dbPath:$.knowledgeDbPath,limit:_.limit})}async getAppWikiNote(_,$={}){let g=this.workspace;if(!W_(g.knowledgeDbPath))return null;return DW({dbPath:g.knowledgeDbPath,store:this.artifactStore(),id:_,includeContent:$.includeContent})}async addAppWikiSourceRef(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return UW({scope:this.scope,workspace:$,sourceRef:_.sourceRef,purpose:_.purpose,config:this.config(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async searchAppWiki(_){return this.search(_)}async queryAppWiki(_){return this.retrieveContext(_)}async initWiki(){let _=this.ensureWorkspace();h(_.knowledgeDbPath);let $=await QG(this.artifactStore()),g=v(_.knowledgeDbPath);try{s$(g,$.artifacts),TG(g,$.artifacts)}finally{g.close()}return $}async compileWiki(_={}){let $=this.ensureWorkspace();return XG({..._,dbPath:$.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer(_){let $=this.ensureWorkspace(),g=await this.retrieveContext({query:_.prompt,limit:_.limit,semantic:_.semantic,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake});return RG({dbPath:$.knowledgeDbPath,store:this.artifactStore(),prompt:_.prompt,answer:_.answer,context:g,approveWrite:_.approveWrite})}lintWiki(){let _=this.ensureWorkspace();return GG({dbPath:_.knowledgeDbPath})}async ingestManifest(_){let $=this.ensureWorkspace();return oS({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource(_,$){let g=this.ensureWorkspace();return pU({dbPath:g.knowledgeDbPath,sourceRef:_,purpose:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance(_={}){let $=_.dryRun!==!1,g=$?this.workspace:this.ensureWorkspace();return jG({root:_.root??this.options.cwd??process.cwd(),scope:this.scope,owner:_.owner,dryRun:$,deprecateLegacy:_.deprecateLegacy,includeLegacy:_.includeLegacy,legacyStorePath:g.jsonStorePath,dbPath:g.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:_.maxItems,limit:_.limit})}async resolveSource(_,$={}){let g=this.ensureWorkspace();return lU({dbPath:g.knowledgeDbPath,sourceRef:_,purpose:$.purpose,limit:$.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox(_){let $=this.ensureWorkspace();return RR({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return Ob();return oR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}enqueueReindex(_={}){let $=this.ensureWorkspace();return U3({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async refreshEmbeddings(_={}){let $=this.ensureWorkspace();return pR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}providerStatus(_=process.env){return OW(this.config(),_)}modelRegistry(){return WE(this.config())}embeddingStatus(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return Ab();return SW(_.knowledgeDbPath)}async indexEmbeddings(_={}){let $=this.ensureWorkspace();return sU({..._,dbPath:$.knowledgeDbPath,config:this.config()})}isApiMode(){return Y6()}async fetchCloudItems(){let _=fg();if(!_)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return yU(_)}async semanticSearch(_){let $=this.workspace;if(this.isApiMode()){let g=await this.fetchCloudItems(),U=await j4(g,{..._},["semantic_search_requires_local_catalog"]);return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:U.results}}if(!W_($.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:[]};return _I({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async search(_){let $=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return j4(U,_)}let g=B3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){if(W_(g))return UI({..._,legacyStorePath:g,config:this.config()});return eG(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return DI({..._,dbPath:$.knowledgeDbPath,legacyStorePath:g,config:this.config()})}async retrieveContext(_){let $=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return jI(U,_)}let g=B3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){if(W_(g)){let U=await UI({..._,legacyStorePath:g,config:this.config()});return R0(U,{contextChars:_.contextChars})}return Nb(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return G0({..._,dbPath:$.knowledgeDbPath,legacyStorePath:g,config:this.config()})}async contextPack(_){let $=this.workspace;if(this.isApiMode()){let U=(_.query??_.topic??"").trim();if(U&&_.source!=="loops"&&_.source!=="runs"){let D=await this.fetchCloudItems(),I=await j4(D,{..._,query:U}),j=R0(I,{contextChars:_.contextChars});return cG(_,j,this.safetyPolicy())}return nG(_)}let g=B3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){let U=(_.query??_.topic??"").trim();if(U&&_.source!=="loops"&&_.source!=="runs"&&W_(g)){let D=await UI({..._,query:U,legacyStorePath:g,config:this.config()}),I=R0(D,{contextChars:_.contextChars});return cG(_,I,this.safetyPolicy())}return nG(_)}return mW({..._,dbPath:$.knowledgeDbPath,legacyStorePath:g,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt(_){if(this.isApiMode()){let U=await this.fetchCloudItems();return fW(U,{..._,config:this.config()})}let $=this.ensureWorkspace(),g=_.legacyStorePath??$.jsonStorePath;if(!_.legacyStorePath)Hg(g);return vW({..._,dbPath:$.knowledgeDbPath,legacyStorePath:g,config:this.config()})}async webSearch(_){let $=this.ensureWorkspace();return AG({..._,dbPath:$.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology(_={}){let $=this.workspace;return CR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}async machinePreflight(_={}){let $=this.workspace;return fR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}syncStatus(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return Lb({scope:this.scope,workspaceHome:_.home});return zX({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home})}async syncDoctor(_={}){let $=this.ensureWorkspace();h($.knowledgeDbPath);let g=this.syncStatus(),U=this.storageContract(),D=this.validateStorage(),I=Jb($.knowledgeDbPath,U),j=_.machine?.trim()||null,N=_.peerWorkspace?.trim()||null,O=[],A=null,L=null;if(j&&!lG(j)){let S=await sP({machineId:j,includeTailscale:_.includeTailscale});A=q3(S),O.push(...S.warnings)}if(j||N){let S=await ij({machineId:j??T3($),peerWorkspace:N,includeTailscale:_.includeTailscale});if(j&&!N&&(A?.source==="raw"||!S.ok||!S.project_root)){let X=rG($.knowledgeDbPath,j);if(X){if(A?.source==="raw"&&X.ssh_target)A=q3(vG(X,j,{target:A.target,route:A.route,targetKind:A.target_kind,confidence:A.confidence,source:A.source,adapter:A.adapter,evidence:A.evidence,cacheability:A.cacheability,warnings:[]}));if(!S.ok||!S.project_root){let G=fG(X,j,S);if(G)L=OU(G,G.project_root),O.push(...G.warnings)}}}L=S.ok&&S.project_root?OU(S,S.project_root):L??{...OU(S,N??""),project_root:S.project_root??N??""},O.push(...S.warnings)}if(!D.ok)O.push(...D.errors.map((S)=>`storage:${S}`));let z=_b($.knowledgeDbPath,L);if(!z.ok)O.push("open_files_boundary_raw_payload_sentinels");if(!I.ok)O.push(...I.warnings);let W=L?.diagnostics.filter((S)=>S.severity==="fail")??[],J=D.ok&&I.ok&&z.ok&&W.length===0&&(L?.project_root!==""||!L),P=zb({scope:this.scope,machine:j,peerWorkspace:N,tables:_.tables,resolvedWorkspace:L,openConflicts:g.conflicts.open});return{ok:J,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:$.home,database:{sqlite_schema_version:g.sqlite_schema_version,table_counts:g.table_counts},storage:{contract:U,validation:D,artifact_manifest:I},sync:{machines:g.machines.total,snapshots:g.snapshots.total,clocks:g.clocks.total,imports:g.imports.total,open_conflicts:g.conflicts.open,table_clocks:g.clocks.rows},open_files:z,resolved_route:A,resolved_workspace:L,recommended_commands:P,warnings:[...new Set(O)],message:J?`Sync readiness ok: ${g.clocks.total} table clock(s), ${g.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(O)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys(_={}){let $=this.ensureWorkspace();h($.knowledgeDbPath);let g=this.storageContract(),U=Z3(g),D=Pb($.knowledgeDbPath,g),I=_.dryRun===!0||_.approveWrite!==!0;if(D.length===0)return{ok:!0,dry_run:I,approval_required:!1,storage_type:g.storage_type,storage_prefix:U,candidates:D,repaired:0,audit_event_id:null,message:"No legacy S3 artifact manifest keys found"};if(_.dryRun===!0)return{ok:!0,dry_run:!0,approval_required:!1,storage_type:g.storage_type,storage_prefix:U,candidates:D,repaired:0,audit_event_id:null,message:`Would repair ${D.length} legacy S3 artifact manifest key(s)`};if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:g.storage_type,storage_prefix:U,candidates:D,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let j=v($.knowledgeDbPath);try{let N=new Date().toISOString();j.transaction((L)=>{let z=j.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),W=j.query("SELECT id, metadata_json FROM storage_objects").all(),J=new Map(W.map((P)=>[P.id,c4(P.metadata_json)]));for(let P of L){let S=J.get(P.id)??{};S.key=P.repaired_key,z.run(JSON.stringify(S),N,P.id)}})(D);let A=X_(j,{event_type:"artifact_manifest_key_repair",action:"storage.artifact_manifest.repair_keys",target_uri:`knowledge-storage://${$.home}/storage_objects`,decision:"allow",metadata:{approved_by:_.approvedBy,repaired:D.length,storage_type:g.storage_type,storage_prefix:U,artifact_uris:D.map((L)=>L.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:g.storage_type,storage_prefix:U,candidates:D,repaired:D.length,audit_event_id:A,message:`Repaired ${D.length} legacy S3 artifact manifest key(s)`}}finally{j.close()}}async createSyncSnapshot(_={}){let $=this.ensureWorkspace(),g=await this.machineTopology({includeTailscale:_.includeTailscale!==!1});return PX({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),topology:g,machineId:_.machineId})}syncConflicts(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return[];return SX($.knowledgeDbPath,_)}syncConflict(_){let $=this.ensureWorkspace(),g=WI($.knowledgeDbPath,_);if(!g)throw Error(`Sync conflict not found: ${_}`);return g}proposeSyncConflictResolution(_){let $=this.ensureWorkspace();return lg($.knowledgeDbPath,_)}async proposeSyncConflictResolutionWithAi(_){let $=this.ensureWorkspace();return WR({dbPath:$.knowledgeDbPath,id:_.id,config:this.config(),modelRef:_.modelRef,fake:_.fake,env:_.env})}resolveSyncConflict(_){let $=this.ensureWorkspace(),g=lg($.knowledgeDbPath,_.id);if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,approval_required:!0,conflict:g.conflict,proposal:g,message:"Sync conflict resolution requires --approve-write and --approved-by "};let U=RX($.knowledgeDbPath,{id:_.id,strategy:_.strategy??g.proposed_strategy,approvedBy:_.approvedBy,proposedPatchUri:_.proposedPatchUri}),D=v($.knowledgeDbPath);try{let I=X_(D,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${_.id}`,decision:"allow",metadata:{conflict_id:_.id,entity_kind:U.entity_kind,entity_id:U.entity_id,strategy:U.resolution_strategy,approved_by:U.approved_by,proposed_patch_uri:U.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:U,audit_event_id:I,message:`Resolved sync conflict ${_.id}`}}finally{D.close()}}syncMachines(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return[];return vE(_.knowledgeDbPath)}exportSyncBundle(_={}){let $=this.ensureWorkspace();return this.assertStorageValid("sync export"),h($.knowledgeDbPath),ig({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.recordClocks!==!1})}async importSyncBundle(_){let $=this.ensureWorkspace();return this.assertStorageValid("sync import"),h($.knowledgeDbPath),SI({targetDbPath:$.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:$.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:_.bundle,direction:_.direction??"import",dryRun:_.dryRun,localMachineId:_.machineId??null})}async syncRemotePeer(_){let $=_.direction??"both",g=_.dryRun===!0,U=this.ensureWorkspace();h(U.knowledgeDbPath);let D=_.tables?.length?["--tables",_.tables.join(",")]:[],I=_.includeArtifactContent===!1?["--no-artifact-content"]:[],j=["--scope",this.scope,"--json"],N=await sP({machineId:_.machine,includeTailscale:_.includeTailscale}),O=await ij({machineId:_.machine,peerWorkspace:_.peerWorkspace,includeTailscale:_.includeTailscale});if(!_.peerWorkspace&&N.source==="raw"||!O.ok||!O.project_root){let J=rG(U.knowledgeDbPath,_.machine);if(J){if(!_.peerWorkspace&&N.source==="raw"&&J.ssh_target)N=vG(J,_.machine,N);if(!O.ok||!O.project_root){let P=fG(J,_.machine,O);if(P)O=P}}}if(!O.ok||!O.project_root)throw Error([`Unable to resolve peer workspace for ${_.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",O.warnings.length?`Warnings: ${O.warnings.join(", ")}`:null].filter(Boolean).join(" "));let A=O.project_root,L={ok:!0,dry_run:g,direction:$,transport:"ssh",machine:_.machine,resolved_machine:N.target,resolved_route:q3(N),resolved_workspace:OU(O,O.project_root),peer_workspace:A,message:""},z=!1,W=()=>{if(g||z)return;AX(U.knowledgeDbPath,{machineId:_.machine,route:N,workspace:O}),z=!0};if($==="pull"||$==="both"){let J=CG(A,["sync","export",...j,...D,...I]),P=dG(_.machine,J,void 0,N),S=mG(_.machine,"sync export",P);Wb(_.machine,S),L.pull=await this.importSyncBundle({bundle:S,dryRun:g,direction:"pull",machineId:_.machineId??null})}if($==="push"||$==="both"){W();let J=this.exportSyncBundle({machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:!g}),P=CG(A,["sync","import",...j,...g?["--dry-run"]:[]]),S=mG(_.machine,"sync import",dG(_.machine,P,JSON.stringify(J),N));Xb(_.machine,S),L.push=S}return L.ok=(L.pull?.ok??!0)&&(L.push?.ok??!0),W(),L.message=[wG(L.resolved_workspace),L.pull?`pull: ${L.pull.message}`:null,L.push?`push: ${L.push.message}`:null].filter(Boolean).join("; "),L}async syncPeer(_){let $=_.direction??"both",g=this.ensureWorkspace();h(g.knowledgeDbPath);let U=iG(_.peerWorkspace),D=iZ(U);h(D.knowledgeDbPath);let I=MN(D.configPath),j=dU(I,D,this.scope),N=gE(I,D),O=_.machineId??T3(g),A=T3(D),L=await ij({machineId:_.machineId??A,peerWorkspace:U,includeTailscale:!1}),z=()=>ig({dbPath:g.knowledgeDbPath,scope:this.scope,workspaceHome:g.home,storage:this.storageContract(),machineId:O,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),W=()=>ig({dbPath:D.knowledgeDbPath,scope:this.scope,workspaceHome:D.home,storage:j,machineId:A,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),J={ok:!0,dry_run:_.dryRun===!0,direction:$,resolved_workspace:OU(L,L.project_root??U),message:""};if($==="pull"||$==="both")J.pull=await SI({targetDbPath:g.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:g.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:W(),targetBundle:z(),direction:"pull",dryRun:_.dryRun,localMachineId:O});if($==="push"||$==="both")J.push=await SI({targetDbPath:D.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:D.home,targetStorage:j,targetStore:N,bundle:z(),targetBundle:W(),direction:"push",dryRun:_.dryRun,localMachineId:A});return J.ok=(J.pull?.ok??!0)&&(J.push?.ok??!0),J.message=[wG(J.resolved_workspace),J.pull?`pull: ${J.pull.message}`:null,J.push?`push: ${J.push.message}`:null].filter(Boolean).join("; "),J}}function UN(_={}){return new aG(_)}import{createHash as sG}from"crypto";var Gb=Object.defineProperty,Yb=(_)=>_;function Qb(_,$){this[_]=Yb.bind(null,$)}var Tb=(_,$)=>{for(var g in $)Gb(_,g,{get:$[g],enumerable:!0,configurable:!0,set:Qb.bind($,g)})},E={};Tb(E,{void:()=>jH,util:()=>U_,unknown:()=>UH,union:()=>AH,undefined:()=>$H,tuple:()=>PH,transformer:()=>g9,symbol:()=>_H,string:()=>W9,strictObject:()=>OH,setErrorMap:()=>Kb,set:()=>WH,record:()=>zH,quotelessJson:()=>qb,promise:()=>TH,preprocess:()=>KH,pipeline:()=>VH,ostring:()=>FH,optional:()=>qH,onumber:()=>MH,oboolean:()=>ZH,objectUtil:()=>k3,object:()=>EH,number:()=>X9,nullable:()=>BH,null:()=>gH,never:()=>IH,nativeEnum:()=>QH,nan:()=>eb,map:()=>SH,makeIssue:()=>NN,literal:()=>GH,lazy:()=>RH,late:()=>ob,isValid:()=>n4,isDirty:()=>r3,isAsync:()=>PU,isAborted:()=>C3,intersection:()=>JH,instanceof:()=>pb,getParsedType:()=>P6,getErrorMap:()=>jN,function:()=>XH,enum:()=>YH,effect:()=>g9,discriminatedUnion:()=>LH,defaultErrorMap:()=>Eg,datetimeRegex:()=>P9,date:()=>sb,custom:()=>S9,coerce:()=>bH,boolean:()=>R9,bigint:()=>ab,array:()=>NH,any:()=>DH,addIssueToContext:()=>u,ZodVoid:()=>SU,ZodUnknown:()=>m6,ZodUnion:()=>Jg,ZodUndefined:()=>Ag,ZodType:()=>__,ZodTuple:()=>d$,ZodTransformer:()=>R$,ZodSymbol:()=>zU,ZodString:()=>F$,ZodSet:()=>i4,ZodSchema:()=>__,ZodRecord:()=>WU,ZodReadonly:()=>Gg,ZodPromise:()=>l4,ZodPipeline:()=>GU,ZodParsedType:()=>y,ZodOptional:()=>Z$,ZodObject:()=>b_,ZodNumber:()=>i6,ZodNullable:()=>z6,ZodNull:()=>Lg,ZodNever:()=>n$,ZodNativeEnum:()=>Wg,ZodNaN:()=>RU,ZodMap:()=>XU,ZodLiteral:()=>Sg,ZodLazy:()=>zg,ZodIssueCode:()=>k,ZodIntersection:()=>Pg,ZodFunction:()=>jg,ZodFirstPartyTypeKind:()=>i,ZodError:()=>O$,ZodEnum:()=>t6,ZodEffects:()=>R$,ZodDiscriminatedUnion:()=>AN,ZodDefault:()=>Xg,ZodDate:()=>d4,ZodCatch:()=>Rg,ZodBranded:()=>LN,ZodBoolean:()=>Og,ZodBigInt:()=>l6,ZodArray:()=>M$,ZodAny:()=>m4,Schema:()=>__,ParseStatus:()=>m_,OK:()=>a_,NEVER:()=>HH,INVALID:()=>m,EMPTY_PATH:()=>Vb,DIRTY:()=>Ig,BRAND:()=>tb});var U_;(function(_){_.assertEqual=(D)=>{};function $(D){}_.assertIs=$;function g(D){throw Error()}_.assertNever=g,_.arrayToEnum=(D)=>{let I={};for(let j of D)I[j]=j;return I},_.getValidEnumValues=(D)=>{let I=_.objectKeys(D).filter((N)=>typeof D[D[N]]!=="number"),j={};for(let N of I)j[N]=D[N];return _.objectValues(j)},_.objectValues=(D)=>{return _.objectKeys(D).map(function(I){return D[I]})},_.objectKeys=typeof Object.keys==="function"?(D)=>Object.keys(D):(D)=>{let I=[];for(let j in D)if(Object.prototype.hasOwnProperty.call(D,j))I.push(j);return I},_.find=(D,I)=>{for(let j of D)if(I(j))return j;return},_.isInteger=typeof Number.isInteger==="function"?(D)=>Number.isInteger(D):(D)=>typeof D==="number"&&Number.isFinite(D)&&Math.floor(D)===D;function U(D,I=" | "){return D.map((j)=>typeof j==="string"?`'${j}'`:j).join(I)}_.joinValues=U,_.jsonStringifyReplacer=(D,I)=>{if(typeof I==="bigint")return I.toString();return I}})(U_||(U_={}));var k3;(function(_){_.mergeShapes=($,g)=>{return{...$,...g}}})(k3||(k3={}));var y=U_.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),P6=(_)=>{switch(typeof _){case"undefined":return y.undefined;case"string":return y.string;case"number":return Number.isNaN(_)?y.nan:y.number;case"boolean":return y.boolean;case"function":return y.function;case"bigint":return y.bigint;case"symbol":return y.symbol;case"object":if(Array.isArray(_))return y.array;if(_===null)return y.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return y.promise;if(typeof Map<"u"&&_ instanceof Map)return y.map;if(typeof Set<"u"&&_ instanceof Set)return y.set;if(typeof Date<"u"&&_ instanceof Date)return y.date;return y.object;default:return y.unknown}},k=U_.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),qb=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class O$ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=(g)=>{this.issues=[...this.issues,g]},this.addIssues=(g=[])=>{this.issues=[...this.issues,...g]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=_}format(_){let $=_||function(D){return D.message},g={_errors:[]},U=(D)=>{for(let I of D.issues)if(I.code==="invalid_union")I.unionErrors.map(U);else if(I.code==="invalid_return_type")U(I.returnTypeError);else if(I.code==="invalid_arguments")U(I.argumentsError);else if(I.path.length===0)g._errors.push($(I));else{let j=g,N=0;while(N$.message){let $={},g=[];for(let U of this.issues)if(U.path.length>0){let D=U.path[0];$[D]=$[D]||[],$[D].push(_(U))}else g.push(_(U));return{formErrors:g,fieldErrors:$}}get formErrors(){return this.flatten()}}O$.create=(_)=>{return new O$(_)};var Bb=(_,$)=>{let g;switch(_.code){case k.invalid_type:if(_.received===y.undefined)g="Required";else g=`Expected ${_.expected}, received ${_.received}`;break;case k.invalid_literal:g=`Invalid literal value, expected ${JSON.stringify(_.expected,U_.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:g=`Unrecognized key(s) in object: ${U_.joinValues(_.keys,", ")}`;break;case k.invalid_union:g="Invalid input";break;case k.invalid_union_discriminator:g=`Invalid discriminator value. Expected ${U_.joinValues(_.options)}`;break;case k.invalid_enum_value:g=`Invalid enum value. Expected ${U_.joinValues(_.options)}, received '${_.received}'`;break;case k.invalid_arguments:g="Invalid function arguments";break;case k.invalid_return_type:g="Invalid function return type";break;case k.invalid_date:g="Invalid date";break;case k.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if(g=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")g=`${g} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)g=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)g=`Invalid input: must end with "${_.validation.endsWith}"`;else U_.assertNever(_.validation);else if(_.validation!=="regex")g=`Invalid ${_.validation}`;else g="Invalid";break;case k.too_small:if(_.type==="array")g=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")g=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")g=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")g=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")g=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else g="Invalid input";break;case k.too_big:if(_.type==="array")g=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")g=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")g=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")g=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")g=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else g="Invalid input";break;case k.custom:g="Invalid input";break;case k.invalid_intersection_types:g="Intersection results could not be merged";break;case k.not_multiple_of:g=`Number must be a multiple of ${_.multipleOf}`;break;case k.not_finite:g="Number must be finite";break;default:g=$.defaultError,U_.assertNever(_)}return{message:g}},Eg=Bb,A9=Eg;function Kb(_){A9=_}function jN(){return A9}var NN=(_)=>{let{data:$,path:g,errorMaps:U,issueData:D}=_,I=[...g,...D.path||[]],j={...D,path:I};if(D.message!==void 0)return{...D,path:I,message:D.message};let N="",O=U.filter((A)=>!!A).slice().reverse();for(let A of O)N=A(j,{data:$,defaultError:N}).message;return{...D,path:I,message:N}},Vb=[];function u(_,$){let g=jN(),U=NN({issueData:$,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,g,g===Eg?void 0:Eg].filter((D)=>!!D)});_.common.issues.push(U)}class m_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,$){let g=[];for(let U of $){if(U.status==="aborted")return m;if(U.status==="dirty")_.dirty();g.push(U.value)}return{status:_.value,value:g}}static async mergeObjectAsync(_,$){let g=[];for(let U of $){let D=await U.key,I=await U.value;g.push({key:D,value:I})}return m_.mergeObjectSync(_,g)}static mergeObjectSync(_,$){let g={};for(let U of $){let{key:D,value:I}=U;if(D.status==="aborted")return m;if(I.status==="aborted")return m;if(D.status==="dirty")_.dirty();if(I.status==="dirty")_.dirty();if(D.value!=="__proto__"&&(typeof I.value<"u"||U.alwaysSet))g[D.value]=I.value}return{status:_.value,value:g}}}var m=Object.freeze({status:"aborted"}),Ig=(_)=>({status:"dirty",value:_}),a_=(_)=>({status:"valid",value:_}),C3=(_)=>_.status==="aborted",r3=(_)=>_.status==="dirty",n4=(_)=>_.status==="valid",PU=(_)=>typeof Promise<"u"&&_ instanceof Promise,n;(function(_){_.errToObj=($)=>typeof $==="string"?{message:$}:$||{},_.toString=($)=>typeof $==="string"?$:$?.message})(n||(n={}));class b${constructor(_,$,g,U){this._cachedPath=[],this.parent=_,this.data=$,this._path=g,this._key=U}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var _9=(_,$)=>{if(n4($))return{success:!0,data:$.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let g=new O$(_.common.issues);return this._error=g,this._error}}}};function e(_){if(!_)return{};let{errorMap:$,invalid_type_error:g,required_error:U,description:D}=_;if($&&(g||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:D};return{errorMap:(j,N)=>{let{message:O}=_;if(j.code==="invalid_enum_value")return{message:O??N.defaultError};if(typeof N.data>"u")return{message:O??U??N.defaultError};if(j.code!=="invalid_type")return{message:N.defaultError};return{message:O??g??N.defaultError}},description:D}}class __{get description(){return this._def.description}_getType(_){return P6(_.data)}_getOrReturnCtx(_,$){return $||{common:_.parent.common,data:_.data,parsedType:P6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new m_,ctx:{common:_.parent.common,data:_.data,parsedType:P6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let $=this._parse(_);if(PU($))throw Error("Synchronous parse encountered promise.");return $}_parseAsync(_){let $=this._parse(_);return Promise.resolve($)}parse(_,$){let g=this.safeParse(_,$);if(g.success)return g.data;throw g.error}safeParse(_,$){let g={common:{issues:[],async:$?.async??!1,contextualErrorMap:$?.errorMap},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)},U=this._parseSync({data:_,path:g.path,parent:g});return _9(g,U)}"~validate"(_){let $={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)};if(!this["~standard"].async)try{let g=this._parseSync({data:_,path:[],parent:$});return n4(g)?{value:g.value}:{issues:$.common.issues}}catch(g){if(g?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;$.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:$}).then((g)=>n4(g)?{value:g.value}:{issues:$.common.issues})}async parseAsync(_,$){let g=await this.safeParseAsync(_,$);if(g.success)return g.data;throw g.error}async safeParseAsync(_,$){let g={common:{issues:[],contextualErrorMap:$?.errorMap,async:!0},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)},U=this._parse({data:_,path:g.path,parent:g}),D=await(PU(U)?U:Promise.resolve(U));return _9(g,D)}refine(_,$){let g=(U)=>{if(typeof $==="string"||typeof $>"u")return{message:$};else if(typeof $==="function")return $(U);else return $};return this._refinement((U,D)=>{let I=_(U),j=()=>D.addIssue({code:k.custom,...g(U)});if(typeof Promise<"u"&&I instanceof Promise)return I.then((N)=>{if(!N)return j(),!1;else return!0});if(!I)return j(),!1;else return!0})}refinement(_,$){return this._refinement((g,U)=>{if(!_(g))return U.addIssue(typeof $==="function"?$(g,U):$),!1;else return!0})}_refinement(_){return new R$({schema:this,typeName:i.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:($)=>this["~validate"]($)}}optional(){return Z$.create(this,this._def)}nullable(){return z6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return M$.create(this)}promise(){return l4.create(this,this._def)}or(_){return Jg.create([this,_],this._def)}and(_){return Pg.create(this,_,this._def)}transform(_){return new R$({...e(this._def),schema:this,typeName:i.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let $=typeof _==="function"?_:()=>_;return new Xg({...e(this._def),innerType:this,defaultValue:$,typeName:i.ZodDefault})}brand(){return new LN({typeName:i.ZodBranded,type:this,...e(this._def)})}catch(_){let $=typeof _==="function"?_:()=>_;return new Rg({...e(this._def),innerType:this,catchValue:$,typeName:i.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return GU.create(this,_)}readonly(){return Gg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Fb=/^c[^\s-]{8,}$/i,Mb=/^[0-9a-z]+$/,Zb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Hb=/^[a-z0-9_-]{21}$/i,kb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cb=/^[-+]?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)?)??$/,rb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",b3,fb=/^(?:(?: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])$/,wb=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ub=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,xb=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,yb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,L9="((\\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])))",cb=new RegExp(`^${L9}$`);function J9(_){let $="[0-5]\\d";if(_.precision)$=`${$}\\.\\d{${_.precision}}`;else if(_.precision==null)$=`${$}(\\.\\d+)?`;let g=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${g}`}function nb(_){return new RegExp(`^${J9(_)}$`)}function P9(_){let $=`${L9}T${J9(_)}`,g=[];if(g.push(_.local?"Z?":"Z"),_.offset)g.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${g.join("|")})`,new RegExp(`^${$}$`)}function db(_,$){if(($==="v4"||!$)&&fb.test(_))return!0;if(($==="v6"||!$)&&ub.test(_))return!0;return!1}function mb(_,$){if(!kb.test(_))return!1;try{let[g]=_.split(".");if(!g)return!1;let U=g.replace(/-/g,"+").replace(/_/g,"/").padEnd(g.length+(4-g.length%4)%4,"="),D=JSON.parse(atob(U));if(typeof D!=="object"||D===null)return!1;if("typ"in D&&D?.typ!=="JWT")return!1;if(!D.alg)return!1;if($&&D.alg!==$)return!1;return!0}catch{return!1}}function ib(_,$){if(($==="v4"||!$)&&wb.test(_))return!0;if(($==="v6"||!$)&&xb.test(_))return!0;return!1}class F$ extends __{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==y.string){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.string,received:D.parsedType}),m}let g=new m_,U=void 0;for(let D of this._def.checks)if(D.kind==="min"){if(_.data.lengthD.value)U=this._getOrReturnCtx(_,U),u(U,{code:k.too_big,maximum:D.value,type:"string",inclusive:!0,exact:!1,message:D.message}),g.dirty()}else if(D.kind==="length"){let I=_.data.length>D.value,j=_.data.length_.test(U),{validation:$,code:k.invalid_string,...n.errToObj(g)})}_addCheck(_){return new F$({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...n.errToObj(_)})}url(_){return this._addCheck({kind:"url",...n.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...n.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...n.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...n.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...n.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...n.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...n.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...n.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...n.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...n.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...n.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...n.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...n.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...n.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...n.errToObj(_)})}regex(_,$){return this._addCheck({kind:"regex",regex:_,...n.errToObj($)})}includes(_,$){return this._addCheck({kind:"includes",value:_,position:$?.position,...n.errToObj($?.message)})}startsWith(_,$){return this._addCheck({kind:"startsWith",value:_,...n.errToObj($)})}endsWith(_,$){return this._addCheck({kind:"endsWith",value:_,...n.errToObj($)})}min(_,$){return this._addCheck({kind:"min",value:_,...n.errToObj($)})}max(_,$){return this._addCheck({kind:"max",value:_,...n.errToObj($)})}length(_,$){return this._addCheck({kind:"length",value:_,...n.errToObj($)})}nonempty(_){return this.min(1,n.errToObj(_))}trim(){return new F$({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new F$({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new F$({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxLength(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}}F$.create=(_)=>{return new F$({checks:[],typeName:i.ZodString,coerce:_?.coerce??!1,...e(_)})};function lb(_,$){let g=(_.toString().split(".")[1]||"").length,U=($.toString().split(".")[1]||"").length,D=g>U?g:U,I=Number.parseInt(_.toFixed(D).replace(".","")),j=Number.parseInt($.toFixed(D).replace(".",""));return I%j/10**D}class i6 extends __{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==y.number){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.number,received:D.parsedType}),m}let g=void 0,U=new m_;for(let D of this._def.checks)if(D.kind==="int"){if(!U_.isInteger(_.data))g=this._getOrReturnCtx(_,g),u(g,{code:k.invalid_type,expected:"integer",received:"float",message:D.message}),U.dirty()}else if(D.kind==="min"){if(D.inclusive?_.dataD.value:_.data>=D.value)g=this._getOrReturnCtx(_,g),u(g,{code:k.too_big,maximum:D.value,type:"number",inclusive:D.inclusive,exact:!1,message:D.message}),U.dirty()}else if(D.kind==="multipleOf"){if(lb(_.data,D.value)!==0)g=this._getOrReturnCtx(_,g),u(g,{code:k.not_multiple_of,multipleOf:D.value,message:D.message}),U.dirty()}else if(D.kind==="finite"){if(!Number.isFinite(_.data))g=this._getOrReturnCtx(_,g),u(g,{code:k.not_finite,message:D.message}),U.dirty()}else U_.assertNever(D);return{status:U.value,value:_.data}}gte(_,$){return this.setLimit("min",_,!0,n.toString($))}gt(_,$){return this.setLimit("min",_,!1,n.toString($))}lte(_,$){return this.setLimit("max",_,!0,n.toString($))}lt(_,$){return this.setLimit("max",_,!1,n.toString($))}setLimit(_,$,g,U){return new i6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:g,message:n.toString(U)}]})}_addCheck(_){return new i6({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:n.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:n.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:n.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:n.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:n.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:n.toString($)})}finite(_){return this._addCheck({kind:"finite",message:n.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:n.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:n.toString(_)})}get minValue(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxValue(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&U_.isInteger(_.value))}get isFinite(){let _=null,$=null;for(let g of this._def.checks)if(g.kind==="finite"||g.kind==="int"||g.kind==="multipleOf")return!0;else if(g.kind==="min"){if($===null||g.value>$)$=g.value}else if(g.kind==="max"){if(_===null||g.value<_)_=g.value}return Number.isFinite($)&&Number.isFinite(_)}}i6.create=(_)=>{return new i6({checks:[],typeName:i.ZodNumber,coerce:_?.coerce||!1,...e(_)})};class l6 extends __{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==y.bigint)return this._getInvalidInput(_);let g=void 0,U=new m_;for(let D of this._def.checks)if(D.kind==="min"){if(D.inclusive?_.dataD.value:_.data>=D.value)g=this._getOrReturnCtx(_,g),u(g,{code:k.too_big,type:"bigint",maximum:D.value,inclusive:D.inclusive,message:D.message}),U.dirty()}else if(D.kind==="multipleOf"){if(_.data%D.value!==BigInt(0))g=this._getOrReturnCtx(_,g),u(g,{code:k.not_multiple_of,multipleOf:D.value,message:D.message}),U.dirty()}else U_.assertNever(D);return{status:U.value,value:_.data}}_getInvalidInput(_){let $=this._getOrReturnCtx(_);return u($,{code:k.invalid_type,expected:y.bigint,received:$.parsedType}),m}gte(_,$){return this.setLimit("min",_,!0,n.toString($))}gt(_,$){return this.setLimit("min",_,!1,n.toString($))}lte(_,$){return this.setLimit("max",_,!0,n.toString($))}lt(_,$){return this.setLimit("max",_,!1,n.toString($))}setLimit(_,$,g,U){return new l6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:g,message:n.toString(U)}]})}_addCheck(_){return new l6({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:n.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:n.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:n.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:n.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:n.toString($)})}get minValue(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxValue(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}}l6.create=(_)=>{return new l6({checks:[],typeName:i.ZodBigInt,coerce:_?.coerce??!1,...e(_)})};class Og extends __{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==y.boolean){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.boolean,received:g.parsedType}),m}return a_(_.data)}}Og.create=(_)=>{return new Og({typeName:i.ZodBoolean,coerce:_?.coerce||!1,...e(_)})};class d4 extends __{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==y.date){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.date,received:D.parsedType}),m}if(Number.isNaN(_.data.getTime())){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_date}),m}let g=new m_,U=void 0;for(let D of this._def.checks)if(D.kind==="min"){if(_.data.getTime()D.value)U=this._getOrReturnCtx(_,U),u(U,{code:k.too_big,message:D.message,inclusive:!0,exact:!1,maximum:D.value,type:"date"}),g.dirty()}else U_.assertNever(D);return{status:g.value,value:new Date(_.data.getTime())}}_addCheck(_){return new d4({...this._def,checks:[...this._def.checks,_]})}min(_,$){return this._addCheck({kind:"min",value:_.getTime(),message:n.toString($)})}max(_,$){return this._addCheck({kind:"max",value:_.getTime(),message:n.toString($)})}get minDate(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _!=null?new Date(_):null}}d4.create=(_)=>{return new d4({checks:[],coerce:_?.coerce||!1,typeName:i.ZodDate,...e(_)})};class zU extends __{_parse(_){if(this._getType(_)!==y.symbol){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.symbol,received:g.parsedType}),m}return a_(_.data)}}zU.create=(_)=>{return new zU({typeName:i.ZodSymbol,...e(_)})};class Ag extends __{_parse(_){if(this._getType(_)!==y.undefined){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.undefined,received:g.parsedType}),m}return a_(_.data)}}Ag.create=(_)=>{return new Ag({typeName:i.ZodUndefined,...e(_)})};class Lg extends __{_parse(_){if(this._getType(_)!==y.null){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.null,received:g.parsedType}),m}return a_(_.data)}}Lg.create=(_)=>{return new Lg({typeName:i.ZodNull,...e(_)})};class m4 extends __{constructor(){super(...arguments);this._any=!0}_parse(_){return a_(_.data)}}m4.create=(_)=>{return new m4({typeName:i.ZodAny,...e(_)})};class m6 extends __{constructor(){super(...arguments);this._unknown=!0}_parse(_){return a_(_.data)}}m6.create=(_)=>{return new m6({typeName:i.ZodUnknown,...e(_)})};class n$ extends __{_parse(_){let $=this._getOrReturnCtx(_);return u($,{code:k.invalid_type,expected:y.never,received:$.parsedType}),m}}n$.create=(_)=>{return new n$({typeName:i.ZodNever,...e(_)})};class SU extends __{_parse(_){if(this._getType(_)!==y.undefined){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.void,received:g.parsedType}),m}return a_(_.data)}}SU.create=(_)=>{return new SU({typeName:i.ZodVoid,...e(_)})};class M$ extends __{_parse(_){let{ctx:$,status:g}=this._processInputParams(_),U=this._def;if($.parsedType!==y.array)return u($,{code:k.invalid_type,expected:y.array,received:$.parsedType}),m;if(U.exactLength!==null){let I=$.data.length>U.exactLength.value,j=$.data.lengthU.maxLength.value)u($,{code:k.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),g.dirty()}if($.common.async)return Promise.all([...$.data].map((I,j)=>{return U.type._parseAsync(new b$($,I,$.path,j))})).then((I)=>{return m_.mergeArray(g,I)});let D=[...$.data].map((I,j)=>{return U.type._parseSync(new b$($,I,$.path,j))});return m_.mergeArray(g,D)}get element(){return this._def.type}min(_,$){return new M$({...this._def,minLength:{value:_,message:n.toString($)}})}max(_,$){return new M$({...this._def,maxLength:{value:_,message:n.toString($)}})}length(_,$){return new M$({...this._def,exactLength:{value:_,message:n.toString($)}})}nonempty(_){return this.min(1,_)}}M$.create=(_,$)=>{return new M$({type:_,minLength:null,maxLength:null,exactLength:null,typeName:i.ZodArray,...e($)})};function Dg(_){if(_ instanceof b_){let $={};for(let g in _.shape){let U=_.shape[g];$[g]=Z$.create(Dg(U))}return new b_({..._._def,shape:()=>$})}else if(_ instanceof M$)return new M$({..._._def,type:Dg(_.element)});else if(_ instanceof Z$)return Z$.create(Dg(_.unwrap()));else if(_ instanceof z6)return z6.create(Dg(_.unwrap()));else if(_ instanceof d$)return d$.create(_.items.map(($)=>Dg($)));else return _}class b_ extends __{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),$=U_.objectKeys(_);return this._cached={shape:_,keys:$},this._cached}_parse(_){if(this._getType(_)!==y.object){let O=this._getOrReturnCtx(_);return u(O,{code:k.invalid_type,expected:y.object,received:O.parsedType}),m}let{status:g,ctx:U}=this._processInputParams(_),{shape:D,keys:I}=this._getCached(),j=[];if(!(this._def.catchall instanceof n$&&this._def.unknownKeys==="strip")){for(let O in U.data)if(!I.includes(O))j.push(O)}let N=[];for(let O of I){let A=D[O],L=U.data[O];N.push({key:{status:"valid",value:O},value:A._parse(new b$(U,L,U.path,O)),alwaysSet:O in U.data})}if(this._def.catchall instanceof n$){let O=this._def.unknownKeys;if(O==="passthrough")for(let A of j)N.push({key:{status:"valid",value:A},value:{status:"valid",value:U.data[A]}});else if(O==="strict"){if(j.length>0)u(U,{code:k.unrecognized_keys,keys:j}),g.dirty()}else if(O==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let O=this._def.catchall;for(let A of j){let L=U.data[A];N.push({key:{status:"valid",value:A},value:O._parse(new b$(U,L,U.path,A)),alwaysSet:A in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let O=[];for(let A of N){let L=await A.key,z=await A.value;O.push({key:L,value:z,alwaysSet:A.alwaysSet})}return O}).then((O)=>{return m_.mergeObjectSync(g,O)});else return m_.mergeObjectSync(g,N)}get shape(){return this._def.shape()}strict(_){return n.errToObj,new b_({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:($,g)=>{let U=this._def.errorMap?.($,g).message??g.defaultError;if($.code==="unrecognized_keys")return{message:n.errToObj(_).message??U};return{message:U}}}:{}})}strip(){return new b_({...this._def,unknownKeys:"strip"})}passthrough(){return new b_({...this._def,unknownKeys:"passthrough"})}extend(_){return new b_({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new b_({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:i.ZodObject})}setKey(_,$){return this.augment({[_]:$})}catchall(_){return new b_({...this._def,catchall:_})}pick(_){let $={};for(let g of U_.objectKeys(_))if(_[g]&&this.shape[g])$[g]=this.shape[g];return new b_({...this._def,shape:()=>$})}omit(_){let $={};for(let g of U_.objectKeys(this.shape))if(!_[g])$[g]=this.shape[g];return new b_({...this._def,shape:()=>$})}deepPartial(){return Dg(this)}partial(_){let $={};for(let g of U_.objectKeys(this.shape)){let U=this.shape[g];if(_&&!_[g])$[g]=U;else $[g]=U.optional()}return new b_({...this._def,shape:()=>$})}required(_){let $={};for(let g of U_.objectKeys(this.shape))if(_&&!_[g])$[g]=this.shape[g];else{let D=this.shape[g];while(D instanceof Z$)D=D._def.innerType;$[g]=D}return new b_({...this._def,shape:()=>$})}keyof(){return z9(U_.objectKeys(this.shape))}}b_.create=(_,$)=>{return new b_({shape:()=>_,unknownKeys:"strip",catchall:n$.create(),typeName:i.ZodObject,...e($)})};b_.strictCreate=(_,$)=>{return new b_({shape:()=>_,unknownKeys:"strict",catchall:n$.create(),typeName:i.ZodObject,...e($)})};b_.lazycreate=(_,$)=>{return new b_({shape:_,unknownKeys:"strip",catchall:n$.create(),typeName:i.ZodObject,...e($)})};class Jg extends __{_parse(_){let{ctx:$}=this._processInputParams(_),g=this._def.options;function U(D){for(let j of D)if(j.result.status==="valid")return j.result;for(let j of D)if(j.result.status==="dirty")return $.common.issues.push(...j.ctx.common.issues),j.result;let I=D.map((j)=>new O$(j.ctx.common.issues));return u($,{code:k.invalid_union,unionErrors:I}),m}if($.common.async)return Promise.all(g.map(async(D)=>{let I={...$,common:{...$.common,issues:[]},parent:null};return{result:await D._parseAsync({data:$.data,path:$.path,parent:I}),ctx:I}})).then(U);else{let D=void 0,I=[];for(let N of g){let O={...$,common:{...$.common,issues:[]},parent:null},A=N._parseSync({data:$.data,path:$.path,parent:O});if(A.status==="valid")return A;else if(A.status==="dirty"&&!D)D={result:A,ctx:O};if(O.common.issues.length)I.push(O.common.issues)}if(D)return $.common.issues.push(...D.ctx.common.issues),D.result;let j=I.map((N)=>new O$(N));return u($,{code:k.invalid_union,unionErrors:j}),m}}get options(){return this._def.options}}Jg.create=(_,$)=>{return new Jg({options:_,typeName:i.ZodUnion,...e($)})};var J6=(_)=>{if(_ instanceof zg)return J6(_.schema);else if(_ instanceof R$)return J6(_.innerType());else if(_ instanceof Sg)return[_.value];else if(_ instanceof t6)return _.options;else if(_ instanceof Wg)return U_.objectValues(_.enum);else if(_ instanceof Xg)return J6(_._def.innerType);else if(_ instanceof Ag)return[void 0];else if(_ instanceof Lg)return[null];else if(_ instanceof Z$)return[void 0,...J6(_.unwrap())];else if(_ instanceof z6)return[null,...J6(_.unwrap())];else if(_ instanceof LN)return J6(_.unwrap());else if(_ instanceof Gg)return J6(_.unwrap());else if(_ instanceof Rg)return J6(_._def.innerType);else return[]};class AN extends __{_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.object)return u($,{code:k.invalid_type,expected:y.object,received:$.parsedType}),m;let g=this.discriminator,U=$.data[g],D=this.optionsMap.get(U);if(!D)return u($,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[g]}),m;if($.common.async)return D._parseAsync({data:$.data,path:$.path,parent:$});else return D._parseSync({data:$.data,path:$.path,parent:$})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,$,g){let U=new Map;for(let D of $){let I=J6(D.shape[_]);if(!I.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let j of I){if(U.has(j))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(j)}`);U.set(j,D)}}return new AN({typeName:i.ZodDiscriminatedUnion,discriminator:_,options:$,optionsMap:U,...e(g)})}}function v3(_,$){let g=P6(_),U=P6($);if(_===$)return{valid:!0,data:_};else if(g===y.object&&U===y.object){let D=U_.objectKeys($),I=U_.objectKeys(_).filter((N)=>D.indexOf(N)!==-1),j={..._,...$};for(let N of I){let O=v3(_[N],$[N]);if(!O.valid)return{valid:!1};j[N]=O.data}return{valid:!0,data:j}}else if(g===y.array&&U===y.array){if(_.length!==$.length)return{valid:!1};let D=[];for(let I=0;I<_.length;I++){let j=_[I],N=$[I],O=v3(j,N);if(!O.valid)return{valid:!1};D.push(O.data)}return{valid:!0,data:D}}else if(g===y.date&&U===y.date&&+_===+$)return{valid:!0,data:_};else return{valid:!1}}class Pg extends __{_parse(_){let{status:$,ctx:g}=this._processInputParams(_),U=(D,I)=>{if(C3(D)||C3(I))return m;let j=v3(D.value,I.value);if(!j.valid)return u(g,{code:k.invalid_intersection_types}),m;if(r3(D)||r3(I))$.dirty();return{status:$.value,value:j.data}};if(g.common.async)return Promise.all([this._def.left._parseAsync({data:g.data,path:g.path,parent:g}),this._def.right._parseAsync({data:g.data,path:g.path,parent:g})]).then(([D,I])=>U(D,I));else return U(this._def.left._parseSync({data:g.data,path:g.path,parent:g}),this._def.right._parseSync({data:g.data,path:g.path,parent:g}))}}Pg.create=(_,$,g)=>{return new Pg({left:_,right:$,typeName:i.ZodIntersection,...e(g)})};class d$ extends __{_parse(_){let{status:$,ctx:g}=this._processInputParams(_);if(g.parsedType!==y.array)return u(g,{code:k.invalid_type,expected:y.array,received:g.parsedType}),m;if(g.data.lengththis._def.items.length)u(g,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let D=[...g.data].map((I,j)=>{let N=this._def.items[j]||this._def.rest;if(!N)return null;return N._parse(new b$(g,I,g.path,j))}).filter((I)=>!!I);if(g.common.async)return Promise.all(D).then((I)=>{return m_.mergeArray($,I)});else return m_.mergeArray($,D)}get items(){return this._def.items}rest(_){return new d$({...this._def,rest:_})}}d$.create=(_,$)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new d$({items:_,typeName:i.ZodTuple,rest:null,...e($)})};class WU extends __{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:g}=this._processInputParams(_);if(g.parsedType!==y.object)return u(g,{code:k.invalid_type,expected:y.object,received:g.parsedType}),m;let U=[],D=this._def.keyType,I=this._def.valueType;for(let j in g.data)U.push({key:D._parse(new b$(g,j,g.path,j)),value:I._parse(new b$(g,g.data[j],g.path,j)),alwaysSet:j in g.data});if(g.common.async)return m_.mergeObjectAsync($,U);else return m_.mergeObjectSync($,U)}get element(){return this._def.valueType}static create(_,$,g){if($ instanceof __)return new WU({keyType:_,valueType:$,typeName:i.ZodRecord,...e(g)});return new WU({keyType:F$.create(),valueType:_,typeName:i.ZodRecord,...e($)})}}class XU extends __{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:g}=this._processInputParams(_);if(g.parsedType!==y.map)return u(g,{code:k.invalid_type,expected:y.map,received:g.parsedType}),m;let U=this._def.keyType,D=this._def.valueType,I=[...g.data.entries()].map(([j,N],O)=>{return{key:U._parse(new b$(g,j,g.path,[O,"key"])),value:D._parse(new b$(g,N,g.path,[O,"value"]))}});if(g.common.async){let j=new Map;return Promise.resolve().then(async()=>{for(let N of I){let O=await N.key,A=await N.value;if(O.status==="aborted"||A.status==="aborted")return m;if(O.status==="dirty"||A.status==="dirty")$.dirty();j.set(O.value,A.value)}return{status:$.value,value:j}})}else{let j=new Map;for(let N of I){let{key:O,value:A}=N;if(O.status==="aborted"||A.status==="aborted")return m;if(O.status==="dirty"||A.status==="dirty")$.dirty();j.set(O.value,A.value)}return{status:$.value,value:j}}}}XU.create=(_,$,g)=>{return new XU({valueType:$,keyType:_,typeName:i.ZodMap,...e(g)})};class i4 extends __{_parse(_){let{status:$,ctx:g}=this._processInputParams(_);if(g.parsedType!==y.set)return u(g,{code:k.invalid_type,expected:y.set,received:g.parsedType}),m;let U=this._def;if(U.minSize!==null){if(g.data.sizeU.maxSize.value)u(g,{code:k.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),$.dirty()}let D=this._def.valueType;function I(N){let O=new Set;for(let A of N){if(A.status==="aborted")return m;if(A.status==="dirty")$.dirty();O.add(A.value)}return{status:$.value,value:O}}let j=[...g.data.values()].map((N,O)=>D._parse(new b$(g,N,g.path,O)));if(g.common.async)return Promise.all(j).then((N)=>I(N));else return I(j)}min(_,$){return new i4({...this._def,minSize:{value:_,message:n.toString($)}})}max(_,$){return new i4({...this._def,maxSize:{value:_,message:n.toString($)}})}size(_,$){return this.min(_,$).max(_,$)}nonempty(_){return this.min(1,_)}}i4.create=(_,$)=>{return new i4({valueType:_,minSize:null,maxSize:null,typeName:i.ZodSet,...e($)})};class jg extends __{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.function)return u($,{code:k.invalid_type,expected:y.function,received:$.parsedType}),m;function g(j,N){return NN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,jN(),Eg].filter((O)=>!!O),issueData:{code:k.invalid_arguments,argumentsError:N}})}function U(j,N){return NN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,jN(),Eg].filter((O)=>!!O),issueData:{code:k.invalid_return_type,returnTypeError:N}})}let D={errorMap:$.common.contextualErrorMap},I=$.data;if(this._def.returns instanceof l4){let j=this;return a_(async function(...N){let O=new O$([]),A=await j._def.args.parseAsync(N,D).catch((W)=>{throw O.addIssue(g(N,W)),O}),L=await Reflect.apply(I,this,A);return await j._def.returns._def.type.parseAsync(L,D).catch((W)=>{throw O.addIssue(U(L,W)),O})})}else{let j=this;return a_(function(...N){let O=j._def.args.safeParse(N,D);if(!O.success)throw new O$([g(N,O.error)]);let A=Reflect.apply(I,this,O.data),L=j._def.returns.safeParse(A,D);if(!L.success)throw new O$([U(A,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new jg({...this._def,args:d$.create(_).rest(m6.create())})}returns(_){return new jg({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,$,g){return new jg({args:_?_:d$.create([]).rest(m6.create()),returns:$||m6.create(),typeName:i.ZodFunction,...e(g)})}}class zg extends __{get schema(){return this._def.getter()}_parse(_){let{ctx:$}=this._processInputParams(_);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}zg.create=(_,$)=>{return new zg({getter:_,typeName:i.ZodLazy,...e($)})};class Sg extends __{_parse(_){if(_.data!==this._def.value){let $=this._getOrReturnCtx(_);return u($,{received:$.data,code:k.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:_.data}}get value(){return this._def.value}}Sg.create=(_,$)=>{return new Sg({value:_,typeName:i.ZodLiteral,...e($)})};function z9(_,$){return new t6({values:_,typeName:i.ZodEnum,...e($)})}class t6 extends __{_parse(_){if(typeof _.data!=="string"){let $=this._getOrReturnCtx(_),g=this._def.values;return u($,{expected:U_.joinValues(g),received:$.parsedType,code:k.invalid_type}),m}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let $=this._getOrReturnCtx(_),g=this._def.values;return u($,{received:$.data,code:k.invalid_enum_value,options:g}),m}return a_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let $ of this._def.values)_[$]=$;return _}get Values(){let _={};for(let $ of this._def.values)_[$]=$;return _}get Enum(){let _={};for(let $ of this._def.values)_[$]=$;return _}extract(_,$=this._def){return t6.create(_,{...this._def,...$})}exclude(_,$=this._def){return t6.create(this.options.filter((g)=>!_.includes(g)),{...this._def,...$})}}t6.create=z9;class Wg extends __{_parse(_){let $=U_.getValidEnumValues(this._def.values),g=this._getOrReturnCtx(_);if(g.parsedType!==y.string&&g.parsedType!==y.number){let U=U_.objectValues($);return u(g,{expected:U_.joinValues(U),received:g.parsedType,code:k.invalid_type}),m}if(!this._cache)this._cache=new Set(U_.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let U=U_.objectValues($);return u(g,{received:g.data,code:k.invalid_enum_value,options:U}),m}return a_(_.data)}get enum(){return this._def.values}}Wg.create=(_,$)=>{return new Wg({values:_,typeName:i.ZodNativeEnum,...e($)})};class l4 extends __{unwrap(){return this._def.type}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.promise&&$.common.async===!1)return u($,{code:k.invalid_type,expected:y.promise,received:$.parsedType}),m;let g=$.parsedType===y.promise?$.data:Promise.resolve($.data);return a_(g.then((U)=>{return this._def.type.parseAsync(U,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}l4.create=(_,$)=>{return new l4({type:_,typeName:i.ZodPromise,...e($)})};class R$ extends __{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===i.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:$,ctx:g}=this._processInputParams(_),U=this._def.effect||null,D={addIssue:(I)=>{if(u(g,I),I.fatal)$.abort();else $.dirty()},get path(){return g.path}};if(D.addIssue=D.addIssue.bind(D),U.type==="preprocess"){let I=U.transform(g.data,D);if(g.common.async)return Promise.resolve(I).then(async(j)=>{if($.value==="aborted")return m;let N=await this._def.schema._parseAsync({data:j,path:g.path,parent:g});if(N.status==="aborted")return m;if(N.status==="dirty")return Ig(N.value);if($.value==="dirty")return Ig(N.value);return N});else{if($.value==="aborted")return m;let j=this._def.schema._parseSync({data:I,path:g.path,parent:g});if(j.status==="aborted")return m;if(j.status==="dirty")return Ig(j.value);if($.value==="dirty")return Ig(j.value);return j}}if(U.type==="refinement"){let I=(j)=>{let N=U.refinement(j,D);if(g.common.async)return Promise.resolve(N);if(N instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return j};if(g.common.async===!1){let j=this._def.schema._parseSync({data:g.data,path:g.path,parent:g});if(j.status==="aborted")return m;if(j.status==="dirty")$.dirty();return I(j.value),{status:$.value,value:j.value}}else return this._def.schema._parseAsync({data:g.data,path:g.path,parent:g}).then((j)=>{if(j.status==="aborted")return m;if(j.status==="dirty")$.dirty();return I(j.value).then(()=>{return{status:$.value,value:j.value}})})}if(U.type==="transform")if(g.common.async===!1){let I=this._def.schema._parseSync({data:g.data,path:g.path,parent:g});if(!n4(I))return m;let j=U.transform(I.value,D);if(j instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:j}}else return this._def.schema._parseAsync({data:g.data,path:g.path,parent:g}).then((I)=>{if(!n4(I))return m;return Promise.resolve(U.transform(I.value,D)).then((j)=>({status:$.value,value:j}))});U_.assertNever(U)}}R$.create=(_,$,g)=>{return new R$({schema:_,typeName:i.ZodEffects,effect:$,...e(g)})};R$.createWithPreprocess=(_,$,g)=>{return new R$({schema:$,effect:{type:"preprocess",transform:_},typeName:i.ZodEffects,...e(g)})};class Z$ extends __{_parse(_){if(this._getType(_)===y.undefined)return a_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}Z$.create=(_,$)=>{return new Z$({innerType:_,typeName:i.ZodOptional,...e($)})};class z6 extends __{_parse(_){if(this._getType(_)===y.null)return a_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}z6.create=(_,$)=>{return new z6({innerType:_,typeName:i.ZodNullable,...e($)})};class Xg extends __{_parse(_){let{ctx:$}=this._processInputParams(_),g=$.data;if($.parsedType===y.undefined)g=this._def.defaultValue();return this._def.innerType._parse({data:g,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}Xg.create=(_,$)=>{return new Xg({innerType:_,typeName:i.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...e($)})};class Rg extends __{_parse(_){let{ctx:$}=this._processInputParams(_),g={...$,common:{...$.common,issues:[]}},U=this._def.innerType._parse({data:g.data,path:g.path,parent:{...g}});if(PU(U))return U.then((D)=>{return{status:"valid",value:D.status==="valid"?D.value:this._def.catchValue({get error(){return new O$(g.common.issues)},input:g.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new O$(g.common.issues)},input:g.data})}}removeCatch(){return this._def.innerType}}Rg.create=(_,$)=>{return new Rg({innerType:_,typeName:i.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...e($)})};class RU extends __{_parse(_){if(this._getType(_)!==y.nan){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.nan,received:g.parsedType}),m}return{status:"valid",value:_.data}}}RU.create=(_)=>{return new RU({typeName:i.ZodNaN,...e(_)})};var tb=Symbol("zod_brand");class LN extends __{_parse(_){let{ctx:$}=this._processInputParams(_),g=$.data;return this._def.type._parse({data:g,path:$.path,parent:$})}unwrap(){return this._def.type}}class GU extends __{_parse(_){let{status:$,ctx:g}=this._processInputParams(_);if(g.common.async)return(async()=>{let D=await this._def.in._parseAsync({data:g.data,path:g.path,parent:g});if(D.status==="aborted")return m;if(D.status==="dirty")return $.dirty(),Ig(D.value);else return this._def.out._parseAsync({data:D.value,path:g.path,parent:g})})();else{let U=this._def.in._parseSync({data:g.data,path:g.path,parent:g});if(U.status==="aborted")return m;if(U.status==="dirty")return $.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:g.path,parent:g})}}static create(_,$){return new GU({in:_,out:$,typeName:i.ZodPipeline})}}class Gg extends __{_parse(_){let $=this._def.innerType._parse(_),g=(U)=>{if(n4(U))U.value=Object.freeze(U.value);return U};return PU($)?$.then((U)=>g(U)):g($)}unwrap(){return this._def.innerType}}Gg.create=(_,$)=>{return new Gg({innerType:_,typeName:i.ZodReadonly,...e($)})};function $9(_,$){let g=typeof _==="function"?_($):typeof _==="string"?{message:_}:_;return typeof g==="string"?{message:g}:g}function S9(_,$={},g){if(_)return m4.create().superRefine((U,D)=>{let I=_(U);if(I instanceof Promise)return I.then((j)=>{if(!j){let N=$9($,U),O=N.fatal??g??!0;D.addIssue({code:"custom",...N,fatal:O})}});if(!I){let j=$9($,U),N=j.fatal??g??!0;D.addIssue({code:"custom",...j,fatal:N})}return});return m4.create()}var ob={object:b_.lazycreate},i;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(i||(i={}));var pb=(_,$={message:`Input not instance of ${_.name}`})=>S9((g)=>g instanceof _,$),W9=F$.create,X9=i6.create,eb=RU.create,ab=l6.create,R9=Og.create,sb=d4.create,_H=zU.create,$H=Ag.create,gH=Lg.create,DH=m4.create,UH=m6.create,IH=n$.create,jH=SU.create,NH=M$.create,EH=b_.create,OH=b_.strictCreate,AH=Jg.create,LH=AN.create,JH=Pg.create,PH=d$.create,zH=WU.create,SH=XU.create,WH=i4.create,XH=jg.create,RH=zg.create,GH=Sg.create,YH=t6.create,QH=Wg.create,TH=l4.create,g9=R$.create,qH=Z$.create,BH=z6.create,KH=R$.createWithPreprocess,VH=GU.create,FH=()=>W9().optional(),MH=()=>X9().optional(),ZH=()=>R9().optional(),bH={string:(_)=>F$.create({..._,coerce:!0}),number:(_)=>i6.create({..._,coerce:!0}),boolean:(_)=>Og.create({..._,coerce:!0}),bigint:(_)=>l6.create({..._,coerce:!0}),date:(_)=>d4.create({..._,coerce:!0})},HH=m;var x={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",taskToPrProjection:"hasna.task_to_pr_projection.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",secureLocalStorePolicy:"hasna.secure_local_store_policy.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},w3=E.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),V_=E.string().datetime(),t=E.string().trim().min(1),H$=t.refine((_)=>_.startsWith("artifact://")||_.startsWith("repo://")||_.startsWith("project://")||_.startsWith("dashboard://")||_.startsWith("render://")||_.startsWith("integration://")||_.startsWith("task://")||_.startsWith("todo://")||_.startsWith("file://")||_.startsWith("files://")||_.startsWith("mailery://")||_.startsWith("conversation://")||_.startsWith("knowledge://")||_.startsWith("memento://")||_.startsWith("https://")||_.startsWith("http://")||_.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),G9=E.string().regex(/^[a-fA-F0-9]{64}$/),Y9=E.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),o6=E.record(E.unknown()),Tg=E.array(E.string().min(1)).default([]),t4=V_.nullable().optional(),kH=new Set(["succeeded","failed","cancelled","blocked","skipped"]),e4=E.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function L_(_){return E.object({schema:E.literal(_),id:E.string().min(1),createdAt:V_,updatedAt:t4,metadata:o6.optional()}).strict()}var jd=E.object({schema:w3,id:E.string().min(1),createdAt:V_,updatedAt:t4,metadata:o6.optional()}).strict(),Q9=E.enum(["agent","human","service","model","workflow","system"]),CH=L_(x.actorRef).extend({kind:Q9,name:E.string().min(1).optional(),provider:E.string().min(1).optional(),accountId:E.string().min(1).optional(),machineId:E.string().min(1).optional(),capabilities:E.array(E.string().min(1)).default([])}).strict(),m$=E.object({kind:Q9,id:E.string().min(1),name:E.string().min(1).optional(),provider:E.string().min(1).optional(),accountId:E.string().min(1).optional(),machineId:E.string().min(1).optional()}).strict(),T9=E.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),rH=L_(x.resourceRef).extend({kind:T9,name:E.string().min(1).optional(),uri:H$.optional(),externalId:t.optional(),sourcePackage:t.optional(),tags:Tg}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.externalId&&_.sourcePackage))$.addIssue({code:E.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),s=E.object({kind:T9,id:E.string().min(1),name:E.string().min(1).optional(),uri:H$.optional(),externalId:t.optional(),sourcePackage:t.optional(),tags:Tg}).strict().superRefine((_,$)=>{if(!_.uri&&Boolean(_.externalId)!==Boolean(_.sourcePackage))$.addIssue({code:E.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:_.externalId?["sourcePackage"]:["externalId"]})}),u3=E.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),vH=E.enum(["none","partial","full","unknown"]),fH=L_(x.evidenceRef).extend({kind:u3,uri:H$,sha256:G9.optional(),summary:E.string().min(1).optional(),contentType:E.string().min(1).optional(),sizeBytes:E.number().int().nonnegative().optional(),redaction:vH.default("unknown"),producer:m$.optional(),resourceRefs:E.array(s).default([]),tags:Tg}).strict(),T_=E.object({id:E.string().min(1),kind:u3.optional(),uri:H$.optional(),sha256:G9.optional(),summary:E.string().min(1).optional()}).strict(),YU=L_(x.costEstimate).extend({currency:E.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:E.number().int().nonnegative(),provider:E.string().min(1).optional(),model:E.string().min(1).optional(),accountId:E.string().min(1).optional(),promptTokens:E.number().int().nonnegative().optional(),completionTokens:E.number().int().nonnegative().optional(),totalTokens:E.number().int().nonnegative().optional(),basis:E.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.promptTokens!==void 0&&_.completionTokens!==void 0&&_.totalTokens!==void 0&&_.totalTokens!==_.promptTokens+_.completionTokens)$.addIssue({code:E.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),wH=E.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),q9=L_(x.decisionEnvelope).extend({decisionType:E.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:wH,actor:m$.optional(),traceId:E.string().min(1).optional(),inputHash:Y9.optional(),policyBundleId:E.string().min(1).optional(),selected:E.array(s).default([]),skipped:E.array(s).default([]),reason:E.string().min(1),obligations:E.array(E.string().min(1)).default([]),redactions:E.array(E.string().min(1)).default([]),costEstimate:YU.optional(),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.status==="selected"&&_.selected.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if(_.status==="skipped"&&_.skipped.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if(_.status==="denied"){if(_.selected.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!_.policyBundleId&&_.evidenceRefs.length===0&&_.obligations.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if(_.status==="approval_required"&&_.obligations.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),uH=L_(x.capabilityCard).extend({kind:E.enum(["model","tool","machine","agent","lane","connector","service"]),name:E.string().min(1),version:E.string().min(1).optional(),status:E.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:E.array(E.string().min(1)).default([]),limitations:E.array(E.string().min(1)).default([]),riskLevel:E.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:YU.optional(),evidenceRefs:E.array(T_).default([])}).strict(),Yg=E.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),xH=E.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),yH=E.object({refName:t,requiredForModes:E.array(Yg).min(1),allowedSecretInputs:E.array(E.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:t,revocationCheck:E.boolean().default(!0)}).strict(),hH=E.object({operation:t,supportedModes:E.array(Yg).min(1),sideEffectClass:xH,requiresApproval:E.boolean().default(!1),requiresIdempotencyKey:E.boolean().default(!1),requiresSandboxEvidence:E.boolean().default(!1),requiresRollbackOrRevocation:E.boolean().default(!1),rollbackOrRevocation:t.optional(),noSideEffectSmoke:t.optional(),reconciliation:t.optional()}).strict().superRefine((_,$)=>{if(_.supportedModes.includes("live_mutating")){if(_.sideEffectClass==="none"||_.sideEffectClass==="read_only")$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!_.requiresApproval)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!_.requiresIdempotencyKey)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!_.requiresSandboxEvidence)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!_.requiresRollbackOrRevocation||!_.rollbackOrRevocation)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!_.reconciliation)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),cH=E.object({providerId:t,appId:t,adapterId:t,ownerPackage:t,modes:E.array(Yg).min(1),defaultMode:Yg,credentialRequirements:E.array(yH).default([]),operations:E.array(hH).min(1),rateLimitPosture:t,costPosture:t.optional(),auditEvents:E.array(t).default([]),redactionRules:E.array(t).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(!_.modes.includes(_.defaultMode))$.addIssue({code:E.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let g=new Set(_.operations.flatMap((U)=>U.supportedModes));for(let U of g)if(!_.modes.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(g.has("live_mutating")){if(!_.credentialRequirements.some((D)=>D.requiredForModes.includes("live_mutating")))$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if(_.auditEvents.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),nH=E.object({appId:t,repo:t,priority:E.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:E.array(t).min(1),firstOperations:E.array(t).min(1),blockedUntil:E.array(t).default([])}).strict(),dH=L_(x.providerLiveModeStandard).extend({name:t,version:t,modes:E.array(Yg).refine((_)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every(($)=>_.includes($)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:E.array(t).min(1),liveMutationGate:E.object({requiredMode:E.literal("live_mutating"),requiredChecks:E.array(t).min(1),forbiddenBypassSignals:E.array(t).min(1),disabledLiveSmoke:t}).strict(),noSideEffectSmoke:E.object({requiredForModes:E.array(Yg).min(1),commandEvidence:E.array(t).min(1),secretOutputScan:E.boolean().default(!0)}).strict(),credentialPolicy:E.object({acceptedInputs:E.array(E.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:E.literal(!1),missingCredentialBehavior:E.literal("fail_closed"),revocationCheckRequired:E.boolean().default(!0)}).strict(),operationCards:E.array(cH).min(1),firstAdoptionTargets:E.array(nH).min(1),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let g=new Set(_.firstAdoptionTargets.map((D)=>D.appId)),U=new Set(_.operationCards.map((D)=>D.appId));for(let D of g)if(!U.has(D))$.addIssue({code:E.ZodIssueCode.custom,message:`first adoption target ${D} requires a provider capability card`,path:["firstAdoptionTargets"]})}),mH=E.object({id:E.string().min(1),title:E.string().min(1).optional(),summary:E.string().min(1),text:E.string().optional(),tokens:E.number().int().nonnegative().optional(),source:T_,resourceRefs:E.array(s).default([])}).strict(),B9=L_(x.contextPack).extend({objective:E.string().min(1),budget:E.object({maxTokens:E.number().int().positive().optional(),maxBytes:E.number().int().positive().optional()}).strict().optional(),items:E.array(mH).default([]),citations:E.array(T_).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),permissions:E.array(E.string().min(1)).default([]),redactions:E.array(E.string().min(1)).default([]),conflicts:E.array(E.string().min(1)).default([]),uncertainty:E.string().min(1).optional()}).strict(),W$=t.refine((_)=>!_.startsWith("/")&&!_.includes("\\")&&!_.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),o4=E.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),iH=E.enum(["public","internal","private","sensitive"]),lH=E.enum(["draft","active","paused","archived"]),x3=E.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),K9=L_(x.integrationRef).extend({kind:x3,name:E.string().min(1),projectId:o4.optional(),sourcePackage:t.optional(),externalId:t.optional(),uri:H$.optional(),enabled:E.boolean().default(!0),readOnly:E.boolean().default(!0),capabilities:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:s.optional(),evidenceRefs:E.array(T_).default([]),config:o6.optional()}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.sourcePackage&&_.externalId)&&!_.resourceRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),tH=E.object({schemaRoot:W$.default(".hasna/project"),dashboardManifest:W$.default(".hasna/project/dashboard.render.json"),snapshotsDir:W$.default(".hasna/project/snapshots"),documentsDir:W$.default("documents"),reportsDir:W$.default("reports"),evidenceDir:W$.default(".hasna/project/evidence"),privateDir:W$.default(".hasna/project/private")}).strict(),oH=L_(x.projectManifest).extend({projectId:o4,slug:o4,name:E.string().min(1),summary:E.string().min(1).optional(),status:lH.default("active"),classification:iH.default("private"),owner:m$.optional(),layout:tH.default({}),integrations:E.array(K9).default([]),renderManifests:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),tags:Tg}).strict().superRefine((_,$)=>{let g=new Set,U=new Set;if(_.projectId!==_.slug)$.addIssue({code:E.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[D,I]of _.integrations.entries()){if(g.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",D,"id"]});if(g.add(I.id),I.projectId&&I.projectId!==_.projectId)$.addIssue({code:E.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",D,"projectId"]})}for(let[D,I]of _.renderManifests.entries()){if(I.kind!=="render")$.addIssue({code:E.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",D,"kind"]});if(U.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",D,"id"]});U.add(I.id)}}),pH=E.enum(["local","package","provider","url"]),y3=E.object({id:E.string().min(1),kind:pH,specifier:E.string().min(1),path:W$.optional(),packageName:E.string().min(1).optional(),uri:H$.optional(),provider:x3.optional(),schemaId:w3.optional(),integrity:Y9.optional(),resourceRef:s.optional(),optional:E.boolean().default(!1)}).strict().superRefine((_,$)=>{if(_.kind==="local"&&!_.path)$.addIssue({code:E.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if(_.kind==="package"&&!_.packageName)$.addIssue({code:E.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if(_.kind==="provider"&&!_.provider)$.addIssue({code:E.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if(_.kind==="url"&&!_.uri)$.addIssue({code:E.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),eH=E.enum(["dashboard","canvas","panel","report","document","custom"]),aH=E.object({id:E.string().min(1),title:E.string().min(1),kind:eH,default:E.boolean().default(!1),entry:W$.optional(),imports:E.array(y3).default([]),panelRefs:E.array(s).default([]),dataRefs:E.array(s).default([]),layout:o6.optional()}).strict(),sH=L_(x.renderManifest).extend({projectId:o4,name:E.string().min(1),version:E.string().min(1),manifestPath:W$.default(".hasna/project/dashboard.render.json"),renderer:E.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:E.array(aH).min(1),imports:E.array(y3).default([]),theme:o6.optional(),compatibility:E.object({minProjectsVersion:E.string().min(1).optional(),minContractsVersion:E.string().min(1).optional()}).strict().optional(),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let g=_.views.filter((I)=>I.default),U=new Set,D=new Set;if(g.length>1)$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[I,j]of _.imports.entries()){if(D.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",I,"id"]});D.add(j.id)}for(let[I,j]of _.views.entries()){if(U.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",I,"id"]});U.add(j.id);let N=new Set;for(let[O,A]of j.imports.entries()){if(N.has(A.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",I,"imports",O,"id"]});N.add(A.id)}for(let[O,A]of j.panelRefs.entries())if(A.kind!=="panel")$.addIssue({code:E.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",I,"panelRefs",O,"kind"]})}}),_k=E.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),$k=E.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),gk=E.object({id:E.string().min(1),label:E.string().min(1),value:E.union([E.string(),E.number(),E.boolean()]),unit:E.string().min(1).optional(),status:E.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:E.array(s).default([])}).strict(),Dk=E.object({id:E.string().min(1),title:E.string().min(1),summary:E.string().min(1).optional(),status:E.string().min(1).optional(),priority:E.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:V_.optional(),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),metadata:o6.optional()}).strict(),Uk=E.object({renderer:E.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:E.string().min(1).optional(),entry:W$.optional(),imports:E.array(y3).default([]),spec:o6.default({})}).strict(),V9=L_(x.projectPanel).extend({projectId:o4,provider:E.object({kind:x3,id:E.string().min(1),name:E.string().min(1).optional(),sourcePackage:t.optional(),externalId:t.optional()}).strict(),kind:$k,title:E.string().min(1),summary:E.string().min(1).optional(),state:_k.default("ready"),stateReason:E.string().min(1).optional(),generatedAt:V_,freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),metrics:E.array(gk).default([]),items:E.array(Dk).default([]),actions:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),renderFragment:Uk.optional(),warnings:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{let g=new Set(["error","auth_required","unavailable","stale"]),U=new Set,D=new Set;if(g.has(_.state)&&!_.stateReason)$.addIssue({code:E.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if(_.state==="ready"&&_.metrics.length===0&&_.items.length===0&&!_.renderFragment)$.addIssue({code:E.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[I,j]of _.metrics.entries()){if(U.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",I,"id"]});U.add(j.id)}for(let[I,j]of _.items.entries()){if(D.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",I,"id"]});D.add(j.id)}for(let[I,j]of _.actions.entries())if(j.kind!=="action")$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",I,"kind"]})}),Ik=L_(x.projectSnapshot).extend({projectId:o4,generatedAt:V_,status:e4.default("unknown"),manifestRef:s,renderManifestRef:s.optional(),panels:E.array(V9).default([]),contextPacks:E.array(B9).default([]),proofBundleRefs:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),warnings:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{let g=new Set,U=new Set;if(_.manifestRef.kind!=="project")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if(_.renderManifestRef&&_.renderManifestRef.kind!=="render")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[D,I]of _.proofBundleRefs.entries())if(I.kind!=="proof_bundle")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",D,"kind"]});for(let[D,I]of _.panels.entries()){if(I.projectId!==_.projectId)$.addIssue({code:E.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",D,"projectId"]});if(g.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",D,"id"]});g.add(I.id)}for(let[D,I]of _.contextPacks.entries()){if(U.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",D,"id"]});U.add(I.id)}}),F9=E.object({id:E.string().min(1),kind:E.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:E.boolean().default(!0),command:E.string().min(1).optional(),expected:E.string().min(1).optional(),timeoutMs:E.number().int().positive().optional(),resourceRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has(_.kind)&&!_.command&&!_.expected)$.addIssue({code:E.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),jk=L_(x.validationPlan).extend({objective:E.string().min(1),subject:s.optional(),checks:E.array(F9).min(1),verifier:m$.optional(),requiredEvidenceKinds:E.array(u3).default([])}).strict(),Nk=E.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),Ek=E.enum(["draft","active","deprecated","archived"]),Ok=E.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Ak=E.object({key:E.string().regex(/^[A-Z][A-Z0-9_]*$/),description:E.string().min(1),required:E.boolean().default(!1),["secret"]:E.boolean().default(!1),group:E.string().min(1).optional(),default:E.string().optional()}).strict().superRefine((_,$)=>{if(_.secret&&_.default!==void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Lk=E.object({name:E.string().min(1),command:E.string().min(1),description:E.string().min(1).optional(),required:E.boolean().default(!1)}).strict(),Jk=E.object({packageManager:E.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:E.array(E.string().min(1)).default([]),requiredFiles:E.array(E.string().min(1)).default([]),requiredDirectories:E.array(E.string().min(1)).default([]),optionalDirectories:E.array(E.string().min(1)).default([])}).strict(),Pk=L_(x.scaffoldManifest).extend({name:E.string().min(1),version:E.string().min(1),summary:E.string().min(1),type:Nk,status:Ek.default("draft"),capabilities:E.array(Ok).default([]),techStack:E.array(E.string().min(1)).default([]),tags:Tg,source:s.optional(),output:Jk,env:E.array(Ak).default([]),scripts:E.array(Lk).default([]),validationChecks:E.array(F9).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.source?.uri?.startsWith("file://"))$.addIssue({code:E.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if(_.status==="active"&&_.validationChecks.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if(_.status==="active"&&_.output.requiredFiles.length===0&&_.output.requiredDirectories.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),zk=E.enum(["installed","failed","cancelled","partial","unknown"]),Sk=L_(x.scaffoldInstallRecord).extend({scaffoldId:E.string().min(1),scaffoldVersion:E.string().min(1).optional(),manifestRef:s.optional(),target:s,status:zk,installedAt:V_.optional(),installer:m$.optional(),packageManager:E.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:o6.optional(),generatedFiles:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),proofBundleRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.status==="installed"&&!_.installedAt)$.addIssue({code:E.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if(_.status==="installed"&&_.generatedFiles.length===0&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if((_.status==="failed"||_.status==="partial")&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),Qg=E.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),h3=E.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),M9=E.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),Wk=E.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),Xk=t.refine((_)=>_.startsWith("https://github.com/")||_.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),Rk=E.enum(["active","stub","deprecated","archived"]),Gk=E.enum(["stable","beta","canary","internal"]),Yk=E.object({transport:E.enum(["http","stdio"]).default("http"),bin:E.string().min(1).optional(),url:H$.optional()}).strict(),Qk=E.object({healthPath:E.string().min(1).default("/health"),port:E.number().int().positive().optional(),baseUrl:H$.optional()}).strict(),Tk=E.object({bins:E.array(E.string().min(1)).default([]),mcp:Yk.optional(),http:Qk.optional()}).strict(),qk=L_(x.app).extend({appId:Qg,npmName:h3,repoFolder:Qg,githubUrl:Xk,projectSlug:o4,surfaces:Tk.default({}),lifecycle:Rk,releaseChannel:Gk.default("stable"),summary:E.string().min(1).optional(),tags:Tg}).strict().superRefine((_,$)=>{let g=new Set;for(let[U,D]of _.surfaces.bins.entries()){if(g.has(D))$.addIssue({code:E.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});g.add(D)}}),Bk=E.enum(["skill","ci","backfilled"]),Kk=L_(x.release).extend({appId:Qg,package:h3,version:M9,gitSha:Wk,publishedAt:V_,publishPath:Bk,changelogRef:s.optional(),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.publishPath!=="backfilled"&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Vk=E.enum(["install","update","rollback","freeze-blocked"]),Fk=E.object({cliVersion:E.string().min(1).optional(),mcpHealth:E.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine((_,$)=>{if(!_.cliVersion&&_.mcpHealth===void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),Mk=L_(x.rolloutRecord).extend({appId:Qg,package:h3,version:M9,machine:t,action:Vk,result:e4,verifiedBy:Fk.optional(),at:V_,evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.action==="freeze-blocked"&&_.result!=="blocked"&&_.result!=="skipped")$.addIssue({code:E.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let g=Boolean(_.verifiedBy?.cliVersion)||_.verifiedBy?.mcpHealth!==void 0&&_.verifiedBy.mcpHealth!=="not_checked",U=_.verifiedBy?Object.keys(_.verifiedBy).length>0:!1;if((_.action==="install"||_.action==="update")&&_.result==="succeeded"&&(!_.verifiedBy||U&&!g))$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),Zk=E.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),bk=E.enum(["pending","queued","sent","failed","skipped","suppressed"]),Hk=E.object({channel:Zk,status:bk,deliveredAt:V_.optional(),detail:E.string().min(1).optional()}).strict().superRefine((_,$)=>{if(_.status==="sent"&&!_.deliveredAt)$.addIssue({code:E.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if(_.status==="failed"&&!_.detail)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),kk=L_(x.announcement).extend({campaignId:t,appId:Qg.optional(),releaseRef:s.optional(),channels:E.array(Hk).min(1),audienceRef:s,sentAt:V_}).strict().superRefine((_,$)=>{if(_.releaseRef&&_.releaseRef.kind!=="release")$.addIssue({code:E.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if(_.audienceRef.kind!=="audience")$.addIssue({code:E.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),Ck=E.enum(["tag","attribute","group"]),rk=E.enum(["eq","neq","in","not_in","exists","not_exists"]),D9=E.union([E.string(),E.number(),E.boolean()]),vk=E.object({kind:Ck,key:E.string().min(1).optional(),op:rk.default("eq"),value:D9.optional(),values:E.array(D9).default([])}).strict().superRefine((_,$)=>{if(_.kind==="attribute"&&!_.key)$.addIssue({code:E.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if((_.op==="eq"||_.op==="neq")&&_.value===void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if((_.op==="in"||_.op==="not_in")&&_.values.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),fk=E.object({match:E.enum(["all","any"]).default("all"),predicates:E.array(vk).min(1)}).strict(),wk=E.enum(["opt_in","opt_out","transactional","none"]),uk=L_(x.audience).extend({audienceId:Qg,name:t,definition:fk,consentPolicy:wk,suppressionSyncedAt:t4}).strict(),IN=["@hasna/cloud","open-cloud"],xk=E.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),yk=E.object({id:E.string().min(1),provider:xk,kind:E.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:E.string().min(1),region:E.string().min(1).optional(),accountId:E.string().min(1).optional(),uri:H$.optional(),machineScoped:E.boolean().default(!1)}).strict(),Z9=L_(x.appCloudManifest).extend({packageName:E.string().min(1),packageVersion:E.string().min(1).optional(),appId:E.string().min(1),repository:s.optional(),storageMode:E.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:E.enum(["none","app_owned","external_service","local_cache"]),cloudResources:E.array(yk).default([]),localCache:E.object({path:E.string().min(1).optional(),pullMode:E.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:E.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:E.array(E.string().min(1)).default([...IN]),dependencies:E.array(E.string().min(1)).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let g=new Set([...IN,..._.forbiddenSharedRuntimes]);if(g.has(_.packageName))$.addIssue({code:E.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of IN)if(!_.forbiddenSharedRuntimes.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of g)if(_.dependencies.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if(_.storageMode==="local_only"&&_.cloudBoundary!=="none")$.addIssue({code:E.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if(_.storageMode==="app_owned_cloud"&&_.cloudBoundary!=="app_owned")$.addIssue({code:E.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if(_.storageMode==="hybrid_local_cache"){if(_.cloudBoundary!=="local_cache")$.addIssue({code:E.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!_.localCache)$.addIssue({code:E.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if(_.storageMode==="external_service"){if(_.cloudBoundary!=="external_service")$.addIssue({code:E.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if(_.cloudResources.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if((_.storageMode==="app_owned_cloud"||_.storageMode==="hybrid_local_cache")&&_.cloudResources.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if(_.cloudBoundary==="none"&&_.cloudResources.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});_.cloudResources.forEach((U,D)=>{if(U.ownerPackage!==_.packageName)$.addIssue({code:E.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",D,"ownerPackage"]})})}),b9=E.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),hk=E.enum(["low","medium","high","critical"]),H9=E.object({id:E.string().min(1),kind:b9,severity:hk,path:E.string().min(1).optional(),packageName:E.string().min(1).optional(),pattern:E.string().min(1),message:E.string().min(1),evidenceRefs:E.array(T_).default([])}).strict(),ck=E.object({id:E.string().min(1),kind:b9,status:e4,target:E.string().min(1),command:E.string().min(1).optional(),evidenceRefs:E.array(T_).default([]),findings:E.array(H9).default([])}).strict(),nk=L_(x.noCloudEvidencePack).extend({subject:s,packageName:E.string().min(1).optional(),packageVersion:E.string().min(1).optional(),generatedBy:m$.optional(),scanMode:E.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:e4,verdict:E.enum(["passed","failed","warning","not_run"]),appCloudManifest:Z9.optional(),checks:E.array(ck).min(1),findings:E.array(H9).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let g=[..._.findings,..._.checks.flatMap((D)=>D.findings)],U=g.filter((D)=>D.severity==="high"||D.severity==="critical");if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if(_.checks.some((D)=>D.status!=="succeeded"))$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if(_.verdict==="failed"&&g.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if(_.status==="succeeded"&&_.checks.some((D)=>D.status==="failed"))$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});_.checks.forEach((D,I)=>{let j=D.findings.filter((N)=>N.severity==="high"||N.severity==="critical");if(D.status==="succeeded"&&j.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",I,"findings"]})})}),dk=E.object({checkId:E.string().min(1),status:e4,summary:E.string().min(1).optional(),startedAt:t4,finishedAt:t4,evidenceRefs:E.array(T_).default([])}).strict(),mk=L_(x.proofBundle).extend({subject:s,validationPlanRef:s.optional(),status:e4,verdict:E.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:E.array(dk).default([]),verifier:m$.optional(),evidenceRefs:E.array(T_).default([]),residualRisks:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if(_.checks.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if(_.checks.forEach((U,D)=>{if(U.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",D,"status"]})}),!(_.evidenceRefs.length>0||_.checks.some((U)=>U.evidenceRefs.length>0)))$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!_.verifier)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if(_.verdict==="not_run"&&_.checks.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if(_.verdict==="failed"&&!_.checks.some((g)=>g.status==="failed")&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),ik=L_(x.workRun).extend({objective:E.string().min(1),status:e4,actor:m$,traceId:E.string().min(1).optional(),startedAt:t4,finishedAt:t4,constraints:E.array(E.string().min(1)).default([]),resourceRefs:E.array(s).default([]),decisions:E.array(q9).default([]),costEstimates:E.array(YU).default([]),evidenceRefs:E.array(T_).default([]),validationPlanRefs:E.array(s).default([]),proofBundleRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.startedAt&&_.finishedAt&&Date.parse(_.finishedAt)0||_.proofBundleRefs.length>0;if(_.status==="succeeded"&&!g)$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if((_.status==="failed"||_.status==="blocked")&&!g&&_.decisions.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),lk=Object.freeze({work_run:Object.freeze(["codewith"]),root_request:Object.freeze(["todos"]),pr_group:Object.freeze(["todos"]),leaf_task:Object.freeze(["todos"]),attempt:Object.freeze(["todos"]),writer_generation:Object.freeze(["todos"]),writer_lease:Object.freeze(["repos"]),writer_fence:Object.freeze(["repos"]),provider_profile:Object.freeze(["codewith"]),provider_route:Object.freeze(["codewith"]),admission:Object.freeze(["codewith"]),worker_actor:Object.freeze(["codewith"]),worker:Object.freeze(["codewith"]),runtime:Object.freeze(["codewith"]),repo:Object.freeze(["repos"]),worktree:Object.freeze(["repos"]),branch:Object.freeze(["repos"]),event_stream:Object.freeze(["todos"]),replay_cursor:Object.freeze(["todos"]),handoff:Object.freeze(["todos"]),pull_request:Object.freeze(["todos"]),commit:Object.freeze(["repos"]),review:Object.freeze(["review"]),reviewer:Object.freeze(["review"]),review_run:Object.freeze(["review"]),proof_bundle:Object.freeze(["review"]),repair_cycle:Object.freeze(["todos"]),merge_guard:Object.freeze(["todos"]),merge_operator:Object.freeze(["merge_provider"]),merge_operator_run:Object.freeze(["merge_provider"]),merge_guard_receipt:Object.freeze(["merge_provider"]),merge_outcome:Object.freeze(["merge_provider"]),recovery:Object.freeze(["todos"]),cancellation:Object.freeze(["todos"]),cleanup_eligibility:Object.freeze(["repos"]),cleanup_outcome:Object.freeze(["repos"]),rollback_plan:Object.freeze(["todos"]),rollback_outcome:Object.freeze(["repos"]),terminal_disposition:Object.freeze(["todos"]),openloops_invocation:Object.freeze(["openloops"]),adapter_extension:Object.freeze(["adapter"])}),tk=E.enum(["work_run","root_request","pr_group","leaf_task","attempt","writer_generation","writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","repo","worktree","branch","event_stream","replay_cursor","handoff","pull_request","commit","review","reviewer","review_run","proof_bundle","repair_cycle","merge_guard","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","recovery","cancellation","cleanup_eligibility","cleanup_outcome","rollback_plan","rollback_outcome","terminal_disposition","openloops_invocation","adapter_extension"]),ok=E.enum(["todos","codewith","repos","review","merge_provider","openloops","adapter"]),p4=E.string().regex(/^[a-f0-9]{64}$/),JN=E.string().trim().min(3).max(256),k9=/^[a-f0-9]{32}$/;function pk(_,$,g){return`${_}:${$}:opaque-${g.slice(0,32)}`}function ek(_){return`evidence:opaque-${_.slice(0,32)}`}var C9=JN.refine((_)=>{let g=_.startsWith("task_to_pr_projection:opaque-")?_.slice(29):"";return k9.test(g)},"Projection ids must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),c3=JN.refine((_)=>{let g=_.startsWith("attempt_nonce:opaque-")?_.slice(21):"";return k9.test(g)},"Attempt nonces must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),ak=new Set(["writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","worktree","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","openloops_invocation","adapter_extension"]),n3=E.object({role:tk,authority:ok,id:JN,digest:p4,redaction:E.enum(["none","partial","full"])}).strict().superRefine((_,$)=>{let g=lk[_.role];if(!g.includes(_.authority))$.addIssue({code:E.ZodIssueCode.custom,message:`${_.role} refs must be owned by ${g.join(" or ")}`,path:["authority"]});if(ak.has(_.role)&&_.redaction==="none")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.role} refs must be redacted and cannot carry a raw locator or credential`,path:["redaction"]});let U=pk(_.role,_.authority,_.digest);if(_.id!==U)$.addIssue({code:E.ZodIssueCode.custom,message:"Reference ids must be nonsemantic authority-bound surrogates derived from the canonical role, authority, and owner-record digest",path:["id"]})}),X$=E.object({id:JN,digest:p4,redaction:E.enum(["partial","full"])}).strict().superRefine((_,$)=>{if(_.id!==ek(_.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Evidence ids must be nonsemantic owner-resolvable surrogates derived from their canonical digest",path:["id"]})});function r9(_,$,g,U){if(_.id===$.id||_.digest===$.digest)g.addIssue({code:E.ZodIssueCode.custom,message:"Stop and lease-revocation facts require distinct evidence identities and digests",path:U})}function b(_){return n3.refine(($)=>$.role===_,{message:`Reference must use role ${_}`,path:["role"]})}function B_(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id&&_.digest===$.digest&&_.redaction===$.redaction}function d3(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id}function Ng(_,$,g,U,D){if(d3(_,$))g.addIssue({code:E.ZodIssueCode.custom,message:`${D} requires a fresh canonical role/authority/id`,path:U});if(_.digest===$.digest)g.addIssue({code:E.ZodIssueCode.custom,message:`${D} requires a fresh canonical digest`,path:U})}function EN(_){return`${_.role}\x00${_.authority}\x00${_.id}`}function e_(_,$){return _.algorithm===$.algorithm&&_.value===$.value}var Q_=E.object({algorithm:E.enum(["sha1","sha256"]),value:E.string().regex(/^[a-f0-9]+$/)}).strict().superRefine((_,$)=>{let g=_.algorithm==="sha1"?40:64;if(_.value.length!==g)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.algorithm} object ids must contain exactly ${g} lowercase hex characters`,path:["value"]})});function U9(_){if(_.canonicalizationVersion===1){let g=JSON.stringify(["hasna.task_to_pr_projection.binding.v1",_.canonicalizationVersion,_.rootRequestRef.id,_.rootRequestRef.digest,_.prGroupRef.id,_.prGroupRef.digest,_.leafTaskRef.id,_.leafTaskRef.digest,_.repoRef.id,_.repoRef.digest,_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return sG("sha256").update(g,"utf8").digest("hex")}let $=JSON.stringify(["hasna.task_to_pr_projection.binding.v2",_.canonicalizationVersion,...[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repoRef,_.worktreeRef,_.branchRef].flatMap((g)=>[g.role,g.authority,g.id,g.digest]),_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return sG("sha256").update($,"utf8").digest("hex")}var sk=E.object({ref:b("attempt"),nonce:c3,admissionRef:b("admission"),admissionWriterGenerationRef:b("writer_generation"),workerActorRef:b("worker_actor"),workerRef:b("worker"),runtimeRef:b("runtime"),writerGenerationRef:b("writer_generation"),writerLeaseRef:b("writer_lease"),writerFenceRef:b("writer_fence"),providerProfileRef:b("provider_profile"),providerRouteRef:b("provider_route")}).strict(),_C=E.object({repoRef:b("repo"),worktreeRef:b("worktree"),branchRef:b("branch"),baseHead:Q_,branchHead:Q_}).strict(),$C=E.object({streamRef:b("event_stream"),replayCursorRef:b("replay_cursor"),sequence:E.number().int().safe().nonnegative(),prefixDigest:p4}).strict(),gC=E.object({ref:b("handoff"),previousAttemptRef:b("attempt"),nextAttemptRef:b("attempt"),previousWriterGenerationRef:b("writer_generation"),nextWriterGenerationRef:b("writer_generation"),stoppedWorkRunRef:b("work_run"),stopEvidenceRef:X$,leaseRevocationEvidenceRef:X$}).strict().superRefine((_,$)=>{Ng(_.previousAttemptRef,_.nextAttemptRef,$,["nextAttemptRef"],"Handoff attempt rotation"),Ng(_.previousWriterGenerationRef,_.nextWriterGenerationRef,$,["nextWriterGenerationRef"],"Handoff writer-generation rotation"),r9(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),DC=E.object({ref:b("review"),pullRequestRef:b("pull_request"),base:Q_,head:Q_,reviewerRef:b("reviewer"),reviewRunRef:b("review_run"),proofBundleRef:b("proof_bundle"),verdict:E.enum(["approved","changes_requested","blocked"]),reviewedAt:V_}).strict(),UC=E.object({pullRequestRef:b("pull_request"),remoteBranchRef:b("branch"),expectedBase:Q_,providerPullRequestBase:Q_,localHead:Q_,remoteHead:Q_,providerPullRequestHead:Q_,equalityProofRef:b("proof_bundle"),ciProofBundleRefs:E.array(b("proof_bundle")).min(1),verifiedAt:V_}).strict().superRefine((_,$)=>{if(!e_(_.expectedBase,_.providerPullRequestBase))$.addIssue({code:E.ZodIssueCode.custom,message:"Expected and provider-observed pull-request bases must be exactly equal",path:["providerPullRequestBase"]});if(!e_(_.localHead,_.remoteHead)||!e_(_.localHead,_.providerPullRequestHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Local, remote, and provider pull-request heads must be exactly equal",path:["providerPullRequestHead"]});let g=_.ciProofBundleRefs.map(EN);if(new Set(g).size!==g.length)$.addIssue({code:E.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical identities",path:["ciProofBundleRefs"]});let U=_.ciProofBundleRefs.map((D)=>D.digest);if(new Set(U).size!==U.length)$.addIssue({code:E.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical digests",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((D)=>d3(D,_.equalityProofRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical identities",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((D)=>D.digest===_.equalityProofRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical digests",path:["ciProofBundleRefs"]})}),IC=E.object({ref:b("repair_cycle"),cycle:E.number().int().min(0).max(2),cap:E.literal(2),exhausted:E.boolean(),latestRepairRef:b("repair_cycle").optional()}).strict().superRefine((_,$)=>{if(_.exhausted!==(_.cycle===_.cap))$.addIssue({code:E.ZodIssueCode.custom,message:"Repair exhaustion must equal the cumulative cycle cap",path:["exhausted"]});if(_.cycle===0&&_.latestRepairRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Cycle zero cannot reference a repair",path:["latestRepairRef"]});if(_.cycle>0&&!_.latestRepairRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Non-zero repair state requires the latest immutable repair ref",path:["latestRepairRef"]});if(_.latestRepairRef&&d3(_.ref,_.latestRepairRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must be distinct canonical records",path:["latestRepairRef"]});if(_.latestRepairRef&&_.ref.digest===_.latestRepairRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must have distinct canonical digests",path:["latestRepairRef"]})}),jC=E.object({ref:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:Q_,expectedHead:Q_,reviewRefs:E.array(b("review")).min(1),proofBundleRefs:E.array(b("proof_bundle")).min(1),operatorRef:b("merge_operator"),operatorRunRef:b("merge_operator_run"),providerGuardReceiptRef:b("merge_guard_receipt"),mechanism:E.enum(["compare_and_swap","queue_expected_head"]),decision:E.enum(["eligible","denied","consumed","revoked"]),evaluatedAt:V_}).strict().superRefine((_,$)=>{if(new Set(_.reviewRefs.map((I)=>I.id)).size!==_.reviewRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard review refs must be unique",path:["reviewRefs"]});if(new Set(_.proofBundleRefs.map(EN)).size!==_.proofBundleRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical identities",path:["proofBundleRefs"]});if(new Set(_.proofBundleRefs.map((I)=>I.digest)).size!==_.proofBundleRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical digests",path:["proofBundleRefs"]})}),NC=E.object({ref:b("merge_outcome"),guardRef:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:Q_,observedBase:Q_,expectedHead:Q_,observedHead:Q_,status:E.enum(["merged","closed_unmerged","refused","head_drift","base_drift"]),mergeCommitRef:b("commit").optional(),finishedAt:V_,evidenceRefs:E.array(X$).min(1)}).strict().superRefine((_,$)=>{let g=e_(_.expectedBase,_.observedBase),U=e_(_.expectedHead,_.observedHead);if(_.status==="merged"){if(!g||!U)$.addIssue({code:E.ZodIssueCode.custom,message:"Merged outcomes require observed base and head to equal the guarded values",path:[!g?"observedBase":"observedHead"]});if(!_.mergeCommitRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Merged outcomes require an immutable merge commit ref",path:["mergeCommitRef"]})}else if(_.mergeCommitRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Unmerged outcomes cannot claim a merge commit",path:["mergeCommitRef"]});if(_.status==="head_drift"&&U)$.addIssue({code:E.ZodIssueCode.custom,message:"Head-drift outcomes require distinct expected and observed heads",path:["observedHead"]});if(_.status==="head_drift"&&!g)$.addIssue({code:E.ZodIssueCode.custom,message:"Head-drift outcomes cannot also carry an unclassified base drift",path:["observedBase"]});if(_.status==="base_drift"&&g)$.addIssue({code:E.ZodIssueCode.custom,message:"Base-drift outcomes require distinct expected and observed bases",path:["observedBase"]});if(_.status==="base_drift"&&!U)$.addIssue({code:E.ZodIssueCode.custom,message:"Base-drift outcomes cannot also carry an unclassified head drift",path:["observedHead"]});if(!U&&_.status!=="head_drift")$.addIssue({code:E.ZodIssueCode.custom,message:"Only a head_drift outcome may record an observed head that differs from the expected head",path:["observedHead"]});if(!g&&_.status!=="base_drift")$.addIssue({code:E.ZodIssueCode.custom,message:"Only a base_drift outcome may record an observed base that differs from the expected base",path:["observedBase"]})}),EC=E.object({guard:jC,outcome:NC.optional()}).strict(),OC=E.object({ref:b("recovery"),priorAttemptRef:b("attempt"),priorWriterGenerationRef:b("writer_generation"),priorWorkRunRef:b("work_run"),successorAttemptNonce:c3,successorWriterGenerationRef:b("writer_generation"),preservedStateRefs:E.array(n3).min(1),stopEvidenceRef:X$,leaseRevocationEvidenceRef:X$}).strict().superRefine((_,$)=>{Ng(_.priorWriterGenerationRef,_.successorWriterGenerationRef,$,["successorWriterGenerationRef"],"Recovery writer-generation rotation"),r9(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),AC=E.object({ref:b("cancellation"),cancelledAttemptRef:b("attempt"),preservedStateRefs:E.array(n3).min(1),evidenceRefs:E.array(X$).min(1)}).strict(),LC=E.object({ref:b("cleanup_eligibility"),status:E.enum(["not_ready","preserved","blocked","eligible"]),targetWorktreeRef:b("worktree"),eventCursorRef:b("replay_cursor"),terminalDispositionRef:b("terminal_disposition"),writerLeaseRef:b("writer_lease"),leaseRevocationEvidenceRef:X$,consumedEventEvidenceRef:X$,evaluatedAt:V_,evidenceRefs:E.array(X$).min(1)}).strict().superRefine((_,$)=>{if(_.leaseRevocationEvidenceRef.id===_.consumedEventEvidenceRef.id||_.leaseRevocationEvidenceRef.digest===_.consumedEventEvidenceRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup lease-revocation and consumed-event facts require distinct evidence identities and digests",path:["consumedEventEvidenceRef"]})}),JC=E.object({ref:b("cleanup_outcome"),eligibilityRef:b("cleanup_eligibility"),targetWorktreeRef:b("worktree"),status:E.enum(["preserved","deleted","failed","skipped"]),finishedAt:V_,evidenceRefs:E.array(X$).min(1)}).strict(),PC=E.object({eligibility:LC,outcome:JC.optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.eligibilityRef,_.eligibility.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup outcomes must bind the exact eligibility decision",path:["outcome","eligibilityRef"]});if(_.outcome&&!B_(_.outcome.targetWorktreeRef,_.eligibility.targetWorktreeRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility and outcome must bind the same target worktree",path:["outcome","targetWorktreeRef"]});if(_.outcome?.status==="deleted"&&_.eligibility.status!=="eligible")$.addIssue({code:E.ZodIssueCode.custom,message:"Deletion requires an eligible cleanup decision",path:["outcome","status"]})}),zC=E.object({plan:E.object({ref:b("rollback_plan"),targetRef:E.union([b("commit"),b("branch")]),createdAt:V_}).strict(),outcome:E.object({ref:b("rollback_outcome"),planRef:b("rollback_plan"),targetRef:E.union([b("commit"),b("branch")]),status:E.enum(["not_run","succeeded","failed","cancelled"]),finishedAt:V_,evidenceRefs:E.array(X$).min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.planRef,_.plan.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback plan",path:["outcome","planRef"]});if(_.outcome&&!B_(_.outcome.targetRef,_.plan.targetRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback target",path:["outcome","targetRef"]});if(_.outcome&&Date.parse(_.outcome.finishedAt)({category:"ci_proof",ref:$,base:_.exactHead.expectedBase,head:_.exactHead.localHead}))]:[],..._.reviews.flatMap(($)=>[{category:"review_proof",ref:$.proofBundleRef,base:$.base,head:$.head},{category:"review_record",ref:$.ref,base:$.base,head:$.head},{category:"review_run",ref:$.reviewRunRef,base:$.base,head:$.head}]),..._.merge?[{category:"merge_guard",ref:_.merge.guard.ref},{category:"provider_guard_receipt",ref:_.merge.guard.providerGuardReceiptRef,base:_.merge.guard.expectedBase,head:_.merge.guard.expectedHead}]:[],..._.cleanup?[{category:"cleanup_eligibility",ref:_.cleanup.eligibility.ref}]:[],..._.rollback?[{category:"rollback_plan",ref:_.rollback.plan.ref}]:[],..._.terminalDispositionRef?[{category:"terminal_disposition",ref:_.terminalDispositionRef}]:[]]}function XC(_,$){if(_.category!==$.category)return!1;if(_.category==="projection_id"&&$.category==="projection_id")return _.projectionId===$.projectionId;if(_.category==="attempt_nonce"&&$.category==="attempt_nonce")return _.nonce===$.nonce;if(_.category==="replay_prefix"&&$.category==="replay_prefix")return _.sequence===$.sequence&&_.prefixDigest===$.prefixDigest;if(!("ref"in _)||!("ref"in $))return!1;return B_(_.ref,$.ref)&&(("head"in _)&&("head"in $)&&("base"in _)&&("base"in $)&&e_(_.base,$.base)&&e_(_.head,$.head)||!("head"in _)&&!("head"in $)&&!("base"in _)&&!("base"in $))}var RC="hasna.task_to_pr_adapter_extension.",GC=E.object({mode:E.enum(["local","cloud"]),schema:w3,ref:b("adapter_extension"),digest:p4}).strict().superRefine((_,$)=>{if(!_.schema.startsWith(RC))$.addIssue({code:E.ZodIssueCode.custom,message:"Adapter extension schema ids must use the permanently reserved task-to-PR adapter-extension namespace",path:["schema"]})}),YC=E.enum(["admitted","running","handed_off","reviewing","repairing","merge_ready","merged","closed_unmerged","failed","blocked","cancelled","recovering","cleanup_complete","rolled_back"]),I9=new Set(["admitted","running","handed_off"]),j9=new Set(["merged","closed_unmerged","failed","blocked","cancelled","cleanup_complete","rolled_back"]),QC={admitted:new Set(["absent","denied:none","revoked:none"]),running:new Set(["absent","denied:none","revoked:none"]),handed_off:new Set(["absent","denied:none","revoked:none"]),reviewing:new Set(["absent","denied:none","revoked:none"]),repairing:new Set(["absent","denied:none","revoked:none"]),merge_ready:new Set(["eligible:none"]),merged:new Set(["consumed:merged"]),closed_unmerged:new Set(["consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),failed:new Set(["absent","revoked:none"]),blocked:new Set(["absent","revoked:none"]),cancelled:new Set(["absent","revoked:none"]),recovering:new Set(["absent","denied:none","revoked:none"]),cleanup_complete:new Set(["absent","revoked:none","consumed:merged","consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),rolled_back:new Set(["consumed:merged"])},TC=E.object({schema:E.literal(x.taskToPrProjection),id:C9,createdAt:V_,canonicalizationVersion:E.union([E.literal(1),E.literal(2)]),identityDigest:p4,frozenScopeDigest:p4,state:YC,workRunRef:b("work_run"),rootRequestRef:b("root_request"),prGroupRef:b("pr_group"),leafTaskRef:b("leaf_task"),attempt:sk,repository:_C,events:$C,openLoopsInvocationRef:b("openloops_invocation").optional(),pullRequestRef:b("pull_request").optional(),exactHead:UC.optional(),handoff:gC.optional(),reviews:E.array(DC).default([]),repair:IC,merge:EC.optional(),recovery:OC.optional(),cancellation:AC.optional(),cleanup:PC.optional(),rollback:zC.optional(),terminalDispositionRef:b("terminal_disposition").optional(),provenanceLedger:E.array(SC),adapterExtensions:E.array(GC).default([]),evidenceRefs:E.array(X$).default([])}).strict().superRefine((_,$)=>{let g=_.canonicalizationVersion===1?U9({canonicalizationVersion:1,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest}):U9({canonicalizationVersion:2,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,worktreeRef:_.repository.worktreeRef,branchRef:_.repository.branchRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest});if(_.identityDigest!==g)$.addIssue({code:E.ZodIssueCode.custom,message:"identityDigest must equal the selected v1 compatibility or v2 branch/worktree-bound canonical identity digest",path:["identityDigest"]});let U=new Set,D=new Set,I=new Set,j=new Set,N=new Set,O=new Set;for(let[T,q]of _.provenanceLedger.entries()){if("ref"in q){if(U.has(q.ref.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical owner id across categories or generations",path:["provenanceLedger",T,"ref","id"]});if(U.add(q.ref.id),D.has(q.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical digest across categories or generations",path:["provenanceLedger",T,"ref","digest"]});D.add(q.ref.digest);continue}if(q.category==="projection_id"){if(I.has(q.projectionId))$.addIssue({code:E.ZodIssueCode.custom,message:"Projection identity provenance tombstones must be globally unique",path:["provenanceLedger",T,"projectionId"]});I.add(q.projectionId);continue}if(q.category==="attempt_nonce"){if(j.has(q.nonce))$.addIssue({code:E.ZodIssueCode.custom,message:"Attempt nonce provenance tombstones must be globally unique",path:["provenanceLedger",T,"nonce"]});j.add(q.nonce);continue}if(N.has(q.prefixDigest))$.addIssue({code:E.ZodIssueCode.custom,message:"Replay prefix provenance tombstones must be globally unique",path:["provenanceLedger",T,"prefixDigest"]});if(N.add(q.prefixDigest),O.has(q.sequence))$.addIssue({code:E.ZodIssueCode.custom,message:"Replay prefix provenance entries must bind globally unique replay sequences",path:["provenanceLedger",T,"sequence"]});O.add(q.sequence)}for(let T of WC(_))if(!_.provenanceLedger.some((q)=>XC(q,T)))$.addIssue({code:E.ZodIssueCode.custom,message:`The active ${T.category} identity must be represented exactly in the monotonic provenance ledger`,path:["provenanceLedger"]});let A=[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repository.repoRef,_.repository.worktreeRef,_.repository.branchRef,_.events.streamRef,..._.pullRequestRef?[_.pullRequestRef]:[]],L=(T,q,V,Z)=>{let a=new Set(q.map((I_)=>I_.role)),D_=new Set;for(let[I_,J_]of T.entries()){if(!a.has(J_.role))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} cannot preserve an unrecognized ${J_.role} role`,path:[...V,I_]});if(D_.has(J_.role))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} must preserve exactly one canonical ref per role`,path:[...V,I_]});D_.add(J_.role)}if(T.length!==q.length)$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} preservation refs must exactly equal the required canonical role set`,path:V});for(let I_ of q)if(!T.some((J_)=>B_(J_,I_)))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} must preserve ${I_.role}`,path:V})};if(_.handoff&&!B_(_.handoff.nextWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Handoff next generation must be the current attempt writer generation",path:["handoff","nextWriterGenerationRef"]});if(_.handoff&&!B_(_.handoff.nextAttemptRef,_.attempt.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Handoff next attempt must be the current attempt",path:["handoff","nextAttemptRef"]});if(_.handoff)Ng(_.handoff.stoppedWorkRunRef,_.workRunRef,$,["handoff","stoppedWorkRunRef"],"Handoff WorkRun rotation");if(_.recovery){if(_.recovery.successorAttemptNonce!==_.attempt.nonce)$.addIssue({code:E.ZodIssueCode.custom,message:"Recovery successor nonce must equal the current attempt nonce",path:["recovery","successorAttemptNonce"]});if(!B_(_.recovery.successorWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Recovery successor generation must equal the current writer generation",path:["recovery","successorWriterGenerationRef"]});Ng(_.recovery.priorAttemptRef,_.attempt.ref,$,["recovery","priorAttemptRef"],"Recovery attempt rotation"),Ng(_.recovery.priorWorkRunRef,_.workRunRef,$,["recovery","priorWorkRunRef"],"Recovery WorkRun rotation"),L(_.recovery.preservedStateRefs,[_.recovery.priorWorkRunRef,...A],["recovery","preservedStateRefs"],"Recovery")}if(_.cancellation&&!B_(_.cancellation.cancelledAttemptRef,_.attempt.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Cancellation must bind the current attempt",path:["cancellation","cancelledAttemptRef"]});if(_.cancellation)L(_.cancellation.preservedStateRefs,[_.workRunRef,_.attempt.ref,...A],["cancellation","preservedStateRefs"],"Cancellation");if(_.cancellation&&_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"A projection cannot be both the cancellation and recovery snapshot",path:["recovery"]});if(_.handoff&&_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"A projection cannot be both the handoff and recovery snapshot",path:["recovery"]});if(_.cleanup&&!B_(_.cleanup.eligibility.eventCursorRef,_.events.replayCursorRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the current canonical replay cursor",path:["cleanup","eligibility","eventCursorRef"]});if(_.cleanup&&(!_.terminalDispositionRef||!B_(_.cleanup.eligibility.terminalDispositionRef,_.terminalDispositionRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact durable terminal owner fact",path:["cleanup","eligibility","terminalDispositionRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.writerLeaseRef,_.attempt.writerLeaseRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact writer lease being revoked",path:["cleanup","eligibility","writerLeaseRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.targetWorktreeRef,_.repository.worktreeRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the canonical worktree",path:["cleanup","eligibility","targetWorktreeRef"]});if(_.pullRequestRef){if(_.exactHead&&!B_(_.exactHead.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head proof must bind the canonical pull request ref",path:["exactHead","pullRequestRef"]});for(let[T,q]of _.reviews.entries())if(!B_(q.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Every review must bind the canonical pull request ref",path:["reviews",T,"pullRequestRef"]});if(_.merge&&!B_(_.merge.guard.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard must bind the canonical pull request ref",path:["merge","guard","pullRequestRef"]});if(_.merge?.outcome&&!B_(_.merge.outcome.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome must bind the canonical pull request ref",path:["merge","outcome","pullRequestRef"]})}else if(_.exactHead||_.reviews.length>0||_.merge)$.addIssue({code:E.ZodIssueCode.custom,message:"Review and merge state require a canonical pull request ref",path:["pullRequestRef"]});if(_.exactHead&&!e_(_.exactHead.localHead,_.repository.branchHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact local head must equal the canonical branch head",path:["exactHead","localHead"]});if(_.exactHead&&!e_(_.exactHead.expectedBase,_.repository.baseHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head expected base must equal the canonical repository base",path:["exactHead","expectedBase"]});if(_.exactHead&&!B_(_.exactHead.remoteBranchRef,_.repository.branchRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head remote branch ref must equal the canonical repository branch ref",path:["exactHead","remoteBranchRef"]});if(_.exactHead&&Date.parse(_.exactHead.verifiedAt)0&&!_.exactHead)$.addIssue({code:E.ZodIssueCode.custom,message:"Reviews require local/remote/provider exact-head proof",path:["exactHead"]});if(_.exactHead){let T=[{ref:_.exactHead.equalityProofRef,path:["exactHead","equalityProofRef"]},..._.exactHead.ciProofBundleRefs.map((Z,a)=>({ref:Z,path:["exactHead","ciProofBundleRefs",a]})),..._.reviews.map((Z,a)=>({ref:Z.proofBundleRef,path:["reviews",a,"proofBundleRef"]}))],q=new Set,V=new Set;for(let Z of T){let a=EN(Z.ref);if(q.has(a))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical identities",path:Z.path});if(q.add(a),V.has(Z.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical digests",path:Z.path});V.add(Z.ref.digest)}}let z=new Set,W=new Set,J=new Set,P=new Set,S=new Set,X=new Set,G=new Set,R=new Set;for(let[T,q]of _.reviews.entries()){if(!e_(q.base,_.repository.baseHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Review base must equal the exact canonical pull-request base",path:["reviews",T,"base"]});if(!e_(q.head,_.repository.branchHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Review head must equal the exact canonical branch head",path:["reviews",T,"head"]});for(let[Z,a,D_]of[[q.ref.id,z,"ref"],[q.reviewerRef.id,J,"reviewerRef"],[q.reviewRunRef.id,S,"reviewRunRef"]]){if(a.has(Z))$.addIssue({code:E.ZodIssueCode.custom,message:"Review, reviewer, and review-run refs must each be unique",path:["reviews",T,D_]});a.add(Z)}if(W.has(q.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review refs must resolve to distinct canonical record digests",path:["reviews",T,"ref"]});if(W.add(q.ref.digest),P.has(q.reviewerRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Reviewer refs must resolve to distinct canonical actor digests",path:["reviews",T,"reviewerRef"]});if(P.add(q.reviewerRef.digest),X.has(q.reviewRunRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review-run refs must resolve to distinct canonical run digests",path:["reviews",T,"reviewRunRef"]});X.add(q.reviewRunRef.digest);let V=EN(q.proofBundleRef);if(G.has(V))$.addIssue({code:E.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical identities",path:["reviews",T,"proofBundleRef"]});if(G.add(V),R.has(q.proofBundleRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical digests",path:["reviews",T,"proofBundleRef"]});if(R.add(q.proofBundleRef.digest),q.reviewerRef.digest===_.attempt.workerRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Worker and reviewer identities must resolve to distinct canonical digests",path:["reviews",T,"reviewerRef"]});if(q.reviewRunRef.digest===_.attempt.runtimeRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Worker runtime and review run must resolve to distinct canonical digests",path:["reviews",T,"reviewRunRef"]});if(_.exactHead&&Date.parse(q.reviewedAt)Date.parse(_.merge.guard.evaluatedAt)T.verdict!=="approved"))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards require at least one review and all reviews approved",path:["merge","guard","decision"]});if(_.merge.guard.reviewRefs.length!==_.reviews.length||_.merge.guard.reviewRefs.some((T)=>!_.reviews.some((q)=>B_(T,q.ref))))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guard review refs must exactly equal the projected approved review refs as a canonical set",path:["merge","guard","reviewRefs"]});for(let T of _.reviews)if(!_.merge.guard.proofBundleRefs.some((q)=>B_(q,T.proofBundleRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact review proof bundle",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&!_.merge.guard.proofBundleRefs.some((T)=>B_(T,_.exactHead.equalityProofRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind the exact-head equality proof",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&_.exactHead.ciProofBundleRefs.some((T)=>!_.merge.guard.proofBundleRefs.some((q)=>B_(q,T))))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact-head CI proof",path:["merge","guard","proofBundleRefs"]})}}if(_.merge?.outcome){if(!B_(_.merge.outcome.guardRef,_.merge.guard.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome must bind the exact immutable merge guard",path:["merge","outcome","guardRef"]});if(!e_(_.merge.outcome.expectedHead,_.merge.guard.expectedHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome expected head must equal the guarded expected head",path:["merge","outcome","expectedHead"]});if(!e_(_.merge.outcome.expectedBase,_.merge.guard.expectedBase))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome expected base must equal the guarded expected base",path:["merge","outcome","expectedBase"]});if(_.merge.guard.decision!=="consumed")$.addIssue({code:E.ZodIssueCode.custom,message:"Every merge outcome requires an explicitly consumed merge guard",path:["merge","guard","decision"]});if(Date.parse(_.merge.outcome.finishedAt)0)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot carry review bindings before review authority is active`,path:["reviews"]});if((I9.has(_.state)||_.state==="recovering")&&(_.merge?.guard.reviewRefs.length??0)>0)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot hide review bindings in a merge guard before review authority is active`,path:["merge","guard","reviewRefs"]});let K=_.merge?`${_.merge.guard.decision}:${_.merge.outcome?.status??"none"}`:"absent";if(!QC[_.state].has(K))$.addIssue({code:E.ZodIssueCode.custom,message:`State ${_.state} is incompatible with merge authority ${K}`,path:["merge"]});if(j9.has(_.state)&&!_.terminalDispositionRef)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections require a durable Todos terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(!j9.has(_.state)&&_.terminalDispositionRef)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot carry a terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(_.state==="reviewing"&&_.reviews.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Reviewing projections require review refs",path:["reviews"]});if(_.state==="cancelled"&&!_.cancellation)$.addIssue({code:E.ZodIssueCode.custom,message:"Cancelled projections require preservation state",path:["cancellation"]});if(_.cancellation&&_.merge?.outcome)$.addIssue({code:E.ZodIssueCode.custom,message:"Cancellation cannot coexist with a terminal merge outcome",path:["cancellation"]});if(_.state==="recovering"&&!_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"Recovering projections require recovery state",path:["recovery"]});if(_.state==="repairing"&&_.repair.cycle===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Repairing projections require a non-zero repair cycle",path:["repair","cycle"]});if(_.merge&&(_.merge.guard.decision==="eligible"||_.merge.guard.decision==="consumed")&&!B_(_.attempt.admissionWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge eligibility requires admission from the current writer generation",path:["attempt","admissionWriterGenerationRef"]});if(_.state==="merge_ready"&&_.merge?.guard.decision!=="eligible")$.addIssue({code:E.ZodIssueCode.custom,message:"Merge-ready projections require an eligible guard",path:["merge"]});if(_.state==="merged"&&_.merge?.outcome?.status!=="merged")$.addIssue({code:E.ZodIssueCode.custom,message:"Merged projections require a merged immutable outcome",path:["merge"]});if(_.state==="closed_unmerged"&&!_.merge?.outcome?.status.match(/^(closed_unmerged|refused|head_drift|base_drift)$/))$.addIssue({code:E.ZodIssueCode.custom,message:"Closed-unmerged projections require a non-merged terminal outcome",path:["merge"]});if(_.state==="cleanup_complete"&&(!_.cleanup?.outcome||!["deleted","preserved","skipped"].includes(_.cleanup.outcome.status)))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup-complete projections require an immutable cleanup outcome",path:["cleanup"]});if(_.state==="rolled_back"&&_.rollback?.outcome?.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Rolled-back projections require a successful rollback outcome",path:["rollback"]});if((_.state==="failed"||_.state==="blocked")&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed and blocked projections require redacted evidence refs",path:["evidenceRefs"]});if(["admitted","running","handed_off","reviewing","repairing","merge_ready","recovering"].includes(_.state)&&(_.merge?.outcome||_.cancellation||_.cleanup?.outcome||_.rollback?.outcome))$.addIssue({code:E.ZodIssueCode.custom,message:"Non-terminal projections cannot carry terminal owner outcomes",path:["state"]});let Q=new Set;for(let[T,q]of _.adapterExtensions.entries()){let V=`${q.mode}:${q.schema}`;if(Q.has(V))$.addIssue({code:E.ZodIssueCode.custom,message:"Adapter extensions must be unique per local/cloud mode and schema",path:["adapterExtensions",T]});Q.add(V)}});var qC=E.object({id:E.string().min(1),at:V_,kind:E.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:E.string().min(1),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),costEstimate:YU.optional()}).strict(),BC=L_(x.agentTrajectory).extend({actor:m$,workRunRef:s.optional(),events:E.array(qC).default([]),outcome:E.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:s.optional()}).strict(),KC="v1",VC=E.enum(["library","cli-with-store","service","saas"]),FC=["user-hosted","hasna-saas"],MC=E.enum(FC),ZC=["api","sdk","mcp","cli"],v9=E.enum(ZC),bC=E.enum(["supported","deferred","unsupported"]),HC=E.enum(["none","local-only","api-key","session","service-token","custom"]),H3=E.object({method:E.enum(["GET","POST","PUT","PATCH","DELETE"]),path:E.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:E.boolean().default(!1),description:E.string().min(1).optional()}).strict(),kC=E.object({id:E.string().min(1),kind:E.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:E.boolean().default(!0),command:E.string().min(1).optional(),evidenceRef:T_.optional(),status:E.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:E.string().min(1).optional()}).strict().superRefine((_,$)=>{if((_.status==="passed"||_.status==="failed"||_.status==="blocked")&&!_.command&&!_.evidenceRef&&!_.summary)$.addIssue({code:E.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),CC=E.object({name:E.string().min(1),kind:v9.optional(),status:bC,bin:E.string().min(1).optional(),mcpBin:E.string().min(1).optional(),authMode:HC,health:H3.optional(),readiness:H3.optional(),version:H3.optional(),apiBasePath:E.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:E.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),exportSubpath:E.string().regex(/^\.(?:\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*)?$/,"SDK export subpaths must be package export keys such as . or ./sdk").optional(),generatedFrom:E.string().regex(/^\/[A-Za-z0-9_./:-]*$/,"SDK generatedFrom must reference an absolute OpenAPI path").optional(),clientClassName:E.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).optional(),deferReason:E.string().min(1).optional(),readinessGates:E.array(kC).default([])}).strict().superRefine((_,$)=>{if(_.status==="supported"){if(!_.kind||_.kind==="api"){if(!_.bin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a serve bin",path:["bin"]});if(!_.health)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a health endpoint",path:["health"]});if(!_.readiness)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a readiness endpoint",path:["readiness"]});if(!_.version)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a version endpoint",path:["version"]})}if(_.kind==="cli"&&!_.bin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported CLI surfaces require a bin",path:["bin"]});if(_.kind==="mcp"&&!_.mcpBin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported MCP surfaces require an mcpBin",path:["mcpBin"]});if(_.kind==="sdk"&&!_.exportSubpath)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported SDK surfaces require an exportSubpath",path:["exportSubpath"]})}if((_.status==="deferred"||_.status==="unsupported")&&!_.deferReason)$.addIssue({code:E.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if(_.health&&_.health.path!=="/health")$.addIssue({code:E.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if(_.health&&_.health.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Health endpoint must use GET",path:["health","method"]});if(_.readiness&&_.readiness.path!=="/ready")$.addIssue({code:E.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if(_.readiness&&_.readiness.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Readiness endpoint must use GET",path:["readiness","method"]});if(_.version&&_.version.path!=="/version")$.addIssue({code:E.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]});if(_.version&&_.version.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Version endpoint must use GET",path:["version","method"]})}),rC=["sqlite","postgres"],f9=E.enum(rC),w9=["sqlite","postgres"],vC=E.enum(w9),f3=["postgres"],fC=E.object({kind:v9,reason:E.string().trim().min(1)}).strict(),m3=500,i3=200,ON=(_)=>E.string().trim().min(1).max(_).regex(/^[^\u0000-\u001f\u007f]+$/,"Waiver text must not contain control characters"),wC=["domain","host","ip","email"],uC=E.object({kind:E.enum(wC),reason:ON(m3),reviewedBy:ON(i3),expiresAt:V_}).strict(),xC=E.object({engine:E.enum(f3),reason:ON(m3),reviewedBy:ON(i3).optional(),expiresAt:V_.optional()}).strict();function yC(_){if(_.class!=="cli-with-store")return`storage waivers are not permitted for class ${_.class}`;if(_.bins.includes(`${_.name}-serve`))return`storage waivers are not permitted for a service-capable cli-with-store repo shipping ${_.name}-serve`;if(_.storageMode==="postgres")return"storage waivers are not permitted while storage.mode is postgres, which reads and writes PostgreSQL directly";if(_.hosting.includes("hasna-saas"))return"storage waivers are not permitted for a repo declaring the hasna-saas product story";return null}var hC=E.object({conformance:E.object({waivedSurfaces:E.array(fC).default([]),waiverProfile:E.literal("non-node-monorepo").optional(),waivedStorageEngines:E.array(xC).default([]),waivedAssetInventories:E.array(uC).default([])}).catchall(E.unknown()).optional(),release:E.object({artifactScan:E.object({script:E.string().trim().min(1)}).strict().optional()}).catchall(E.unknown()).optional()}).catchall(E.unknown()),cC=E.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),nC=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function dC(_){return nC.map(($)=>`${_}${$}`)}function N9(_){return`hasna/oss/${_}/database-url`}var mC=E.object({mode:f9,engines:E.array(vC).min(1).optional(),envPrefix:E.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:E.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:E.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:E.string().min(1).endsWith(".db","storage.sqlitePath must end in .db").optional(),pgTestGate:E.object({envVar:E.string().regex(/^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$/),command:E.string().trim().min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.engines&&new Set(_.engines).size!==_.engines.length)$.addIssue({code:E.ZodIssueCode.custom,message:"storage.engines must not contain duplicates",path:["engines"]});if(_.engines?.includes("postgres")&&!_.envPrefix)$.addIssue({code:E.ZodIssueCode.custom,message:"storage.engines containing postgres requires envPrefix for the HASNA__DATABASE_URL contract",path:["envPrefix"]})}),u9=E.enum(["0600"]),x9=E.enum(["0700"]),y9=E.enum([".hasna",".codewith"]),iC=E.enum(["directory","file","sqlite_db","sqlite_wal","sqlite_shm","backup","export","report","tmp","log","session","snapshot"]),Ug=W$.refine((_)=>!_.startsWith("~"),"Local store path patterns must be relative to their declared root"),lC=E.object({id:E.string().min(1),source:E.enum(["sqlite","manifest","index","runtime","package_adapter"]),table:E.string().min(1).optional(),column:E.string().min(1).optional(),description:E.string().min(1),required:E.boolean().default(!0)}).strict(),tC=E.object({safeWhen:E.enum(["exclusive_access","offline_only","never"]),operations:E.array(E.enum(["wal_checkpoint_truncate","incremental_vacuum","optimize","vacuum"])).default([])}).strict().superRefine((_,$)=>{if(_.safeWhen==="never"&&_.operations.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"sqliteMaintenance.safeWhen=never cannot declare operations",path:["operations"]})}),oC=E.object({id:E.string().min(1),description:E.string().min(1),ttlDays:E.number().int().nonnegative().optional(),artifactClasses:E.array(iC).min(1),allowlistGlobs:E.array(Ug).min(1),activeRecordExclusions:E.array(lC).default([]),sqliteMaintenance:tC.optional()}).strict(),pC=E.object({storeId:E.string().regex(/^[a-z][a-z0-9-]*$/),packageName:E.string().min(1),displayName:E.string().min(1),root:y9,relativePath:Ug,directoryMode:x9.default("0700"),fileMode:u9.default("0600"),sqliteDatabaseGlobs:E.array(Ug).default([]),sensitiveFileGlobs:E.array(Ug).default([]),backupGlobs:E.array(Ug).default([]),exportGlobs:E.array(Ug).default([]),retentionAdapters:E.array(oC).default([]),notes:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{if(_.relativePath.includes("*"))$.addIssue({code:E.ZodIssueCode.custom,message:"store relativePath must be a concrete directory; use glob fields for files",path:["relativePath"]});let g=new Set;for(let[U,D]of _.retentionAdapters.entries()){if(g.has(D.id))$.addIssue({code:E.ZodIssueCode.custom,message:"retention adapter ids must be unique within a store",path:["retentionAdapters",U,"id"]});g.add(D.id)}}),h9=L_(x.secureLocalStorePolicy).extend({version:E.string().min(1),scope:E.array(y9).min(1),defaults:E.object({directoryMode:x9.default("0700"),fileMode:u9.default("0600"),dryRunDefault:E.literal(!0),requireExplicitApply:E.literal(!0),includeSqliteSidecars:E.literal(!0),redactedEvidenceOnly:E.literal(!0)}).strict(),stores:E.array(pC).min(1),lifecycle:E.object({retentionDryRunDefault:E.literal(!0),requireActiveRecordExclusionProof:E.literal(!0),requireArtifactAllowlist:E.literal(!0),sqliteMaintenanceRequiresExclusiveAccess:E.literal(!0)}).strict(),warnings:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{let g=new Set;for(let[U,D]of _.stores.entries()){if(g.has(D.storeId))$.addIssue({code:E.ZodIssueCode.custom,message:"store ids must be unique",path:["stores",U,"storeId"]});if(g.add(D.storeId),!_.scope.includes(D.root))$.addIssue({code:E.ZodIssueCode.custom,message:"store root must be listed in policy scope",path:["stores",U,"root"]})}}),eC=E.object({$schema:E.string().min(1).optional(),schema:E.literal(x.serviceContract),name:cC,class:VC,contractVersion:E.literal(KC),kitVersion:E.string().min(1),description:E.string().min(1).optional(),bins:E.array(E.string().min(1)).default([]),storage:mC.optional(),hosting:E.array(MC).min(1).default(["user-hosted"]),serviceSurfaces:E.array(CC).default([]),metadata:hC.optional()}).strict().superRefine((_,$)=>{if(new Set(_.hosting).size!==_.hosting.length)$.addIssue({code:E.ZodIssueCode.custom,message:"hosting must not contain duplicates",path:["hosting"]});let g=new Set(dC(_.name)),U=new Set;for(let[A,L]of _.bins.entries()){if(U.has(L))$.addIssue({code:E.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",A]});if(U.add(L),!g.has(L))$.addIssue({code:E.ZodIssueCode.custom,message:`Bin "${L}" is not allowlisted for app "${_.name}"; allowed: ${[...g].join(", ")}`,path:["bins",A]})}let D=(A)=>U.has(`${_.name}${A}`);if(_.storage){let A=_.name.toUpperCase().replace(/-/g,"_");if(_.storage.envPrefix&&_.storage.envPrefix!==`HASNA_${A}_`)$.addIssue({code:E.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${A}_`,path:["storage","envPrefix"]});if(_.storage.databaseUrlSecretRef&&_.storage.databaseUrlSecretRef!==N9(_.name))$.addIssue({code:E.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${N9(_.name)}`,path:["storage","databaseUrlSecretRef"]})}if(_.class==="library"){if(_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(D("-serve")||D("-mcp"))$.addIssue({code:E.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if(_.class==="cli-with-store"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else{if(_.storage.mode==="sqlite"&&!_.storage.sqlitePath)$.addIssue({code:E.ZodIssueCode.custom,message:"sqlite cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(_.storage.engines){let A=new Set(_.storage.engines),L=_.metadata?.conformance?.waivedStorageEngines??[],z=yC({class:_.class,name:_.name,bins:_.bins,hosting:_.hosting,storageMode:_.storage.mode}),W=new Set(z?[]:L.map((P)=>P.engine)),J=w9.filter((P)=>!A.has(P)&&!W.has(P));if(J.length>0){let P=z&&L.length>0?`; declared waiver ignored: ${z}`:"";$.addIssue({code:E.ZodIssueCode.custom,message:`cli-with-store storage.engines must declare both sqlite and postgres unless the engine carries a metadata.conformance.waivedStorageEngines waiver; missing: ${J.join(", ")}${P}`,path:["storage","engines"]})}}}if(!U.has(_.name))$.addIssue({code:E.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${_.name}" bin`,path:["bins"]})}if(_.class==="service"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});else if(_.storage.engines&&(!_.storage.engines.includes("sqlite")||!_.storage.engines.includes("postgres")))$.addIssue({code:E.ZodIssueCode.custom,message:"service storage.engines must declare both sqlite and postgres",path:["storage","engines"]});if(!D("-serve"))$.addIssue({code:E.ZodIssueCode.custom,message:`service repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if(_.class==="saas"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else{if(_.storage.mode!=="postgres")$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must use the postgres storage backend",path:["storage","mode"]});if(!_.storage.envPrefix)$.addIssue({code:E.ZodIssueCode.custom,message:"saas storage requires envPrefix for the public DATABASE_URL contract",path:["storage","envPrefix"]})}if(!D("-serve"))$.addIssue({code:E.ZodIssueCode.custom,message:`saas repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[A,L]of _.serviceSurfaces.entries()){if(L.bin&&!U.has(L.bin))$.addIssue({code:E.ZodIssueCode.custom,message:`Service surface bin "${L.bin}" must be declared in bins`,path:["serviceSurfaces",A,"bin"]});if(L.mcpBin&&!U.has(L.mcpBin))$.addIssue({code:E.ZodIssueCode.custom,message:`Service surface MCP bin "${L.mcpBin}" must be declared in bins`,path:["serviceSurfaces",A,"mcpBin"]})}let I=_.metadata?.conformance?.waivedSurfaces??[],j=new Set;for(let[A,L]of I.entries()){if(j.has(L.kind))$.addIssue({code:E.ZodIssueCode.custom,message:`Duplicate conformance waiver for ${L.kind}`,path:["metadata","conformance","waivedSurfaces",A,"kind"]});j.add(L.kind)}let N=_.metadata?.conformance?.waivedStorageEngines??[],O=new Set;for(let[A,L]of N.entries()){if(O.has(L.engine))$.addIssue({code:E.ZodIssueCode.custom,message:`Duplicate storage-engine waiver for ${L.engine}`,path:["metadata","conformance","waivedStorageEngines",A,"engine"]});O.add(L.engine)}}),Nd=E.object({status:E.enum(["ok","degraded","unavailable"]),version:E.string().min(1),mode:f9}).strict(),Ed=E.object({ready:E.boolean(),reason:E.string().min(1).optional()}).strict(),Od=E.object({version:E.string().min(1)}).strict(),aC=E.enum(["info","notice","breaking","critical"]),sC=E.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),_r=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],$r=E.enum(_r);var gr=E.enum(["fleet","package","machine"]),c9=L_(x.commsEventEnvelope).extend({type:sC,severity:aC,scope:gr,summary:E.string().min(1).optional(),source:m$.optional(),affected_packages:E.array(t).default([]),affected_machines:E.array(t).default([]),action_required:E.boolean().default(!1),ack_by:V_.optional(),dedupe_key:t,resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.scope==="package"&&_.affected_packages.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if(_.scope==="machine"&&_.affected_machines.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if(_.ack_by&&!_.action_required)$.addIssue({code:E.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if(_.type==="fleet.freeze"||_.type==="fleet.unfreeze"){if(_.severity!=="critical")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events are always critical`,path:["severity"]});if(_.scope!=="fleet")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events are always fleet-scoped`,path:["scope"]});if(!_.action_required)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events require action_required`,path:["action_required"]})}}),Dr=E.enum(["fleet","package","product","loop-lane","initiative","personal"]),Ur=E.enum(["quiet","work","firehose"]),Ir=t.refine((_)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(_),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),jr=L_(x.commsChannelMetadata).extend({class:Dr,noise:Ur.optional(),owner:t.optional(),until:Ir.optional(),successor:t.optional()}).strict().superRefine((_,$)=>{if(_.class==="initiative"){if(!_.owner)$.addIssue({code:E.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!_.until)$.addIssue({code:E.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),E9={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},Nr=L_(x.commsMessageMetadata).extend({tag:$r,envelope:c9}).strict().superRefine((_,$)=>{let g=E9[_.tag];if(!g.allowedSeverities.includes(_.envelope.severity))$.addIssue({code:E.ZodIssueCode.custom,message:`[${_.tag}] posts allow severities ${g.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(g.requiredEventType&&_.envelope.type!==g.requiredEventType)$.addIssue({code:E.ZodIssueCode.custom,message:`[${_.tag}] posts require event type ${g.requiredEventType}`,path:["envelope","type"]});for(let[U,D]of Object.entries(E9))if(D.requiredEventType===_.envelope.type&&_.tag!==U)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var Er={[x.actorRef]:CH,[x.resourceRef]:rH,[x.evidenceRef]:fH,[x.workRun]:ik,[x.taskToPrProjection]:TC,[x.decisionEnvelope]:q9,[x.costEstimate]:YU,[x.capabilityCard]:uH,[x.providerLiveModeStandard]:dH,[x.contextPack]:B9,[x.integrationRef]:K9,[x.projectManifest]:oH,[x.projectPanel]:V9,[x.projectSnapshot]:Ik,[x.renderManifest]:sH,[x.agentTrajectory]:BC,[x.validationPlan]:jk,[x.proofBundle]:mk,[x.scaffoldManifest]:Pk,[x.scaffoldInstallRecord]:Sk,[x.appCloudManifest]:Z9,[x.noCloudEvidencePack]:nk,[x.secureLocalStorePolicy]:h9,[x.serviceContract]:eC,[x.commsEventEnvelope]:c9,[x.commsChannelMetadata]:jr,[x.commsMessageMetadata]:Nr,[x.app]:qk,[x.release]:Kk,[x.rolloutRecord]:Mk,[x.announcement]:kk,[x.audience]:uk};class n9 extends Error{schemaId;issues;constructor(_,$){super(`Contract validation failed for ${_}`);this.name="ContractValidationError",this.schemaId=_,this.issues=$}}function d9(_,$){let U=Er[_].safeParse($);if(!U.success)throw new n9(_,U.error.issues);return U.data}var Ad=String.raw`(?:^|[^\w$])(?:_*(?:import|require)|createRequire|Module\s*\.\s*_load)`;var l3=[{pattern:"@hasna/cloud",kind:"module",message:"Shared @hasna/cloud runtime reference is forbidden"},{pattern:"open-cloud",kind:"module",message:"Shared open-cloud runtime reference is forbidden"},{pattern:"cloud-mcp",kind:"module",message:"Legacy cloud-mcp runtime surface is forbidden"},{pattern:"registerCloudTools",kind:"symbol",message:"Legacy registerCloudTools runtime surface is forbidden"},{pattern:"registerCloudCommands",kind:"symbol",message:"Legacy registerCloudCommands runtime surface is forbidden"},{pattern:".hasna/cloud",kind:"config",checkKind:"runtime_config",message:"Legacy .hasna/cloud runtime config is forbidden"},{pattern:"HASNA_CLOUD_",kind:"config",message:"Shared HASNA_CLOUD_* runtime config is forbidden"},{pattern:"HASNA_RDS_PASSWORD",kind:"config",message:"Legacy shared RDS credential config is forbidden"}],Ld=l3.filter((_)=>("checkKind"in _)),Or=l3.filter((_)=>_.kind==="module"),Jd=[...new Set([...IN,...Or.map((_)=>_.pattern)])],Pd=l3.filter((_)=>_.kind==="config");var O9="^[^\\u0000-\\u001f\\u007f]*$",zd={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/hasna/contracts/schema/hasna.service_contract.v1.json",title:"Hasna Service Contract v1",description:"Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Hosting story, product surfaces, and storage capabilities are separate declarations; the storage backend (sqlite | postgres) is the only runtime switch.",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],allOf:[{if:{required:["class"],properties:{class:{const:"saas"}}},then:{required:["storage"],properties:{storage:{required:["mode","envPrefix"],properties:{mode:{const:"postgres"}}}}}}],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:x.serviceContract},name:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",description:"Lowercase dashed app short-name, e.g. todos, mailery, loops."},class:{enum:["library","cli-with-store","service","saas"]},contractVersion:{const:"v1"},kitVersion:{type:"string",minLength:1,description:"Version of @hasna/contracts (the contract kit) the repo tracks."},description:{type:"string",minLength:1},bins:{type:"array",items:{type:"string",minLength:1},description:"Declared bins. Allowlisted: , -cli, -mcp, -serve, -worker, -runner, -daemon, -migrate, -doctor."},hosting:{type:"array",items:{enum:["user-hosted","hasna-saas"]},minItems:1,uniqueItems:!0,description:"Customer-facing product stories. Public OSS cores include user-hosted; add hasna-saas only when a managed control plane exists."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode"],allOf:[{if:{required:["status"],properties:{status:{const:"supported"},kind:{const:"api"}}},then:{required:["bin","health","readiness","version"]}}],properties:{name:{type:"string",minLength:1},kind:{enum:["api","sdk","mcp","cli"]},status:{enum:["supported","deferred","unsupported"]},bin:{type:"string",minLength:1},mcpBin:{type:"string",minLength:1},authMode:{enum:["none","local-only","api-key","session","service-token","custom"]},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},readiness:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},version:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},apiBasePath:{type:"string",pattern:"^/v[0-9]+$"},openApiPath:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$"},exportSubpath:{type:"string",pattern:"^\\.(?:\\/[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)*)?$",description:"SDK package export key such as . or ./sdk."},generatedFrom:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$",description:"OpenAPI path used to generate the SDK."},clientClassName:{type:"string",pattern:"^[A-Za-z_$][A-Za-z0-9_$]*$"},deferReason:{type:"string",minLength:1},readinessGates:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1},kind:{enum:["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]},required:{type:"boolean"},command:{type:"string",minLength:1},evidenceRef:{type:"object"},status:{enum:["pending","passed","failed","blocked","deferred"]},summary:{type:"string",minLength:1}}}}}},description:"Declared API, SDK, MCP, and CLI product surfaces. Legacy entries without kind remain parseable; new manifests declare kind explicitly."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["sqlite","postgres"],description:"Active data backend. sqlite|postgres ONLY \u2014 the single runtime switch."},engines:{type:"array",items:{enum:["sqlite","postgres"]},minItems:1,uniqueItems:!0,description:"Supported storage engines; capability metadata independent of the active backend."},envPrefix:{type:"string",pattern:"^HASNA_[A-Z][A-Z0-9]*_$",description:"Primary env prefix, e.g. HASNA_TODOS_."},aliasEnvPrefix:{type:"string",pattern:"^[A-Z][A-Z0-9]*_$",description:"Optional short alias env prefix, e.g. TODOS_."},databaseUrlSecretRef:{type:"string",pattern:"^hasna/oss/[a-z0-9-]+/database-url$",description:"Legacy/private-tier database secret ref. Public conformance rejects this field."},sqlitePath:{type:"string",pattern:"\\.db$",description:"Local sqlite path (~/.hasna//.db)."},pgTestGate:{type:"object",additionalProperties:!1,required:["envVar","command"],properties:{envVar:{type:"string",pattern:"^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$"},command:{type:"string",minLength:1}},description:"Environment-gated live PostgreSQL test command."}}},metadata:{type:"object",additionalProperties:!0,properties:{conformance:{type:"object",additionalProperties:!0,properties:{waiverProfile:{const:"non-node-monorepo",description:"Explicit surface-waiver eligibility for exceptional non-Node monorepos. Libraries are eligible for API/MCP waivers without this profile."},waivedSurfaces:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["kind","reason"],properties:{kind:{enum:["api","sdk","mcp","cli"]},reason:{type:"string",minLength:1}}}},waivedStorageEngines:{type:"array",uniqueItems:!0,maxItems:f3.length,items:{type:"object",additionalProperties:!1,required:["engine","reason"],properties:{engine:{enum:[...f3]},reason:{type:"string",minLength:1,maxLength:m3,allOf:[{pattern:"\\S"},{pattern:O9}]},reviewedBy:{type:"string",minLength:1,maxLength:i3,allOf:[{pattern:"\\S"},{pattern:O9}]},expiresAt:{type:"string",format:"date-time"}}},description:"Explicit storage-engine exceptions, at most one per engine. Only a CLI-only cli-with-store repo (no -serve bin, storage.mode sqlite, no hasna-saas story) may waive postgres; sqlite is never waivable, expiresAt is a UTC RFC 3339 timestamp, and conformance stops honouring a waiver once it has passed."}}}}}}};var Ar="2026-07-06";function c$(_,$,g,U,D,I=[],j){return{id:_,description:$,ttlDays:g,artifactClasses:U,allowlistGlobs:D,activeRecordExclusions:I.map((N)=>({...N,required:N.required??!0})),sqliteMaintenance:j}}var Sd=h9.parse({schema:x.secureLocalStorePolicy,id:"hasna-secure-local-store-defaults",createdAt:"2026-07-06T00:00:00.000Z",version:Ar,scope:[".hasna",".codewith"],defaults:{directoryMode:"0700",fileMode:"0600",dryRunDefault:!0,requireExplicitApply:!0,includeSqliteSidecars:!0,redactedEvidenceOnly:!0},lifecycle:{retentionDryRunDefault:!0,requireActiveRecordExclusionProof:!0,requireArtifactAllowlist:!0,sqliteMaintenanceRequiresExclusiveAccess:!0},stores:[{storeId:"codewith",packageName:"codewith",displayName:"Codewith native state",root:".codewith",relativePath:".",sqliteDatabaseGlobs:["logs_*.sqlite","state_*.sqlite","goals_*.sqlite"],sensitiveFileGlobs:["sessions/**/*.jsonl","shell_snapshots/**/*","logs*.sqlite","state*.sqlite","goals*.sqlite"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("codewith-session-snapshots","Codewith sessions, shell snapshots, logs, monitor output, mailbox payloads, and scheduler state need package-owned redaction before retention applies.",30,["session","snapshot","log"],["sessions/**/*.jsonl","shell_snapshots/**/*","logs/**/*"],[{id:"codewith-active-session",source:"package_adapter",description:"Exclude currently active sessions, leased schedules, monitors, pending interactions, and active goal rows."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})],notes:["Includes native .codewith DBs and transcript-like artifacts; redaction-before-persistence remains package-owned."]},{storeId:"todos",packageName:"@hasna/todos",displayName:"Todos",root:".hasna",relativePath:"todos",sqliteDatabaseGlobs:["todos.db"],sensitiveFileGlobs:["todos.db","todos.db-wal","todos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak","*.backup"],exportGlobs:["exports/**/*","*.jsonl","*.csv"],retentionAdapters:[c$("todos-exports-backups","Todos backups and exports are deleted only after package redaction and active task/evidence references are excluded.",14,["backup","export"],["backups/**/*","exports/**/*"],[{id:"todos-active-evidence",source:"sqlite",table:"task_files",column:"path",description:"Exclude files still referenced by active tasks, verification evidence, task comments, or handoff records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"conversations",packageName:"@hasna/conversations",displayName:"Conversations",root:".hasna",relativePath:"conversations",sqliteDatabaseGlobs:["messages.db"],sensitiveFileGlobs:["messages.db","messages.db-wal","messages.db-shm","exports/**/*","attachments/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*","*.json","*.csv"],retentionAdapters:[c$("conversations-exports-attachments","Conversation exports and attachments require message-id redaction and active attachment reference checks before deletion.",14,["export","backup"],["exports/**/*","backups/**/*","attachments/**/*"],[{id:"conversations-active-attachments",source:"sqlite",table:"messages",column:"attachments",description:"Exclude attachments still referenced by retained messages or audited redaction records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"mementos",packageName:"@hasna/mementos",displayName:"Mementos",root:".hasna",relativePath:"mementos",sqliteDatabaseGlobs:["mementos.db"],sensitiveFileGlobs:["mementos.db","mementos.db-wal","mementos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("mementos-audit-search-history","Mementos retention must preserve active memory versions while compacting audit/search surfaces through package-owned adapters.",30,["backup","export","log"],["backups/**/*","exports/**/*","audit/**/*"],[{id:"mementos-active-memory-versions",source:"sqlite",table:"memory_versions",column:"memory_id",description:"Exclude current memory versions and audit entries required for provenance."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"knowledge",packageName:"@hasna/knowledge",displayName:"Knowledge",root:".hasna",relativePath:"knowledge",sqliteDatabaseGlobs:["knowledge.db"],sensitiveFileGlobs:["knowledge.db","knowledge.db-wal","knowledge.db-shm","db.json","migration-exports/**/*","*.bak"],backupGlobs:["*.bak","backups/**/*","*.pre-cloud-*"],exportGlobs:["migration-exports/**/*","exports/**/*","*.jsonl"],retentionAdapters:[c$("knowledge-migrations-exports","Knowledge migration exports and pre-cloud backups require replacement, encryption, or redaction before retention deletion.",14,["backup","export"],["migration-exports/**/*","exports/**/*","*.bak","*.pre-cloud-*"],[{id:"knowledge-current-catalog",source:"manifest",description:"Exclude files referenced by the active catalog or migration ledger."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"projects",packageName:"@hasna/projects",displayName:"Projects",root:".hasna",relativePath:"projects",sqliteDatabaseGlobs:["projects.db","data/*/project.db"],sensitiveFileGlobs:["projects.db","projects.db-wal","projects.db-shm","data/*/project.db","data/*/project.db-wal","data/*/project.db-shm","reports/**/*"],backupGlobs:["backups/**/*","data/*/backups/**/*"],exportGlobs:["reports/**/*","exports/**/*"],retentionAdapters:[c$("projects-reports-workspaces","Project reports, dashboards, workspaces, and per-project DBs need active workspace/location references before cleanup.",30,["backup","export","report","tmp"],["backups/**/*","reports/**/*","workspaces/**/*","data/*/backups/**/*"],[{id:"projects-active-workspaces",source:"sqlite",table:"workspaces",column:"primary_path",description:"Exclude active workspace paths, locations, linked reports, and project store artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"browser",packageName:"@hasna/browser",displayName:"Browser",root:".hasna",relativePath:"browser",sqliteDatabaseGlobs:["browser.db"],sensitiveFileGlobs:["browser.db","browser.db-wal","browser.db-shm","profiles/**/cookies.json","states/**/*.json","auth/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*","traces/**/*","har/**/*"],retentionAdapters:[c$("browser-auth-traces","Browser state, trace, HAR, and auth artifacts require session invalidation or redaction before deletion.",7,["backup","export","session","snapshot"],["profiles/**/*","states/**/*","traces/**/*","har/**/*","exports/**/*"],[{id:"browser-active-profiles",source:"sqlite",table:"sessions",column:"profile_path",description:"Exclude profiles, cookies, and storage state used by active browser sessions."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"terminal",packageName:"@hasna/terminal",displayName:"Terminal",root:".hasna",relativePath:"terminal",sqliteDatabaseGlobs:["sessions.db"],sensitiveFileGlobs:["sessions.db","sessions.db-wal","sessions.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("terminal-sessions","Terminal sessions and interactions need active session exclusion plus command-output redaction before retention.",30,["backup","export","session","log"],["backups/**/*","exports/**/*","sessions/**/*"],[{id:"terminal-active-sessions",source:"sqlite",table:"sessions",column:"id",description:"Exclude active terminal session records and any linked interaction artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"logs",packageName:"@hasna/logs",displayName:"Logs",root:".hasna",relativePath:"logs",sqliteDatabaseGlobs:["logs.db"],sensitiveFileGlobs:["logs.db","logs.db-wal","logs.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("logs-retention","Logs require redaction before compaction and must preserve active incident/evidence references.",14,["backup","export","log"],["backups/**/*","exports/**/*","*.log","logs/**/*"],[{id:"logs-active-evidence",source:"sqlite",table:"logs",column:"id",description:"Exclude log rows or files linked to active incidents, tasks, or proof bundles."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"loops",packageName:"@hasna/loops",displayName:"OpenLoops",root:".hasna",relativePath:"loops",sqliteDatabaseGlobs:["loops.db","state.db","*.sqlite"],sensitiveFileGlobs:["*.db","*.sqlite","*.db-wal","*.db-shm","reports/**/*","tmp/**/*","runs/**/*"],backupGlobs:["backups/**/*","tmp/**/*"],exportGlobs:["reports/**/*","runs/**/*","exports/**/*"],retentionAdapters:[c$("loops-reports-tmp","Loop reports, tmp files, workflow artifacts, and command output need run-state checks and redaction before retention deletion.",14,["backup","export","report","tmp","log"],["reports/**/*","tmp/**/*","runs/**/*","exports/**/*"],[{id:"loops-active-runs",source:"sqlite",table:"loop_runs",column:"id",description:"Exclude active, leased, recently failed, or evidence-linked loop and workflow run artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]}],warnings:["This package publishes declarations only; each owning package implements and verifies its own local-store lifecycle.","Retention and redaction evidence remain package-owned and must preserve active-record exclusions.","SQLite maintenance is descriptive policy metadata only and is never executed by @hasna/contracts."]});var Lr=64,Wd=new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${Lr-1}}$`),gg="[0-9a-fA-F]",Xd=new RegExp(`^\\{?(?:${gg}{8}-${gg}{4}-${gg}{4}-${gg}{4}-${gg}{12}|${gg}{32})\\}?$`);var Jr=/^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/;var Rd=new RegExp(Jr.source.replace(/^\^/,"\\b").replace(/\$$/,"\\b"));var m9="@hasna/knowledge";function Pr(_){if(!Number.isFinite(_??0))return 20;return Math.max(1,Math.min(100,Math.trunc(_??20)))}function zr(_){return _.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function QU(_,$=180){let g=String(_??"").replace(/\s+/g," ").trim();if(g.length<=$)return g;return`${g.slice(0,Math.max(0,$-3))}...`}function C_(_,$=""){return typeof _==="string"&&_.length>0?_:$}function TU(_){return typeof _==="number"&&Number.isFinite(_)?_:0}function qg(_){if(typeof _!=="string"||_.length===0)return;let $=_.includes("T")?_:`${_.replace(" ","T")}Z`,g=new Date($);return Number.isNaN(g.valueOf())?void 0:g.toISOString()}function PN(_){return H$.safeParse(_).success}function k$(_,$,g,U,D=[]){return{kind:_,id:$,name:g,uri:U&&PN(U)?U:void 0,externalId:$,sourcePackage:m9,tags:D}}function Sr(_){return[..._.items.flatMap((g)=>[g.updated_at,g.created_at]),..._.sources.flatMap((g)=>[g.updated_at,g.created_at]),..._.chunks.map((g)=>g.created_at),..._.wiki_pages.flatMap((g)=>[g.updated_at,g.created_at]),..._.storage_objects.flatMap((g)=>[g.updated_at,g.created_at]),..._.runs.flatMap((g)=>[g.updated_at,g.created_at]),..._.reindex_queue.flatMap((g)=>[g.updated_at,g.created_at]),..._.sync_conflicts.map((g)=>g.created_at),..._.approval_gates.flatMap((g)=>[g.updated_at,g.created_at])].map(qg).filter(Boolean).sort((g,U)=>U.localeCompare(g))[0]}function Wr(_){if(!_)return"unknown";let $=Date.now()-new Date(_).valueOf();if(!Number.isFinite($))return"unknown";return $>2592000000?"stale":"fresh"}function Xr(_){let $=(g)=>{let U=String(g??"").toLowerCase();return U!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(U)};return _.reindex_queue.filter((g)=>$(g.status)).length+_.sync_conflicts.filter((g)=>$(g.status)).length+_.approval_gates.filter((g)=>$(g.status)).length}function Rr(_,$){let g=[];for(let U of _.items.slice(0,$))g.push({id:`item_${U.id}`,title:U.title,summary:QU(U.content_preview),status:U.archived?"archived":"active",priority:"medium",timestamp:qg(U.updated_at??U.created_at),resourceRefs:[k$("knowledge",U.id,U.title,`knowledge://item/${encodeURIComponent(U.id)}`,U.tags)],evidenceRefs:U.url&&PN(U.url)?[{id:`url_${U.id}`,kind:"url",uri:U.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:U.archived,tags:U.tags,url:U.url||void 0}});for(let U of _.sources.slice(0,Math.max(0,$-g.length))){let D=C_(U.id,C_(U.uri,"source")),I=C_(U.title,C_(U.uri,D)),j=C_(U.uri,`knowledge://source/${encodeURIComponent(D)}`);g.push({id:`source_${D}`,title:I,summary:QU(`${TU(U.chunks)} chunk(s), ${TU(U.revisions)} revision(s)`),status:TU(U.chunks)>0?"indexed":"source",priority:"medium",timestamp:qg(U.updated_at??U.created_at),resourceRefs:[k$("document",D,I,j)],evidenceRefs:PN(j)?[{id:`source_${D}`,kind:"url",uri:j,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:U.kind,chunks:TU(U.chunks),revisions:TU(U.revisions)}})}for(let U of _.chunks.slice(0,Math.max(0,$-g.length))){let D=C_(U.id,"chunk"),I=C_(U.source_uri);g.push({id:`chunk_${D}`,title:C_(U.wiki_title,I?`Chunk from ${I}`:`Knowledge chunk ${D}`),summary:QU(U.text_preview),status:"chunk",priority:"low",timestamp:qg(U.created_at),resourceRefs:[k$("context_pack",D,C_(U.wiki_title,D),`knowledge://chunk/${encodeURIComponent(D)}`)],evidenceRefs:I&&PN(I)?[{id:`chunk_source_${D}`,kind:"url",uri:I,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:I||void 0,token_count:U.token_count,ordinal:U.ordinal}})}for(let U of _.sync_conflicts.slice(0,Math.max(0,$-g.length))){let D=C_(U.id,"sync_conflict");g.push({id:`sync_conflict_${D}`,title:`Sync conflict: ${C_(U.entity_kind,"entity")}/${C_(U.entity_id,D)}`,summary:QU(`Status ${C_(U.status,"unknown")}; strategy ${C_(U.resolution_strategy,"none")}.`),status:C_(U.status,"unknown"),priority:"critical",timestamp:qg(U.created_at),resourceRefs:[k$("finding",D,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(D)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:U.local_machine_id,remote_machine_id:U.remote_machine_id}})}for(let U of _.reindex_queue.slice(0,Math.max(0,$-g.length))){let D=C_(U.id,"reindex");g.push({id:`reindex_${D}`,title:`Reindex ${C_(U.kind,"item")}: ${C_(U.target_id,D)}`,summary:QU(U.reason),status:C_(U.status,"unknown"),priority:C_(U.status).toLowerCase()==="failed"?"high":"medium",timestamp:qg(U.updated_at??U.created_at),resourceRefs:[k$("action",D,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(D)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:U.attempts,source_uri:U.source_uri}})}return g.slice(0,$)}async function i9(_,$={}){let g=Pr($.limit),U=new Date().toISOString(),D=zr(_),j=await($.service??UN({scope:$.scope??"project",cwd:$.cwd})).resolveInventory({limit:g,storePath:$.storePath,includeArchived:$.includeArchived}),N=Sr(j),O=Wr(N),A=j.summary.active_items+j.summary.sources+j.summary.chunks+j.summary.wiki_pages+j.summary.storage_objects,L=Xr(j),z=A===0?"empty":O==="stale"?"stale":"ready",W=Rr(j,g),J={schema:x.projectPanel,id:`knowledge_panel_${D}`,createdAt:U,projectId:D,provider:{kind:"knowledge",id:`knowledge_${D}`,name:"Knowledge",sourcePackage:m9,externalId:j.home},kind:"knowledge",title:"Knowledge",summary:z==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${j.summary.active_items} active note(s), ${j.summary.sources} source(s), ${j.summary.chunks} chunk(s), and ${j.summary.wiki_pages} wiki page(s).`,state:z,stateReason:z==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:U,freshness:O,metrics:[{id:"active_items",label:"Active notes",value:j.summary.active_items,status:j.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:j.summary.sources,status:j.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:j.summary.chunks,status:j.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:j.summary.wiki_pages,status:j.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:j.summary.storage_objects,status:j.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:j.summary.vector_entries,status:j.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:L,status:L>0?"warning":"good"}],items:W,actions:[k$("action","knowledge:inventory","Inspect knowledge inventory"),k$("action","knowledge:context-pack","Build cited context pack"),k$("action","knowledge:ingest","Ingest project source")],resourceRefs:[k$("project",D,_,`project://${D}`),k$("knowledge",`home_${D}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(D)}`),k$("artifact",`db_${D}`,"Knowledge database",`knowledge://db/${encodeURIComponent(D)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:g}},metadata:{scope:j.scope,home:j.home,json_store_exists:j.paths.json_store_exists,latest_activity_at:N}};return d9(x.projectPanel,J)}function l9(_){let $=[`${_.title}: ${_.state}`,_.summary??"",..._.metrics.map((g)=>`${g.label}: ${g.value}`)].filter(Boolean);if(_.items.length>0){$.push("Items:");for(let g of _.items.slice(0,10))if($.push(`- ${g.title}${g.status?` [${g.status}]`:""}`),g.summary)$.push(` ${g.summary}`)}return $.join(` +`)}var p9=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"];var e9="HASNA_KNOWLEDGE_STORAGE_MODE",a9="KNOWLEDGE_STORAGE_MODE";function t9(_){return process.env[_]?.trim()||void 0}function o9(_){let $=_?.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return"sqlite";if($==="postgres"||$==="postgresql")return"postgres";return}function Gr(_={}){let $=D0(ZU(_.scope,_.cwd).home);return h($.knowledgeDbPath),{db:v($.knowledgeDbPath),path:$.knowledgeDbPath,scope:_.scope??"global"}}function s9(){let _=o9(t9(e9))??o9(t9(a9));if(_)return _;return"sqlite"}function t3(_={}){let $=Gr(_);try{Yr($.db);let g=$.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all();return{mode:s9(),service:"knowledge",scope:$.scope,databasePath:$.path,tables:p9,sync:g}}finally{$.db.close()}}function Yr(_){_.exec(` CREATE TABLE IF NOT EXISTS _knowledge_sync_meta ( table_name TEXT NOT NULL, last_synced_at TEXT, direction TEXT NOT NULL CHECK(direction IN ('push', 'pull')), PRIMARY KEY (table_name, direction) ) - `)}var rM=CA(lM(),1),{program:M0$,createCommand:A0$,createArgument:b0$,createOption:w0$,CommanderError:g0$,InvalidArgumentError:k0$,InvalidOptionArgumentError:I0$,Command:pM,Argument:f0$,Option:C0$,Help:P0$}=rM.default;import{chmod as VB,mkdir as vp,readFile as yp,rename as hp,writeFile as sM}from"fs/promises";import{Buffer as GA}from"buffer";import{existsSync as YA}from"fs";import{homedir as mp}from"os";import{join as z9}from"path";import{createHmac as ip,timingSafeEqual as x0$}from"crypto";import{randomUUID as pp}from"crypto";import{spawn as op}from"child_process";import{randomUUID as _o}from"crypto";function kp($,_){return _.split(".").reduce((J,U)=>{if(J&&typeof J==="object"&&U in J)return J[U];return},$)}function Ip($,_){let J=[],U=(X)=>{if(!J.some((G)=>Object.is(G,X)))J.push(X)};if(_.includes(".")&&_ in $)U($[_]);let W=kp($,_);if(W!==void 0||!_.includes("."))U(W);return J}function fp($,_={}){let J="";for(let U=0;U<$.length;U+=1){let W=$[U];if(W==="*")if($[U+1]==="*")J+=".*",U+=1;else J+=_.segmentSafe?"[^/]*":".*";else J+=W.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${J}$`)}function Q9($,_,J={}){if(_===void 0)return!0;if($===void 0)return!1;return(Array.isArray(_)?_:[_]).some((W)=>fp(W,J).test($))}function oM($,_){if(!_)return!0;return Object.entries(_).every(([J,U])=>{let W=Ip($,J);return Cp(W,U,J)})}function Cp($,_,J){if(Sp(_))return!$.some((U)=>tM(U,_.not,J));return $.some((U)=>tM(U,_,J))}function tM($,_,J){if(typeof _==="string"||Array.isArray(_))return Pp($).some((U)=>Q9(U,_,{segmentSafe:J.endsWith("_path")||J.endsWith(".path")}));if(Array.isArray($))return $.some((U)=>U===_);return $===_}function Pp($){if($===void 0)return[];if(Array.isArray($))return $.flatMap((_)=>Tp(_)?[String(_)]:[]);return[String($)]}function Tp($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function Sp($){return Boolean($&&typeof $==="object"&&!Array.isArray($)&&"not"in $)}function Zp($,_){return Q9($.source,_.source)&&Q9($.type,_.type)&&Q9($.subject,_.subject)&&Q9($.severity,_.severity)&&oM($.data,_.data)&&oM($.metadata,_.metadata)}function aM($,_){if(!$.enabled)return!1;if(!$.filters||$.filters.length===0)return!0;return $.filters.some((J)=>Zp(_,J))}var qY="HASNA_EVENTS_DIR",zY="HASNA_EVENTS_HOME",EB="local-json-v1:",xp=100,up=1000;function QA($){return $||process.env[qY]||process.env[zY]||z9(mp(),".hasna","events")}function dp(){if(process.env[qY])return qY;if(process.env[zY])return zY;return null}class jY{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor($=QA()){this.dataDir=$,this.runtime=np($),this.channelsPath=z9($,"channels.json"),this.eventsPath=z9($,"events.json"),this.deliveriesPath=z9($,"deliveries.json")}async init(){await vp(this.dataDir,{recursive:!0,mode:448}),await VB(this.dataDir,448).catch(()=>{return}),await this.ensureArrayFile(this.channelsPath),await this.ensureArrayFile(this.eventsPath),await this.ensureArrayFile(this.deliveriesPath)}async addChannel($){await this.init();let _=await this.readJson(this.channelsPath,[]),J=_.findIndex((U)=>U.id===$.id);if(J>=0)_[J]={...$,createdAt:_[J].createdAt,updatedAt:new Date().toISOString()};else _.push($);return await this.writeJson(this.channelsPath,_),J>=0?_[J]:$}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel($){return(await this.listChannels()).find((J)=>J.id===$)}async removeChannel($){await this.init();let _=await this.readJson(this.channelsPath,[]),J=_.filter((U)=>U.id!==$);return await this.writeJson(this.channelsPath,J),J.length!==_.length}async appendEvent($){await this.init();let _=await this.readJson(this.eventsPath,[]);return _.push($),await this.writeJson(this.eventsPath,_),$}async appendEventOnce($,_={}){await this.init();let J=await this.readJson(this.eventsPath,[]);if(_.dedupe!==!1){let W=$A(J,{id:$.id,dedupeKey:$.dedupeKey});if(W)return{event:W,stored:!1,deduped:!0,identity:{id:W.id,dedupeKey:W.dedupeKey}}}return J.push($),await this.writeJson(this.eventsPath,J),{event:$,stored:!0,deduped:!1,identity:{id:$.id,dedupeKey:$.dedupeKey}}}async listEvents($={}){await this.init();let _=await this.readJson(this.eventsPath,[]);return eM(_,$)}async listEventsPage($={}){await this.init();let _=await this.readJson(this.eventsPath,[]),J=eM(_,{eventId:$.eventId,source:$.source,type:$.type}),U=DY($.cursor,$),W=OY($.limit),X=J.slice(U,U+W),G=U+X.length,Y=G{return})}async readJson($,_){try{let J=await yp($,"utf-8");if(!J.trim())return _;return JSON.parse(J)}catch(J){if(J.code==="ENOENT")return _;throw J}}async writeJson($,_){let J=`${$}.${process.pid}.${Date.now()}.tmp`;await sM(J,`${JSON.stringify(_,null,2)} -`,{encoding:"utf-8",mode:384}),await hp(J,$),await VB($,384).catch(()=>{return})}}function np($=QA()){return{mode:"local-files",name:"json-events-store",remote:!1,localFiles:!0,localSqlite:!1,postgres:!1,s3:!1,aws:!1,durable:!0,idempotency:"best-effort-local",replayCursors:!0,description:`Local JSON files in ${$}; no SQLite, Postgres, S3, or AWS runtime is configured by this store.`}}function qA($,_={}){if(!Number.isInteger($)||$<0)throw Error(`Invalid event cursor offset: ${$}`);let J={offset:$,eventId:_.eventId,source:_.source,type:_.type};return`${EB}${GA.from(JSON.stringify(J),"utf-8").toString("base64url")}`}function DY($,_={}){if(!$)return 0;if(!$.startsWith(EB))throw Error(`Invalid local JSON event cursor: ${$}`);let J=$.slice(EB.length),U;try{U=JSON.parse(GA.from(J,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${$}`)}let W=U.offset;if(!Number.isInteger(W)||W<0)throw Error(`Invalid local JSON event cursor: ${$}`);return RB("eventId",U.eventId,_.eventId),RB("source",U.source,_.source),RB("type",U.type,_.type),W}function OY($){if($===void 0)return xp;if(!Number.isInteger($)||$<1)throw Error(`Event page limit must be a positive integer, got ${$}`);return Math.min($,up)}function eM($,_){let J=$;if(_.eventId)J=J.filter((U)=>U.id===_.eventId);if(_.source)J=J.filter((U)=>U.source===_.source);if(_.type)J=J.filter((U)=>U.type===_.type);if(_.cursor){let U=DY(_.cursor,_);J=J.slice(U)}if(_.limit!==void 0)J=J.slice(0,OY(_.limit));return J}function RB($,_,J){if(_!==J)throw Error(`Local JSON event cursor ${$} filter mismatch`)}function $A($,_){return $.find((J)=>_.id!==void 0&&J.id===_.id||_.dedupeKey!==void 0&&J.dedupeKey===_.dedupeKey)}async function cp($){let _=new jY($);await _.init();let[J,U,W]=await Promise.all([_.listChannels(),_.listEvents(),_.listDeliveries()]),X=J.reduce((G,Y)=>{return G[Y.transport]=(G[Y.transport]??0)+1,G},{});return{service:"events",schemaVersion:"1.0",dataDir:_.dataDir,storage:_.runtime,env:{primary:qY,fallback:zY,active:dp()},files:{channels:KB(_.dataDir,"channels.json",J.length),events:KB(_.dataDir,"events.json",U.length),deliveries:KB(_.dataDir,"deliveries.json",W.length)},counts:{channels:J.length,enabledChannels:J.filter((G)=>G.enabled).length,disabledChannels:J.filter((G)=>!G.enabled).length,events:U.length,deliveries:W.length},transports:X,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function KB($,_,J){let U=z9($,_);return{path:U,exists:YA(U),records:J}}function lp($,_){return`${$}.${_}`}function rp($,_,J){return`sha256=${ip("sha256",$).update(lp(_,J)).digest("hex")}`}function R4(){return new Date().toISOString()}function q9($,_=4096){return $.length>_?`${$.slice(0,_)}...`:$}function tp($,_){if(!_.webhook)throw Error(`Channel ${_.id} has no webhook config`);let J=JSON.stringify($),U=$.time,W={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":$.id,"X-Hasna-Event-Type":$.type,"X-Hasna-Timestamp":U,..._.webhook.headers};if(_.webhook.secret)W["X-Hasna-Signature"]=rp(_.webhook.secret,U,J);return{body:J,headers:W}}async function ap($,_,J={}){if(!_.webhook)throw Error(`Channel ${_.id} has no webhook config`);let U=R4(),{body:W,headers:X}=tp($,_),G=new AbortController,Y=setTimeout(()=>G.abort(),_.webhook.timeoutMs??15000);try{let Q=await(J.fetchImpl??fetch)(_.webhook.url,{method:"POST",headers:X,body:W,signal:G.signal}),q=q9(await Q.text());return{attempt:1,status:Q.ok?"success":"failed",startedAt:U,completedAt:R4(),responseStatus:Q.status,responseBody:q,error:Q.ok?void 0:`Webhook returned HTTP ${Q.status}`}}catch(Q){return{attempt:1,status:"failed",startedAt:U,completedAt:R4(),error:Q instanceof Error?Q.message:String(Q)}}finally{clearTimeout(Y)}}async function sp($,_){if(!_.command)throw Error(`Channel ${_.id} has no command config`);let J=R4(),U=JSON.stringify($),W={...process.env,..._.command.env,HASNA_CHANNEL_ID:_.id,HASNA_EVENT_ID:$.id,HASNA_EVENT_TYPE:$.type,HASNA_EVENT_SOURCE:$.source,HASNA_EVENT_SUBJECT:$.subject??"",HASNA_EVENT_SEVERITY:$.severity,HASNA_EVENT_TIME:$.time,HASNA_EVENT_DEDUPE_KEY:$.dedupeKey??"",HASNA_EVENT_SCHEMA_VERSION:$.schemaVersion,HASNA_EVENT_JSON:U};return new Promise((X)=>{let G=op(_.command.command,_.command.args??[],{cwd:_.command.cwd,env:W,stdio:["pipe","pipe","pipe"]}),Y="",Q="",q=setTimeout(()=>G.kill("SIGTERM"),_.command.timeoutMs??15000);G.stdin.end(U),G.stdout.on("data",(L)=>{Y+=L.toString()}),G.stderr.on("data",(L)=>{Q+=L.toString()}),G.on("error",(L)=>{clearTimeout(q),X({attempt:1,status:"failed",startedAt:J,completedAt:R4(),stdout:q9(Y),stderr:q9(Q),error:L.message})}),G.on("close",(L,N)=>{clearTimeout(q);let R=L===0;X({attempt:1,status:R?"success":"failed",startedAt:J,completedAt:R4(),stdout:q9(Y),stderr:q9(Q),error:R?void 0:`Command exited with ${N?`signal ${N}`:`code ${L}`}`})})})}async function ep($,_,J={}){if(_.transport==="webhook")return ap($,_,J);if(_.transport==="command")return sp($,_);return{attempt:1,status:"skipped",startedAt:R4(),completedAt:R4(),error:`Unsupported transport: ${_.transport}`}}function _A($,_,J){let U=J.some((W)=>W.status==="success")?"success":J.every((W)=>W.status==="skipped")?"skipped":"failed";return{id:pp(),eventId:$.id,channelId:_.id,transport:_.transport,status:U,attempts:J,createdAt:J[0]?.startedAt??R4(),completedAt:J.at(-1)?.completedAt??R4()}}class zA extends Error{eventType;issues;constructor($,_){let J=_.map((U)=>`${U.path||""}: ${U.message}`).join("; ");super(`Event validation failed for type "${$}": ${J}`);this.name="EventValidationError",this.eventType=$,this.issues=_}}class jA{definitions=new Map;register($){return this.definitions.set($.type,$),this}unregister($){return this.definitions.delete($)}has($){return this.definitions.has($)}get($){return this.definitions.get($)}list(){return[...this.definitions.values()]}validateEvent($){let _=this.definitions.get($.type);if(!_)return{ok:!0};return _.validate($.data,$)}assertEventValid($){let _=this.validateEvent($);if(!_.ok)throw new zA($.type,_.issues)}}var $o=new jA;function FB($){return{id:$.id??_o(),source:$.source,type:$.type,time:Go($.time),subject:$.subject,severity:$.severity??"info",data:$.data??{},message:$.message,dedupeKey:$.dedupeKey,schemaVersion:$.schemaVersion??"1.0",metadata:$.metadata??{}}}class DA{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor($={}){this.store=$.store??new jY($.dataDir),this.redactors=$.redactors??[],this.transportOptions={fetchImpl:$.fetchImpl},this.catalog=$.catalog??$o,this.validateCatalogTypes=$.validateCatalogTypes??!1}async addChannel($){let _=new Date().toISOString();return this.store.addChannel({...$,createdAt:$.createdAt??_,updatedAt:$.updatedAt??_})}async listChannels(){return this.store.listChannels()}async removeChannel($){return this.store.removeChannel($)}async emit($,_={}){let J=_.redactSensitiveData===!1?FB($):Uo(FB($));if(_.validate??this.validateCatalogTypes)this.catalog.assertEventValid(J);let U=await this.appendEvent(J,{dedupe:_.dedupe!==!1});if(U.deduped)return{event:U.event,deliveries:[],deduped:!0};let W=_.deliver===!1?[]:await this.deliver(U.event);return{event:U.event,deliveries:W,deduped:!1}}async listEvents($={}){if(Object.keys($).length===0)return this.store.listEvents();return JA(await this.store.listEvents(),$)}async listEventsPage($={}){if(this.store.listEventsPage)return this.store.listEventsPage($);let _=JA(await this.store.listEvents(),{eventId:$.eventId,source:$.source,type:$.type}),J=DY($.cursor,$),U=OY($.limit),W=_.slice(J,J+U),X=J+W.length,G=X<_.length;return{events:W,cursor:$.cursor,nextCursor:G?qA(X,$):void 0,hasMore:G}}async listDeliveries(){return this.store.listDeliveries()}async deliver($){let J=(await this.store.listChannels()).filter((W)=>aM(W,$)),U=[];for(let W of J){let X=await this.applyRedaction($,W),G=await this.deliverWithRetry(X,W);await this.store.appendDelivery(G),U.push(G)}return U}async matchChannel($,_={}){let J=await this.store.getChannel($);if(!J)throw Error(`Channel not found: ${$}`);let U=FB({source:_.source??"hasna.events",type:_.type??"events.test",subject:_.subject??$,severity:_.severity??"info",data:_.data??{test:!0},message:_.message??"Hasna events test delivery",dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion,metadata:_.metadata,time:_.time,id:_.id}),W=aM(J,U);return{channelId:J.id,matched:W,event:U,filters:J.filters,reason:W?void 0:J.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel($,_={},J={}){let U=await this.store.getChannel($);if(!U)throw Error(`Channel not found: ${$}`);let W=await this.matchChannel($,_),X=W.event;if(J.honorFilters&&!W.matched){let Q=new Date().toISOString(),q=_A(X,U,[{attempt:1,status:"skipped",startedAt:Q,completedAt:Q,error:W.reason}]);return q.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(q),q}let G=await this.applyRedaction(X,U),Y=await this.deliverWithRetry(G,U);return await this.store.appendDelivery(Y),Y}async replay($={}){let _=$.cursor||$.limit!==void 0?await this.listEventsPage($):{events:await this.listEvents($),hasMore:!1};if($.dryRun)return{events:_.events,deliveries:[],cursor:_.cursor,nextCursor:_.nextCursor,hasMore:_.hasMore};let J=[];for(let U of _.events)J.push(...await this.deliver(U));return{events:_.events,deliveries:J,cursor:_.cursor,nextCursor:_.nextCursor,hasMore:_.hasMore}}async appendEvent($,_){if(this.store.appendEventOnce)return this.store.appendEventOnce($,{dedupe:_.dedupe});if(_.dedupe){let U=await this.store.findEventByIdentity({id:$.id,dedupeKey:$.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}let J=await this.store.appendEvent($);return{event:J,stored:!0,deduped:!1,identity:{id:J.id,dedupeKey:J.dedupeKey}}}async applyRedaction($,_){let J=Jo($,_.redact?.paths??[],_.redact?.replacement??"[REDACTED]");for(let U of this.redactors)J=await U(J,_);return J}async deliverWithRetry($,_){let J=Yo(_.retry),U=[];for(let W=0;W[J,LA(J)?"[REDACTED]":U]));return _}function Wo($){return $.map(OA)}function Uo($,_="[REDACTED]"){return MB($,_)}function LA($){return/secret|token|password|api[_-]?key|authorization/i.test($)}function MB($,_){if(Array.isArray($))return $.map((J)=>MB(J,_));if(!$||typeof $!=="object")return $;return Object.fromEntries(Object.entries($).map(([J,U])=>[J,LA(J)?_:MB(U,_)]))}function Xo($,_,J){let U=_.split("."),W=$;for(let G of U.slice(0,-1)){let Y=W[G];if(!Y||typeof Y!=="object")return;W=Y}let X=U.at(-1);if(X&&X in W)W[X]=J}function JA($,_){let J=$;if(_.eventId)J=J.filter((U)=>U.id===_.eventId);if(_.source)J=J.filter((U)=>U.source===_.source);if(_.type)J=J.filter((U)=>U.type===_.type);if(_.cursor)J=J.slice(DY(_.cursor,_));if(_.limit!==void 0)J=J.slice(0,OY(_.limit));return J}function Go($){if(!$)return new Date().toISOString();return $ instanceof Date?$.toISOString():$}function Yo($){return{maxAttempts:Math.max(1,$?.maxAttempts??1),backoffMs:Math.max(0,$?.backoffMs??250),multiplier:Math.max(1,$?.multiplier??2)}}function QY($,_,J=!1){if(!$?.length)return;let U={};for(let W of $){let X=zo(W,_),G=X.path;if(G in U)throw Error(`Duplicate ${_} filter path: ${G}`);let Y=J?qo(X.rawValue,_):X.rawValue;U[G]=X.negated?{not:Y}:Y}return U}function Qo($){let _={};if($.source)_.source=$.source;if($.type)_.type=$.type;if($.subject)_.subject=$.subject;if($.severity)_.severity=$.severity;let J=WA(QY($.data,"data"),QY($.dataJson,"data-json",!0)),U=WA(QY($.metadata,"metadata"),QY($.metadataJson,"metadata-json",!0));if(Object.keys(J).length>0)_.data=J;if(Object.keys(U).length>0)_.metadata=U;return Object.keys(_).length>0?[_]:void 0}function WA(...$){let _={};for(let J of $){if(!J)continue;for(let[U,W]of Object.entries(J)){if(U in _)throw Error(`Duplicate filter path: ${U}`);_[U]=W}}return _}function qo($,_){let J=JSON.parse($);if(J===null||typeof J==="string"||typeof J==="number"||typeof J==="boolean"||Array.isArray(J)&&J.every((U)=>typeof U==="string"))return J;throw Error(`${_} filter JSON values must be string, string[], number, boolean, or null`)}function zo($,_){let J=$.indexOf("!=");if(J>0)return{path:$.slice(0,J),rawValue:$.slice(J+2),negated:!0};let U=$.indexOf("=");if(U<=0)throw Error(`Invalid ${_} filter, expected path=value or path!=value: ${$}`);return{path:$.slice(0,U),rawValue:$.slice(U+1),negated:!1}}var jo=100;function mW($,_){if(!$)return _;let J=JSON.parse($);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Expected a JSON object");return J}function Do($){if(!$?.length)return;let _={};for(let J of $){let U=J.indexOf("=");if(U===-1)throw Error(`Invalid header, expected name=value: ${J}`);_[J.slice(0,U)]=J.slice(U+1)}return _}function o0($){if($.createClient)return $.createClient();return new DA({store:new jY($.dataDir)})}function F2($,_,J){if(_)console.log(JSON.stringify($,null,2));else console.log(J)}function UA($,_){let J=$ instanceof Error?$.message:String($);if(_)console.log(JSON.stringify({error:J},null,2));else console.error(J);process.exitCode=1}function XA($){return Boolean($?.json||$?.opts?.().json||$?.optsWithGlobals?.().json||$?.parent?.opts?.().json||$?.parent?.optsWithGlobals?.().json)}function X0($,_){return XA($)||XA(_)}function Oo($,_){let J=$.command(_.channelsCommandName??"channels").description("Manage Hasna event channels");return J.command("add").description("Add or replace a channel").argument("","Webhook URL or command binary").requiredOption("--id ","Channel identifier").option("--transport ","Transport kind: webhook or command","webhook").option("--name ","Display name").option("--type ","Event type filter, e.g. todos.task.*").option("--source ","Event source filter").option("--subject ","Event subject filter").option("--severity ","Event severity filter").option("--data ","Event data field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",K2,[]).option("--metadata ","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",K2,[]).option("--data-json ","Event data field filter with typed JSON value; path!=json negatives supported",K2,[]).option("--metadata-json ","Event metadata field filter with typed JSON value; path!=json negatives supported",K2,[]).option("--secret ","Webhook HMAC secret").option("--header ","Webhook header",K2,[]).option("--arg ","Command argument",K2,[]).option("--timeout-ms ","Transport timeout in milliseconds",j9).option("--retry-attempts ","Maximum delivery attempts",j9).option("--retry-backoff-ms ","Initial retry backoff in milliseconds",j9).option("--redact ","Event field path to redact before delivery",K2,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=new Date().toISOString(),Y={id:W.id,name:W.name,enabled:!W.disabled,transport:W.transport,filters:Qo(W),retry:W.retryAttempts||W.retryBackoffMs?{maxAttempts:W.retryAttempts,backoffMs:W.retryBackoffMs}:void 0,redact:W.redact?.length?{paths:W.redact}:void 0,createdAt:G,updatedAt:G};if(W.transport==="webhook")Y.webhook={url:U,secret:W.secret,headers:Do(W.header),timeoutMs:W.timeoutMs};else if(W.transport==="command")Y.command={command:U,args:W.arg??[],timeoutMs:W.timeoutMs};else throw Error(`Transport ${W.transport} is reserved for future use and cannot be added yet`);let Q=await o0(_).addChannel(Y);F2(OA(Q),X0(W,X),`Added ${Q.transport} channel ${Q.id}`)}),J.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(U,W)=>{let X=await o0(_).listChannels();if(X0(U,W)){console.log(JSON.stringify(Wo(X),null,2));return}if(!X.length){console.log("No channels configured.");return}for(let G of X)console.log(`${G.id} ${G.enabled?"enabled":"disabled"} ${G.transport} ${G.webhook?.url??G.command?.command??G.transport}`)}),J.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(U,W)=>{let X=await cp(_.dataDir);F2(X,X0(U,W),`events dataDir: ${X.dataDir}`)}),J.command("remove").description("Remove a channel").argument("","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=await o0(_).removeChannel(U);F2({removed:G},X0(W,X),G?`Removed ${U}`:`Channel not found: ${U}`)}),J.command("test").description("Send a test event to one channel").argument("","Channel identifier").option("--source ","Event source override").option("--type ","Event type","events.test").option("--subject ","Event subject").option("--message ","Event message","Hasna events test delivery").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("--honor-filters","Skip delivery when the sample event does not match channel filters",!1).option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=X0(W,X);try{let Y=await o0(_).testChannel(U,{source:W.source??_.source,type:W.type,subject:W.subject??U,message:W.message,data:mW(W.data,{test:!0}),metadata:mW(W.metadata,{})},{honorFilters:W.honorFilters});F2(Y,G,`${Y.status}: ${Y.channelId}`)}catch(Y){UA(Y,G)}}),J.command("match").description("Check whether a sample event matches one channel without delivering").argument("","Channel identifier").option("--source ","Event source override").option("--type ","Event type","events.test").option("--subject ","Event subject").option("--message ","Event message","Hasna events match preview").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=X0(W,X);try{let Y=await o0(_).matchChannel(U,{source:W.source??_.source,type:W.type,subject:W.subject??U,message:W.message,data:mW(W.data,{test:!0}),metadata:mW(W.metadata,{})});F2(Y,G,`${Y.matched?"matched":"skipped"}: ${Y.channelId}`)}catch(Y){UA(Y,G)}}),J}function Lo($,_){let J=$.command(_.eventsCommandName??"events").description("Emit, list, and replay Hasna events");J.command("emit").description("Emit an event from this app").argument("","Event type").option("--source ","Event source override").option("--subject ","Event subject").option("--severity ","Event severity","info").option("--message ","Event message").option("--dedupe-key ","Dedupe key").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("--no-deliver","Record without delivering").option("--no-dedupe","Allow duplicate id/dedupeKey events").option("-j, --json","Print JSON output",!1).action(async(W,X,G)=>{let Y=await o0(_).emit({source:X.source??_.source,type:W,subject:X.subject,severity:X.severity,message:X.message,dedupeKey:X.dedupeKey,data:mW(X.data,{}),metadata:mW(X.metadata,{})},{deliver:X.deliver,dedupe:X.dedupe});F2(Y,X0(X,G),`${Y.deduped?"Deduped":"Emitted"} ${Y.event.id} to ${Y.deliveries.length} channel(s)`)});let U=_.defaultEventListLimit??jo;return J.command("list").description("List recorded events").option("--source ","Filter by source").option("--type ","Filter by type").option("--limit ",`Limit to the most recent events (default ${U}; use 0 for all)`,j9,U).option("-j, --json","Print JSON output",!1).action(async(W,X)=>{let G=await o0(_).listEvents();if(W.source)G=G.filter((Y)=>Y.source===W.source);if(W.type)G=G.filter((Y)=>Y.type===W.type);if(W.limit)G=G.slice(-W.limit);if(X0(W,X)){console.log(JSON.stringify(G,null,2));return}if(!G.length){console.log("No events recorded.");return}for(let Y of G)console.log(`${Y.time} ${Y.id} ${Y.source} ${Y.type} ${Y.severity}`)}),J.command("replay").description("Replay recorded events").option("--id ","Replay one event id").option("--source ","Filter by source").option("--type ","Filter by type").option("--cursor ","Opaque replay cursor from a previous page").option("--limit ","Maximum events to replay",j9).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(W,X)=>{let G=await o0(_).replay({eventId:W.id,source:W.source,type:W.type,cursor:W.cursor,limit:W.limit,dryRun:W.dryRun});F2(G,X0(W,X),Bo(G.events.length,G.deliveries.length,G.nextCursor))}),J}function BA($,_){Oo($,_),Lo($,_)}function j9($){let _=Number($);if(!Number.isFinite(_))throw Error(`Expected a number, got ${$}`);return _}function K2($,_){return _.push($),_}function Bo($,_,J){let U=J?`, next cursor: ${J}`:"";return`Replayed ${$} event(s), ${_} delivery result(s)${U}`}import{basename as No}from"path";var s6={name:"@hasna/knowledge",version:"0.2.93",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. ",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.5.2","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};var HA={debug:0,info:1,warn:2,error:3},Vo=()=>{if(process.env.DEBUG)return"debug";if(process.env.LOG_LEVEL==="debug")return"debug";if(process.env.LOG_LEVEL==="warn")return"warn";if(process.env.LOG_LEVEL==="error")return"error";return"info"};function M2($,_,J){if(HA[$]U.toLowerCase()));return _.filter((U)=>!J.has(U.toLowerCase()))}function AB($,_,J){if(J===void 0)return{...$,message:_};return{...$,added:J.length,message:`${_} (added ${J.length} tag${J.length===1?"":"s"})`}}function Ko($,_){if(_===void 0)throw Error("Missing value for --tag. Example: knowledge add <content> -t <tag> -t <tag>");let J=_.split(",").map((U)=>U.trim()).filter((U)=>U.length>0);if(J.length===0)throw Error(`Invalid --tag value ${JSON.stringify(_)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return Ro([...$??[],...J])}function Fo($){let _=[],J={},U=!1;for(let W=0;W<$.length;W+=1){let X=$[W];if(U){_.push(X);continue}if(X==="--"){U=!0;continue}if(!X.startsWith("-")||_[0]==="add"&&_.length===2&&X.startsWith("---")){_.push(X);continue}switch(X){case"--json":J.json=!0;break;case"--verbose":J.verbose=!0;break;case"--yes":case"-y":J.yes=!0;break;case"--help":case"-h":J.help=!0;break;case"--version":case"-v":J.version=!0;break;case"--desc":J.desc=!0;break;case"--page":case"-p":J.page=Number($[W+1]),W+=1;break;case"--limit":case"-l":J.limit=Number($[W+1]),W+=1;break;case"--search":case"-s":J.search=$[W+1],W+=1;break;case"--sort":J.sort=$[W+1],W+=1;break;case"--id":J.id=$[W+1],W+=1;break;case"--store":J.store=$[W+1],W+=1;break;case"--title":J.title=$[W+1],W+=1;break;case"--content":J.content=$[W+1],W+=1;break;case"--url":J.url=$[W+1],W+=1;break;case"--tag":case"-t":J.tag=Ko(J.tag,$[W+1]),J.tagRaw=[...J.tagRaw??[],$[W+1]],W+=1;break;case"--format":J.format=$[W+1],W+=1;break;case"--completions":J.completions=$[W+1],W+=1;break;case"--purpose":J.purpose=$[W+1],W+=1;break;case"--model":J.model=$[W+1],W+=1;break;case"--strategy":J.strategy=$[W+1],W+=1;break;case"--dimensions":J.dimensions=Number($[W+1]),W+=1;break;case"--semantic":J.semantic=!0;break;case"--context":J.context=!0;break;case"--max-tokens":J.maxTokens=Number($[W+1]),W+=1;break;case"--max-items":J.maxItems=Number($[W+1]),W+=1;break;case"--from":J.from=$[W+1],W+=1;break;case"--to":J.to=$[W+1],W+=1;break;case"--rev":J.rev=Number($[W+1]),W+=1;break;case"--since":J.since=$[W+1],W+=1;break;case"--topic":J.topic=$[W+1],W+=1;break;case"--dedupe":J.dedupe=!0;break;case"--generate":J.generate=!0;break;case"--approve-write":J.approveWrite=!0;break;case"--provider":J.provider=$[W+1],W+=1;break;case"--mode":J.mode=$[W+1],W+=1;break;case"--machine":J.machine=$[W+1],W+=1;break;case"--workspace":J.workspace=$[W+1],W+=1;break;case"--api-url":J.apiUrl=$[W+1],W+=1;break;case"--canonical-example":J.canonicalExample=!0;break;case"--api-key":J.apiKey=$[W+1],W+=1;break;case"--email":J.email=$[W+1],W+=1;break;case"--org":J.org=$[W+1],W+=1;break;case"--org-id":J.orgId=$[W+1],W+=1;break;case"--user-id":J.userId=$[W+1],W+=1;break;case"--owner":J.owner=$[W+1],W+=1;break;case"--approved-by":J.approvedBy=$[W+1],W+=1;break;case"--patch-uri":J.patchUri=$[W+1],W+=1;break;case"--domain":J.domain=[...J.domain??[],$[W+1]],W+=1;break;case"--file-results":J.fileResults=!0;break;case"--full":J.full=!0;break;case"--dry-run":J.dryRun=!0;break;case"--fake":J.fake=!0;break;case"--no-tailscale":J.tailscale=!1;break;case"--no-artifact-content":J.artifactContent=!1;break;case"--no-color":J.noColor=!0;break;case"--scope":J.scope=$[W+1],W+=1;break;case"--tables":J.tables=$[W+1],W+=1;break;case"--peer-workspace":J.peerWorkspace=$[W+1],W+=1;break;case"--older-than":J.olderThan=Number($[W+1]),W+=1;break;case"--empty":J.empty=!0;break;case"--archived":J.archived=!0;break;case"--include-archived":J.includeArchived=!0;break;case"--project":J.project=$[W+1],W+=1;break;case"--contract":J.contract=!0;break;case"--source-ref":J.sourceRef=[...J.sourceRef??[],$[W+1]],W+=1;break;case"--allow-global":J.allowGlobal=!0;break;default:throw Error(`Unknown flag: ${X}. Run 'knowledge --help' for valid options.`)}}return{positional:_,flags:J}}function Eo($){if(!$)return"";return MA[$]??$}function Mo($,_){let J=Array.from({length:$.length+1},()=>Array(_.length+1).fill(0));for(let U=0;U<=$.length;U+=1)J[U][0]=U;for(let U=0;U<=_.length;U+=1)J[0][U]=U;for(let U=1;U<=$.length;U+=1)for(let W=1;W<=_.length;W+=1){let X=$[U-1]===_[W-1]?0:1;J[U][W]=Math.min(J[U-1][W]+1,J[U][W-1]+1,J[U-1][W-1]+X)}return J[$.length][_.length]}function Ao($){if(!$)return"";let _=[...EA,...Object.keys(MA)],J="",U=Number.POSITIVE_INFINITY;for(let W of _){let X=Mo($,W);if(X<U)U=X,J=W}return U<=3?J:""}function bo(){return No(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function wo($){if(!FA.includes($[0]??""))return!1;let _=new pM;return _.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),BA(_,{source:"knowledge"}),await _.parseAsync($,{from:"user"}),!0}function go(){console.log(`knowledge - local agent knowledge store + `)}var W8=_Y(S8(),1),{program:Um,createCommand:Im,createArgument:jm,createOption:Nm,CommanderError:Em,InvalidArgumentError:Om,InvalidOptionArgumentError:Am,Command:X8,Argument:Lm,Option:Jm,Help:Pm}=W8.default;import{chmod as Dz,mkdir as Gv,readFile as Yv,rename as Qv,writeFile as Q8}from"fs/promises";import{Buffer as Z8}from"buffer";import{existsSync as b8}from"fs";import{homedir as Tv}from"os";import{join as VU}from"path";import{createHmac as Mv,timingSafeEqual as Qm}from"crypto";import{randomUUID as Hv}from"crypto";import{spawn as kv}from"child_process";import{randomUUID as uv}from"crypto";function Lv(_,$){return $.split(".").reduce((g,U)=>{if(g&&typeof g==="object"&&U in g)return g[U];return},_)}function Jv(_,$){let g=[],U=(I)=>{if(!g.some((j)=>Object.is(j,I)))g.push(I)};if($.includes(".")&&$ in _)U(_[$]);let D=Lv(_,$);if(D!==void 0||!$.includes("."))U(D);return g}function Pv(_,$={}){let g="";for(let U=0;U<_.length;U+=1){let D=_[U];if(D==="*")if(_[U+1]==="*")g+=".*",U+=1;else g+=$.segmentSafe?"[^/]*":".*";else g+=D.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${g}$`)}function BU(_,$,g={}){if($===void 0)return!0;if(_===void 0)return!1;return(Array.isArray($)?$:[$]).some((D)=>Pv(D,g).test(_))}function R8(_,$){if(!$)return!0;return Object.entries($).every(([g,U])=>{let D=Jv(_,g);return zv(D,U,g)})}function zv(_,$,g){if(Xv($))return!_.some((U)=>G8(U,$.not,g));return _.some((U)=>G8(U,$,g))}function G8(_,$,g){if(typeof $==="string"||Array.isArray($))return Sv(_).some((U)=>BU(U,$,{segmentSafe:g.endsWith("_path")||g.endsWith(".path")}));if(Array.isArray(_))return _.some((U)=>U===$);return _===$}function Sv(_){if(_===void 0)return[];if(Array.isArray(_))return _.flatMap(($)=>Wv($)?[String($)]:[]);return[String(_)]}function Wv(_){return _===null||typeof _==="string"||typeof _==="number"||typeof _==="boolean"}function Xv(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_)&&"not"in _)}function Rv(_,$){return BU(_.source,$.source)&&BU(_.type,$.type)&&BU(_.subject,$.subject)&&BU(_.severity,$.severity)&&R8(_.data,$.data)&&R8(_.metadata,$.metadata)}function Y8(_,$){if(!_.enabled)return!1;if(!_.filters||_.filters.length===0)return!0;return _.filters.some((g)=>Rv($,g))}var XN="HASNA_EVENTS_DIR",RN="HASNA_EVENTS_HOME",Nz="local-json-v1:",qv=100,Bv=1000;function H8(_){return _||process.env[XN]||process.env[RN]||VU(Tv(),".hasna","events")}function Kv(){if(process.env[XN])return XN;if(process.env[RN])return RN;return null}class GN{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor(_=H8()){this.dataDir=_,this.runtime=Vv(_),this.channelsPath=VU(_,"channels.json"),this.eventsPath=VU(_,"events.json"),this.deliveriesPath=VU(_,"deliveries.json")}async init(){await Gv(this.dataDir,{recursive:!0,mode:448}),await Dz(this.dataDir,448).catch(()=>{return}),await this.ensureArrayFile(this.channelsPath),await this.ensureArrayFile(this.eventsPath),await this.ensureArrayFile(this.deliveriesPath)}async addChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),g=$.findIndex((U)=>U.id===_.id);if(g>=0)$[g]={..._,createdAt:$[g].createdAt,updatedAt:new Date().toISOString()};else $.push(_);return await this.writeJson(this.channelsPath,$),g>=0?$[g]:_}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel(_){return(await this.listChannels()).find((g)=>g.id===_)}async removeChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),g=$.filter((U)=>U.id!==_);return await this.writeJson(this.channelsPath,g),g.length!==$.length}async appendEvent(_){await this.init();let $=await this.readJson(this.eventsPath,[]);return $.push(_),await this.writeJson(this.eventsPath,$),_}async appendEventOnce(_,$={}){await this.init();let g=await this.readJson(this.eventsPath,[]);if($.dedupe!==!1){let D=q8(g,{id:_.id,dedupeKey:_.dedupeKey});if(D)return{event:D,stored:!1,deduped:!0,identity:{id:D.id,dedupeKey:D.dedupeKey}}}return g.push(_),await this.writeJson(this.eventsPath,g),{event:_,stored:!0,deduped:!1,identity:{id:_.id,dedupeKey:_.dedupeKey}}}async listEvents(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]);return T8($,_)}async listEventsPage(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]),g=T8($,{eventId:_.eventId,source:_.source,type:_.type}),U=YN(_.cursor,_),D=QN(_.limit),I=g.slice(U,U+D),j=U+I.length,N=j<g.length;return{events:I,cursor:_.cursor,nextCursor:N?k8(j,_):void 0,hasMore:N}}async findEventByIdentity(_){let $=await this.listEvents();return q8($,_)}async appendDelivery(_){await this.init();let $=await this.readJson(this.deliveriesPath,[]);return $.push(_),await this.writeJson(this.deliveriesPath,$),_}async listDeliveries(){return await this.init(),this.readJson(this.deliveriesPath,[])}async exportData(){return{channels:await this.listChannels(),events:await this.listEvents(),deliveries:await this.listDeliveries()}}async ensureArrayFile(_){if(!b8(_))await Q8(_,`[] +`,{encoding:"utf-8",mode:384});await Dz(_,384).catch(()=>{return})}async readJson(_,$){try{let g=await Yv(_,"utf-8");if(!g.trim())return $;return JSON.parse(g)}catch(g){if(g.code==="ENOENT")return $;throw g}}async writeJson(_,$){let g=`${_}.${process.pid}.${Date.now()}.tmp`;await Q8(g,`${JSON.stringify($,null,2)} +`,{encoding:"utf-8",mode:384}),await Qv(g,_),await Dz(_,384).catch(()=>{return})}}function Vv(_=H8()){return{mode:"local-files",name:"json-events-store",remote:!1,localFiles:!0,localSqlite:!1,postgres:!1,s3:!1,aws:!1,durable:!0,idempotency:"best-effort-local",replayCursors:!0,description:`Local JSON files in ${_}; no SQLite, Postgres, S3, or AWS runtime is configured by this store.`}}function k8(_,$={}){if(!Number.isInteger(_)||_<0)throw Error(`Invalid event cursor offset: ${_}`);let g={offset:_,eventId:$.eventId,source:$.source,type:$.type};return`${Nz}${Z8.from(JSON.stringify(g),"utf-8").toString("base64url")}`}function YN(_,$={}){if(!_)return 0;if(!_.startsWith(Nz))throw Error(`Invalid local JSON event cursor: ${_}`);let g=_.slice(Nz.length),U;try{U=JSON.parse(Z8.from(g,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${_}`)}let D=U.offset;if(!Number.isInteger(D)||D<0)throw Error(`Invalid local JSON event cursor: ${_}`);return Uz("eventId",U.eventId,$.eventId),Uz("source",U.source,$.source),Uz("type",U.type,$.type),D}function QN(_){if(_===void 0)return qv;if(!Number.isInteger(_)||_<1)throw Error(`Event page limit must be a positive integer, got ${_}`);return Math.min(_,Bv)}function T8(_,$){let g=_;if($.eventId)g=g.filter((U)=>U.id===$.eventId);if($.source)g=g.filter((U)=>U.source===$.source);if($.type)g=g.filter((U)=>U.type===$.type);if($.cursor){let U=YN($.cursor,$);g=g.slice(U)}if($.limit!==void 0)g=g.slice(0,QN($.limit));return g}function Uz(_,$,g){if($!==g)throw Error(`Local JSON event cursor ${_} filter mismatch`)}function q8(_,$){return _.find((g)=>$.id!==void 0&&g.id===$.id||$.dedupeKey!==void 0&&g.dedupeKey===$.dedupeKey)}async function Fv(_){let $=new GN(_);await $.init();let[g,U,D]=await Promise.all([$.listChannels(),$.listEvents(),$.listDeliveries()]),I=g.reduce((j,N)=>{return j[N.transport]=(j[N.transport]??0)+1,j},{});return{service:"events",schemaVersion:"1.0",dataDir:$.dataDir,storage:$.runtime,env:{primary:XN,fallback:RN,active:Kv()},files:{channels:Iz($.dataDir,"channels.json",g.length),events:Iz($.dataDir,"events.json",U.length),deliveries:Iz($.dataDir,"deliveries.json",D.length)},counts:{channels:g.length,enabledChannels:g.filter((j)=>j.enabled).length,disabledChannels:g.filter((j)=>!j.enabled).length,events:U.length,deliveries:D.length},transports:I,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function Iz(_,$,g){let U=VU(_,$);return{path:U,exists:b8(U),records:g}}function Zv(_,$){return`${_}.${$}`}function bv(_,$,g){return`sha256=${Mv("sha256",_).update(Zv($,g)).digest("hex")}`}function i$(){return new Date().toISOString()}function KU(_,$=4096){return _.length>$?`${_.slice(0,$)}...`:_}function Cv(_,$){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let g=JSON.stringify(_),U=_.time,D={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":_.id,"X-Hasna-Event-Type":_.type,"X-Hasna-Timestamp":U,...$.webhook.headers};if($.webhook.secret)D["X-Hasna-Signature"]=bv($.webhook.secret,U,g);return{body:g,headers:D}}async function rv(_,$,g={}){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let U=i$(),{body:D,headers:I}=Cv(_,$),j=new AbortController,N=setTimeout(()=>j.abort(),$.webhook.timeoutMs??15000);try{let O=await(g.fetchImpl??fetch)($.webhook.url,{method:"POST",headers:I,body:D,signal:j.signal}),A=KU(await O.text());return{attempt:1,status:O.ok?"success":"failed",startedAt:U,completedAt:i$(),responseStatus:O.status,responseBody:A,error:O.ok?void 0:`Webhook returned HTTP ${O.status}`}}catch(O){return{attempt:1,status:"failed",startedAt:U,completedAt:i$(),error:O instanceof Error?O.message:String(O)}}finally{clearTimeout(N)}}async function vv(_,$){if(!$.command)throw Error(`Channel ${$.id} has no command config`);let g=i$(),U=JSON.stringify(_),D={...process.env,...$.command.env,HASNA_CHANNEL_ID:$.id,HASNA_EVENT_ID:_.id,HASNA_EVENT_TYPE:_.type,HASNA_EVENT_SOURCE:_.source,HASNA_EVENT_SUBJECT:_.subject??"",HASNA_EVENT_SEVERITY:_.severity,HASNA_EVENT_TIME:_.time,HASNA_EVENT_DEDUPE_KEY:_.dedupeKey??"",HASNA_EVENT_SCHEMA_VERSION:_.schemaVersion,HASNA_EVENT_JSON:U};return new Promise((I)=>{let j=kv($.command.command,$.command.args??[],{cwd:$.command.cwd,env:D,stdio:["pipe","pipe","pipe"]}),N="",O="",A=setTimeout(()=>j.kill("SIGTERM"),$.command.timeoutMs??15000);j.stdin.end(U),j.stdout.on("data",(L)=>{N+=L.toString()}),j.stderr.on("data",(L)=>{O+=L.toString()}),j.on("error",(L)=>{clearTimeout(A),I({attempt:1,status:"failed",startedAt:g,completedAt:i$(),stdout:KU(N),stderr:KU(O),error:L.message})}),j.on("close",(L,z)=>{clearTimeout(A);let W=L===0;I({attempt:1,status:W?"success":"failed",startedAt:g,completedAt:i$(),stdout:KU(N),stderr:KU(O),error:W?void 0:`Command exited with ${z?`signal ${z}`:`code ${L}`}`})})})}async function fv(_,$,g={}){if($.transport==="webhook")return rv(_,$,g);if($.transport==="command")return vv(_,$);return{attempt:1,status:"skipped",startedAt:i$(),completedAt:i$(),error:`Unsupported transport: ${$.transport}`}}function B8(_,$,g){let U=g.some((D)=>D.status==="success")?"success":g.every((D)=>D.status==="skipped")?"skipped":"failed";return{id:Hv(),eventId:_.id,channelId:$.id,transport:$.transport,status:U,attempts:g,createdAt:g[0]?.startedAt??i$(),completedAt:g.at(-1)?.completedAt??i$()}}class C8 extends Error{eventType;issues;constructor(_,$){let g=$.map((U)=>`${U.path||"<root>"}: ${U.message}`).join("; ");super(`Event validation failed for type "${_}": ${g}`);this.name="EventValidationError",this.eventType=_,this.issues=$}}class r8{definitions=new Map;register(_){return this.definitions.set(_.type,_),this}unregister(_){return this.definitions.delete(_)}has(_){return this.definitions.has(_)}get(_){return this.definitions.get(_)}list(){return[...this.definitions.values()]}validateEvent(_){let $=this.definitions.get(_.type);if(!$)return{ok:!0};return $.validate(_.data,_)}assertEventValid(_){let $=this.validateEvent(_);if(!$.ok)throw new C8(_.type,$.issues)}}var wv=new r8;function jz(_){return{id:_.id??uv(),source:_.source,type:_.type,time:nv(_.time),subject:_.subject,severity:_.severity??"info",data:_.data??{},message:_.message,dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion??"1.0",metadata:_.metadata??{}}}class v8{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor(_={}){this.store=_.store??new GN(_.dataDir),this.redactors=_.redactors??[],this.transportOptions={fetchImpl:_.fetchImpl},this.catalog=_.catalog??wv,this.validateCatalogTypes=_.validateCatalogTypes??!1}async addChannel(_){let $=new Date().toISOString();return this.store.addChannel({..._,createdAt:_.createdAt??$,updatedAt:_.updatedAt??$})}async listChannels(){return this.store.listChannels()}async removeChannel(_){return this.store.removeChannel(_)}async emit(_,$={}){let g=$.redactSensitiveData===!1?jz(_):hv(jz(_));if($.validate??this.validateCatalogTypes)this.catalog.assertEventValid(g);let U=await this.appendEvent(g,{dedupe:$.dedupe!==!1});if(U.deduped)return{event:U.event,deliveries:[],deduped:!0};let D=$.deliver===!1?[]:await this.deliver(U.event);return{event:U.event,deliveries:D,deduped:!1}}async listEvents(_={}){if(Object.keys(_).length===0)return this.store.listEvents();return K8(await this.store.listEvents(),_)}async listEventsPage(_={}){if(this.store.listEventsPage)return this.store.listEventsPage(_);let $=K8(await this.store.listEvents(),{eventId:_.eventId,source:_.source,type:_.type}),g=YN(_.cursor,_),U=QN(_.limit),D=$.slice(g,g+U),I=g+D.length,j=I<$.length;return{events:D,cursor:_.cursor,nextCursor:j?k8(I,_):void 0,hasMore:j}}async listDeliveries(){return this.store.listDeliveries()}async deliver(_){let g=(await this.store.listChannels()).filter((D)=>Y8(D,_)),U=[];for(let D of g){let I=await this.applyRedaction(_,D),j=await this.deliverWithRetry(I,D);await this.store.appendDelivery(j),U.push(j)}return U}async matchChannel(_,$={}){let g=await this.store.getChannel(_);if(!g)throw Error(`Channel not found: ${_}`);let U=jz({source:$.source??"hasna.events",type:$.type??"events.test",subject:$.subject??_,severity:$.severity??"info",data:$.data??{test:!0},message:$.message??"Hasna events test delivery",dedupeKey:$.dedupeKey,schemaVersion:$.schemaVersion,metadata:$.metadata,time:$.time,id:$.id}),D=Y8(g,U);return{channelId:g.id,matched:D,event:U,filters:g.filters,reason:D?void 0:g.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel(_,$={},g={}){let U=await this.store.getChannel(_);if(!U)throw Error(`Channel not found: ${_}`);let D=await this.matchChannel(_,$),I=D.event;if(g.honorFilters&&!D.matched){let O=new Date().toISOString(),A=B8(I,U,[{attempt:1,status:"skipped",startedAt:O,completedAt:O,error:D.reason}]);return A.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(A),A}let j=await this.applyRedaction(I,U),N=await this.deliverWithRetry(j,U);return await this.store.appendDelivery(N),N}async replay(_={}){let $=_.cursor||_.limit!==void 0?await this.listEventsPage(_):{events:await this.listEvents(_),hasMore:!1};if(_.dryRun)return{events:$.events,deliveries:[],cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore};let g=[];for(let U of $.events)g.push(...await this.deliver(U));return{events:$.events,deliveries:g,cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore}}async appendEvent(_,$){if(this.store.appendEventOnce)return this.store.appendEventOnce(_,{dedupe:$.dedupe});if($.dedupe){let U=await this.store.findEventByIdentity({id:_.id,dedupeKey:_.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}let g=await this.store.appendEvent(_);return{event:g,stored:!0,deduped:!1,identity:{id:g.id,dedupeKey:g.dedupeKey}}}async applyRedaction(_,$){let g=xv(_,$.redact?.paths??[],$.redact?.replacement??"[REDACTED]");for(let U of this.redactors)g=await U(g,$);return g}async deliverWithRetry(_,$){let g=dv($.retry),U=[];for(let D=0;D<g.maxAttempts;D+=1){let I=await fv(_,$,this.transportOptions);if(I.attempt=D+1,I.status==="failed"&&D+1<g.maxAttempts)I.nextBackoffMs=Math.round(g.backoffMs*g.multiplier**D);if(U.push(I),I.status!=="failed")break;if(I.nextBackoffMs)await Bun.sleep(I.nextBackoffMs)}return B8(_,$,U)}}function xv(_,$,g="[REDACTED]"){if($.length===0)return _;let U=structuredClone(_);for(let D of $)cv(U,D,g);return U}function f8(_){let $=structuredClone(_);if($.webhook?.secret)$.webhook.secret="[REDACTED]";if($.command?.env)$.command.env=Object.fromEntries(Object.entries($.command.env).map(([g,U])=>[g,w8(g)?"[REDACTED]":U]));return $}function yv(_){return _.map(f8)}function hv(_,$="[REDACTED]"){return Ez(_,$)}function w8(_){return/secret|token|password|api[_-]?key|authorization/i.test(_)}function Ez(_,$){if(Array.isArray(_))return _.map((g)=>Ez(g,$));if(!_||typeof _!=="object")return _;return Object.fromEntries(Object.entries(_).map(([g,U])=>[g,w8(g)?$:Ez(U,$)]))}function cv(_,$,g){let U=$.split("."),D=_;for(let j of U.slice(0,-1)){let N=D[j];if(!N||typeof N!=="object")return;D=N}let I=U.at(-1);if(I&&I in D)D[I]=g}function K8(_,$){let g=_;if($.eventId)g=g.filter((U)=>U.id===$.eventId);if($.source)g=g.filter((U)=>U.source===$.source);if($.type)g=g.filter((U)=>U.type===$.type);if($.cursor)g=g.slice(YN($.cursor,$));if($.limit!==void 0)g=g.slice(0,QN($.limit));return g}function nv(_){if(!_)return new Date().toISOString();return _ instanceof Date?_.toISOString():_}function dv(_){return{maxAttempts:Math.max(1,_?.maxAttempts??1),backoffMs:Math.max(0,_?.backoffMs??250),multiplier:Math.max(1,_?.multiplier??2)}}function WN(_,$,g=!1){if(!_?.length)return;let U={};for(let D of _){let I=lv(D,$),j=I.path;if(j in U)throw Error(`Duplicate ${$} filter path: ${j}`);let N=g?iv(I.rawValue,$):I.rawValue;U[j]=I.negated?{not:N}:N}return U}function mv(_){let $={};if(_.source)$.source=_.source;if(_.type)$.type=_.type;if(_.subject)$.subject=_.subject;if(_.severity)$.severity=_.severity;let g=V8(WN(_.data,"data"),WN(_.dataJson,"data-json",!0)),U=V8(WN(_.metadata,"metadata"),WN(_.metadataJson,"metadata-json",!0));if(Object.keys(g).length>0)$.data=g;if(Object.keys(U).length>0)$.metadata=U;return Object.keys($).length>0?[$]:void 0}function V8(..._){let $={};for(let g of _){if(!g)continue;for(let[U,D]of Object.entries(g)){if(U in $)throw Error(`Duplicate filter path: ${U}`);$[U]=D}}return $}function iv(_,$){let g=JSON.parse(_);if(g===null||typeof g==="string"||typeof g==="number"||typeof g==="boolean"||Array.isArray(g)&&g.every((U)=>typeof U==="string"))return g;throw Error(`${$} filter JSON values must be string, string[], number, boolean, or null`)}function lv(_,$){let g=_.indexOf("!=");if(g>0)return{path:_.slice(0,g),rawValue:_.slice(g+2),negated:!0};let U=_.indexOf("=");if(U<=0)throw Error(`Invalid ${$} filter, expected path=value or path!=value: ${_}`);return{path:_.slice(0,U),rawValue:_.slice(U+1),negated:!1}}var tv=100;function Bg(_,$){if(!_)return $;let g=JSON.parse(_);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Expected a JSON object");return g}function ov(_){if(!_?.length)return;let $={};for(let g of _){let U=g.indexOf("=");if(U===-1)throw Error(`Invalid header, expected name=value: ${g}`);$[g.slice(0,U)]=g.slice(U+1)}return $}function p6(_){if(_.createClient)return _.createClient();return new v8({store:new GN(_.dataDir)})}function s4(_,$,g){if($)console.log(JSON.stringify(_,null,2));else console.log(g)}function F8(_,$){let g=_ instanceof Error?_.message:String(_);if($)console.log(JSON.stringify({error:g},null,2));else console.error(g);process.exitCode=1}function M8(_){return Boolean(_?.json||_?.opts?.().json||_?.optsWithGlobals?.().json||_?.parent?.opts?.().json||_?.parent?.optsWithGlobals?.().json)}function W6(_,$){return M8(_)||M8($)}function pv(_,$){let g=_.command($.channelsCommandName??"channels").description("Manage Hasna event channels");return g.command("add").description("Add or replace a channel").argument("<target>","Webhook URL or command binary").requiredOption("--id <id>","Channel identifier").option("--transport <kind>","Transport kind: webhook or command","webhook").option("--name <name>","Display name").option("--type <pattern>","Event type filter, e.g. todos.task.*").option("--source <pattern>","Event source filter").option("--subject <pattern>","Event subject filter").option("--severity <pattern>","Event severity filter").option("--data <path=value...>","Event data field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",a4,[]).option("--metadata <path=value...>","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",a4,[]).option("--data-json <path=json...>","Event data field filter with typed JSON value; path!=json negatives supported",a4,[]).option("--metadata-json <path=json...>","Event metadata field filter with typed JSON value; path!=json negatives supported",a4,[]).option("--secret <secret>","Webhook HMAC secret").option("--header <name=value...>","Webhook header",a4,[]).option("--arg <arg...>","Command argument",a4,[]).option("--timeout-ms <ms>","Transport timeout in milliseconds",FU).option("--retry-attempts <n>","Maximum delivery attempts",FU).option("--retry-backoff-ms <ms>","Initial retry backoff in milliseconds",FU).option("--redact <path...>","Event field path to redact before delivery",a4,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(U,D,I)=>{let j=new Date().toISOString(),N={id:D.id,name:D.name,enabled:!D.disabled,transport:D.transport,filters:mv(D),retry:D.retryAttempts||D.retryBackoffMs?{maxAttempts:D.retryAttempts,backoffMs:D.retryBackoffMs}:void 0,redact:D.redact?.length?{paths:D.redact}:void 0,createdAt:j,updatedAt:j};if(D.transport==="webhook")N.webhook={url:U,secret:D.secret,headers:ov(D.header),timeoutMs:D.timeoutMs};else if(D.transport==="command")N.command={command:U,args:D.arg??[],timeoutMs:D.timeoutMs};else throw Error(`Transport ${D.transport} is reserved for future use and cannot be added yet`);let O=await p6($).addChannel(N);s4(f8(O),W6(D,I),`Added ${O.transport} channel ${O.id}`)}),g.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(U,D)=>{let I=await p6($).listChannels();if(W6(U,D)){console.log(JSON.stringify(yv(I),null,2));return}if(!I.length){console.log("No channels configured.");return}for(let j of I)console.log(`${j.id} ${j.enabled?"enabled":"disabled"} ${j.transport} ${j.webhook?.url??j.command?.command??j.transport}`)}),g.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(U,D)=>{let I=await Fv($.dataDir);s4(I,W6(U,D),`events dataDir: ${I.dataDir}`)}),g.command("remove").description("Remove a channel").argument("<id>","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(U,D,I)=>{let j=await p6($).removeChannel(U);s4({removed:j},W6(D,I),j?`Removed ${U}`:`Channel not found: ${U}`)}),g.command("test").description("Send a test event to one channel").argument("<id>","Channel identifier").option("--source <source>","Event source override").option("--type <type>","Event type","events.test").option("--subject <subject>","Event subject").option("--message <message>","Event message","Hasna events test delivery").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("--honor-filters","Skip delivery when the sample event does not match channel filters",!1).option("-j, --json","Print JSON output",!1).action(async(U,D,I)=>{let j=W6(D,I);try{let N=await p6($).testChannel(U,{source:D.source??$.source,type:D.type,subject:D.subject??U,message:D.message,data:Bg(D.data,{test:!0}),metadata:Bg(D.metadata,{})},{honorFilters:D.honorFilters});s4(N,j,`${N.status}: ${N.channelId}`)}catch(N){F8(N,j)}}),g.command("match").description("Check whether a sample event matches one channel without delivering").argument("<id>","Channel identifier").option("--source <source>","Event source override").option("--type <type>","Event type","events.test").option("--subject <subject>","Event subject").option("--message <message>","Event message","Hasna events match preview").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("-j, --json","Print JSON output",!1).action(async(U,D,I)=>{let j=W6(D,I);try{let N=await p6($).matchChannel(U,{source:D.source??$.source,type:D.type,subject:D.subject??U,message:D.message,data:Bg(D.data,{test:!0}),metadata:Bg(D.metadata,{})});s4(N,j,`${N.matched?"matched":"skipped"}: ${N.channelId}`)}catch(N){F8(N,j)}}),g}function ev(_,$){let g=_.command($.eventsCommandName??"events").description("Emit, list, and replay Hasna events");g.command("emit").description("Emit an event from this app").argument("<type>","Event type").option("--source <source>","Event source override").option("--subject <subject>","Event subject").option("--severity <severity>","Event severity","info").option("--message <message>","Event message").option("--dedupe-key <key>","Dedupe key").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("--no-deliver","Record without delivering").option("--no-dedupe","Allow duplicate id/dedupeKey events").option("-j, --json","Print JSON output",!1).action(async(D,I,j)=>{let N=await p6($).emit({source:I.source??$.source,type:D,subject:I.subject,severity:I.severity,message:I.message,dedupeKey:I.dedupeKey,data:Bg(I.data,{}),metadata:Bg(I.metadata,{})},{deliver:I.deliver,dedupe:I.dedupe});s4(N,W6(I,j),`${N.deduped?"Deduped":"Emitted"} ${N.event.id} to ${N.deliveries.length} channel(s)`)});let U=$.defaultEventListLimit??tv;return g.command("list").description("List recorded events").option("--source <source>","Filter by source").option("--type <type>","Filter by type").option("--limit <n>",`Limit to the most recent <n> events (default ${U}; use 0 for all)`,FU,U).option("-j, --json","Print JSON output",!1).action(async(D,I)=>{let j=await p6($).listEvents();if(D.source)j=j.filter((N)=>N.source===D.source);if(D.type)j=j.filter((N)=>N.type===D.type);if(D.limit)j=j.slice(-D.limit);if(W6(D,I)){console.log(JSON.stringify(j,null,2));return}if(!j.length){console.log("No events recorded.");return}for(let N of j)console.log(`${N.time} ${N.id} ${N.source} ${N.type} ${N.severity}`)}),g.command("replay").description("Replay recorded events").option("--id <id>","Replay one event id").option("--source <source>","Filter by source").option("--type <type>","Filter by type").option("--cursor <cursor>","Opaque replay cursor from a previous page").option("--limit <n>","Maximum events to replay",FU).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(D,I)=>{let j=await p6($).replay({eventId:D.id,source:D.source,type:D.type,cursor:D.cursor,limit:D.limit,dryRun:D.dryRun});s4(j,W6(D,I),av(j.events.length,j.deliveries.length,j.nextCursor))}),g}function u8(_,$){pv(_,$),ev(_,$)}function FU(_){let $=Number(_);if(!Number.isFinite($))throw Error(`Expected a number, got ${_}`);return $}function a4(_,$){return $.push(_),$}function av(_,$,g){let U=g?`, next cursor: ${g}`:"";return`Replayed ${_} event(s), ${$} delivery result(s)${U}`}import{basename as _f}from"path";var C$={name:"@hasna/knowledge",version:"0.2.93",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. <hasna@example.com>",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.8.5","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};var x8={debug:0,info:1,warn:2,error:3},$f=()=>{if(process.env.DEBUG)return"debug";if(process.env.LOG_LEVEL==="debug")return"debug";if(process.env.LOG_LEVEL==="warn")return"warn";if(process.env.LOG_LEVEL==="error")return"error";return"info"};function $0(_,$,g){if(x8[_]<x8[$f()])return;let U={debug:"[DEBUG]",info:"[INFO]",warn:"[WARN]",error:"[ERROR]"}[_],D=g?`${U} ${$} ${JSON.stringify(g)}`:`${U} ${$}`;if(_==="error")console.error(D);else console.error(D)}var d8=["events","webhooks"],m8=["add","list","get","delete","update","archive","restore","upsert","untag","versions","diff","export","prune","dedupe","stats","inventory","project-panel","paths","mode","setup","auth","storage","machines","sync","db","wiki","app-wiki","source","ingest","reindex","search","context","proposals","web","ask","build","embeddings","providers","safety","help",...d8],i8={ls:"list",rm:"delete",edit:"update",unarchive:"restore"};function gf(_){let $=new Set,g=[];for(let U of _){let D=U.toLowerCase();if($.has(D))continue;$.add(D),g.push(U)}return g}function y8(_,$){let g=new Set((_??[]).map((U)=>U.toLowerCase()));return $.filter((U)=>!g.has(U.toLowerCase()))}function Oz(_,$,g){if(g===void 0)return{..._,message:$};return{..._,added:g.length,message:`${$} (added ${g.length} tag${g.length===1?"":"s"})`}}function Df(_,$){if($===void 0)throw Error("Missing value for --tag. Example: knowledge add <title> <content> -t <tag> -t <tag>");let g=$.split(",").map((U)=>U.trim()).filter((U)=>U.length>0);if(g.length===0)throw Error(`Invalid --tag value ${JSON.stringify($)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return gf([..._??[],...g])}function Uf(_){let $=[],g={},U=!1;for(let D=0;D<_.length;D+=1){let I=_[D];if(U){$.push(I);continue}if(I==="--"){U=!0;continue}if(!I.startsWith("-")||$[0]==="add"&&$.length===2&&I.startsWith("---")){$.push(I);continue}switch(I){case"--json":g.json=!0;break;case"--verbose":g.verbose=!0;break;case"--yes":case"-y":g.yes=!0;break;case"--help":case"-h":g.help=!0;break;case"--version":case"-v":g.version=!0;break;case"--desc":g.desc=!0;break;case"--page":case"-p":g.page=Number(_[D+1]),D+=1;break;case"--limit":case"-l":g.limit=Number(_[D+1]),D+=1;break;case"--search":case"-s":g.search=_[D+1],D+=1;break;case"--sort":g.sort=_[D+1],D+=1;break;case"--id":g.id=_[D+1],D+=1;break;case"--store":g.store=_[D+1],D+=1;break;case"--title":g.title=_[D+1],D+=1;break;case"--content":g.content=_[D+1],D+=1;break;case"--url":g.url=_[D+1],D+=1;break;case"--tag":case"-t":g.tag=Df(g.tag,_[D+1]),g.tagRaw=[...g.tagRaw??[],_[D+1]],D+=1;break;case"--format":g.format=_[D+1],D+=1;break;case"--completions":g.completions=_[D+1],D+=1;break;case"--purpose":g.purpose=_[D+1],D+=1;break;case"--model":g.model=_[D+1],D+=1;break;case"--strategy":g.strategy=_[D+1],D+=1;break;case"--dimensions":g.dimensions=Number(_[D+1]),D+=1;break;case"--semantic":g.semantic=!0;break;case"--context":g.context=!0;break;case"--max-tokens":g.maxTokens=Number(_[D+1]),D+=1;break;case"--max-items":g.maxItems=Number(_[D+1]),D+=1;break;case"--from":g.from=_[D+1],D+=1;break;case"--to":g.to=_[D+1],D+=1;break;case"--rev":g.rev=Number(_[D+1]),D+=1;break;case"--since":g.since=_[D+1],D+=1;break;case"--topic":g.topic=_[D+1],D+=1;break;case"--dedupe":g.dedupe=!0;break;case"--generate":g.generate=!0;break;case"--approve-write":g.approveWrite=!0;break;case"--provider":g.provider=_[D+1],D+=1;break;case"--mode":g.mode=_[D+1],D+=1;break;case"--machine":g.machine=_[D+1],D+=1;break;case"--workspace":g.workspace=_[D+1],D+=1;break;case"--api-url":g.apiUrl=_[D+1],D+=1;break;case"--canonical-example":g.canonicalExample=!0;break;case"--api-key":g.apiKey=_[D+1],D+=1;break;case"--email":g.email=_[D+1],D+=1;break;case"--org":g.org=_[D+1],D+=1;break;case"--org-id":g.orgId=_[D+1],D+=1;break;case"--user-id":g.userId=_[D+1],D+=1;break;case"--owner":g.owner=_[D+1],D+=1;break;case"--approved-by":g.approvedBy=_[D+1],D+=1;break;case"--patch-uri":g.patchUri=_[D+1],D+=1;break;case"--domain":g.domain=[...g.domain??[],_[D+1]],D+=1;break;case"--file-results":g.fileResults=!0;break;case"--full":g.full=!0;break;case"--dry-run":g.dryRun=!0;break;case"--fake":g.fake=!0;break;case"--no-tailscale":g.tailscale=!1;break;case"--no-artifact-content":g.artifactContent=!1;break;case"--no-color":g.noColor=!0;break;case"--scope":g.scope=_[D+1],D+=1;break;case"--tables":g.tables=_[D+1],D+=1;break;case"--peer-workspace":g.peerWorkspace=_[D+1],D+=1;break;case"--older-than":g.olderThan=Number(_[D+1]),D+=1;break;case"--empty":g.empty=!0;break;case"--archived":g.archived=!0;break;case"--include-archived":g.includeArchived=!0;break;case"--project":g.project=_[D+1],D+=1;break;case"--contract":g.contract=!0;break;case"--source-ref":g.sourceRef=[...g.sourceRef??[],_[D+1]],D+=1;break;case"--allow-global":g.allowGlobal=!0;break;default:throw Error(`Unknown flag: ${I}. Run 'knowledge --help' for valid options.`)}}return{positional:$,flags:g}}function If(_){if(!_)return"";return i8[_]??_}function jf(_,$){let g=Array.from({length:_.length+1},()=>Array($.length+1).fill(0));for(let U=0;U<=_.length;U+=1)g[U][0]=U;for(let U=0;U<=$.length;U+=1)g[0][U]=U;for(let U=1;U<=_.length;U+=1)for(let D=1;D<=$.length;D+=1){let I=_[U-1]===$[D-1]?0:1;g[U][D]=Math.min(g[U-1][D]+1,g[U][D-1]+1,g[U-1][D-1]+I)}return g[_.length][$.length]}function Nf(_){if(!_)return"";let $=[...m8,...Object.keys(i8)],g="",U=Number.POSITIVE_INFINITY;for(let D of $){let I=jf(_,D);if(I<U)U=I,g=D}return U<=3?g:""}function Ef(){return _f(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function Of(_){if(!d8.includes(_[0]??""))return!1;let $=new X8;return $.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),u8($,{source:"knowledge"}),await $.parseAsync(_,{from:"user"}),!0}function Af(){console.log(`knowledge - local agent knowledge store Usage: knowledge <command> [options] @@ -1489,60 +1490,60 @@ Export Options: Prune Options: --older-than <days> Remove items older than N days - --empty Remove items with empty content`)}function ko($){if($==="add"){console.log(`Usage: knowledge add <title> <content> [--url <url>] [-t <tag>]... [--json] - -t/--tag is repeatable and accepts comma-separated values: -t a -t b == -t "a,b"`);return}if($==="list"||$==="ls"){console.log(`Usage: knowledge list|ls [--format table|json] [-p <page>] [-l <limit>] [-s <search>] [-t <tag>]... [--sort created|title] [--desc] [--archived] [--include-archived] [--verbose] [--json] + --empty Remove items with empty content`)}function Lf(_){if(_==="add"){console.log(`Usage: knowledge add <title> <content> [--url <url>] [-t <tag>]... [--json] + -t/--tag is repeatable and accepts comma-separated values: -t a -t b == -t "a,b"`);return}if(_==="list"||_==="ls"){console.log(`Usage: knowledge list|ls [--format table|json] [-p <page>] [-l <limit>] [-s <search>] [-t <tag>]... [--sort created|title] [--desc] [--archived] [--include-archived] [--verbose] [--json] -t/--tag is repeatable and accepts comma-separated values; repeated -t narrows (an item must carry every tag). Each value matches an item carrying the whole value OR all of its comma-split names \u2014 a union, so \`-t "a,b,c"\` finds items carrying a legacy literal "a,b,c" tag as well as items carrying the three names separately. (\`untag\` differs on purpose: it stops at the whole-value match.) Use --json to tell those two shapes apart; the table renders them near-identically. Archived items are excluded by default; add --include-archived to sweep both. - If both --archived and --include-archived are passed, --archived wins (archived items only).`);return}if($==="get"){console.log("Usage: knowledge get --id <id> [--json]");return}if($==="update"||$==="edit"){console.log(`Usage: knowledge update|edit --id <id> [--title <title>] [--content <content>] [--url <url>] [-t <tag>]... [--json] + If both --archived and --include-archived are passed, --archived wins (archived items only).`);return}if(_==="get"){console.log("Usage: knowledge get --id <id> [--json]");return}if(_==="update"||_==="edit"){console.log(`Usage: knowledge update|edit --id <id> [--title <title>] [--content <content>] [--url <url>] [-t <tag>]... [--json] -t/--tag is repeatable and accepts comma-separated values; tags are added, never replaced. - With -t the output reports how many tags were actually added, so 0 added is not read as 3.`);return}if($==="archive"){console.log("Usage: knowledge archive --id <id> [--json]");return}if($==="restore"||$==="unarchive"){console.log("Usage: knowledge restore|unarchive --id <id> [--json]");return}if($==="upsert"){console.log(`Usage: knowledge upsert [title] [content] [--id <id>] [--title <title>] [--content <content>] [--url <url>] [-t <tag>]... [--json] + With -t the output reports how many tags were actually added, so 0 added is not read as 3.`);return}if(_==="archive"){console.log("Usage: knowledge archive --id <id> [--json]");return}if(_==="restore"||_==="unarchive"){console.log("Usage: knowledge restore|unarchive --id <id> [--json]");return}if(_==="upsert"){console.log(`Usage: knowledge upsert [title] [content] [--id <id>] [--title <title>] [--content <content>] [--url <url>] [-t <tag>]... [--json] -t/--tag is repeatable and accepts comma-separated values; tags are added, never replaced. - With -t the output reports how many tags were actually added, on both the create and update paths.`);return}if($==="untag"){console.log(`Usage: knowledge untag --id <id> -t <tag>... [--json] + With -t the output reports how many tags were actually added, on both the create and update paths.`);return}if(_==="untag"){console.log(`Usage: knowledge untag --id <id> -t <tag>... [--json] -t/--tag is repeatable and accepts comma-separated values. Each value is matched whole first, and only split on commas if no stored tag equals it, so a legacy literal "a,b,c" tag can still be removed. - Removing nothing exits 1; unmatched names are reported in not_found.`);return}if($==="versions"){console.log(`Usage: knowledge versions --id <id> [-l <limit>] [--json] + Removing nothing exits 1; unmatched names are reported in not_found.`);return}if(_==="versions"){console.log(`Usage: knowledge versions --id <id> [-l <limit>] [--json] Lists the retained prior versions of an item, newest first, with the version the item is at now. An item that exists but was never edited prints an EMPTY history, which is not the same answer as "no such item" (that exits 1) or "this store keeps no history" (also exits 1, naming the store). - Entry history lives in the Postgres-backed store; the local JSON store has no version line.`);return}if($==="diff"){console.log(`Usage: knowledge diff --id <id> [--rev <n>] [--from <a> --to <b>] [--json] + Entry history lives in the Postgres-backed store; the local JSON store has no version line.`);return}if(_==="diff"){console.log(`Usage: knowledge diff --id <id> [--rev <n>] [--from <a> --to <b>] [--json] Default: the latest retained version vs the item as it stands now. --rev <n>: version n vs version n-1. --from <a> --to <b>: two explicit versions, where either side may be "current" to mean the live item. --rev is spelled out because -v is the global --version flag. Reports changed fields (title/url/tags/metadata/archived) as well as a line diff of the body, - so an edit that moved only the tags is not rendered as "no changes".`);return}if($==="delete"||$==="rm"){console.log("Usage: knowledge delete|rm --id <id> -y [--json]");return}if($==="export"){console.log("Usage: knowledge export [--verbose] [--json] [--format json|jsonl]");return}if($==="prune"){console.log("Usage: knowledge prune --yes [--older-than <days>] [--empty] [--json]");return}if($==="dedupe"){console.log("Usage: knowledge dedupe --yes [--json]");return}if($==="stats"){console.log("Usage: knowledge stats [--json]");return}if($==="inventory"){console.log("Usage: knowledge inventory [--scope local|global|project] [--limit <n>] [--include-archived] [--verbose] [--json]");return}if($==="project-panel"){console.log("Usage: knowledge project-panel --project <id|name|slug> [--scope project|local|global] [--limit <n>] [--include-archived] [--json|--contract]");return}if($==="paths"){console.log("Usage: knowledge paths [--scope local|global|project] [--verbose] [--json]");return}if($==="mode"){console.log(`Usage: knowledge mode [--json] - Reports which backend this process would use \u2014 local (on-box store) or cloud (HTTP /v1) \u2014 and + so an edit that moved only the tags is not rendered as "no changes".`);return}if(_==="delete"||_==="rm"){console.log("Usage: knowledge delete|rm --id <id> -y [--json]");return}if(_==="export"){console.log("Usage: knowledge export [--verbose] [--json] [--format json|jsonl]");return}if(_==="prune"){console.log("Usage: knowledge prune --yes [--older-than <days>] [--empty] [--json]");return}if(_==="dedupe"){console.log("Usage: knowledge dedupe --yes [--json]");return}if(_==="stats"){console.log("Usage: knowledge stats [--json]");return}if(_==="inventory"){console.log("Usage: knowledge inventory [--scope local|global|project] [--limit <n>] [--include-archived] [--verbose] [--json]");return}if(_==="project-panel"){console.log("Usage: knowledge project-panel --project <id|name|slug> [--scope project|local|global] [--limit <n>] [--include-archived] [--json|--contract]");return}if(_==="paths"){console.log("Usage: knowledge paths [--scope local|global|project] [--verbose] [--json]");return}if(_==="mode"){console.log(`Usage: knowledge mode [--json] + Reports which backend this process would use \u2014 sqlite (on-box store) or postgres (HTTP /v1) \u2014 and which env var selected it. Reads the environment only: no store is opened, no config file is read, and no request is made, so it is safe on a machine with no config and no network. - Selection is EXPLICIT-ONLY: set ${y4[0]}=local|cloud. Setting only - ${S9[0]} / ${Z9[0]} does NOT switch backends; - those are reported as present-but-ignored pointers. Env var NAMES are printed, never values.`);return}if($==="setup"){console.log("Usage: knowledge setup --mode local|hosted [--api-url https://...] [--canonical-example] [--scope local|global|project] [--json]");return}if($==="auth"){console.log("Usage: knowledge auth login|whoami|logout [--api-key <key>] [--email <email>] [--org <slug>] [--api-url https://...] [--scope local|global|project] [--json]");return}if($==="storage"){console.log(`Usage: knowledge storage status|validate|repair-artifact-keys|migrate-legacy-path|merge-legacy-path [--approve-write --approved-by <name>] [--scope local|global|project] [--json] - knowledge storage import-legacy [--dry-run] [--scope global] [--json]`);return}if($==="machines"){console.log("Usage: knowledge machines topology [--no-tailscale] | preflight [machine] [--workspace <repo>] [--scope local|global|project] [--verbose] [--json]");return}if($==="sync"){console.log(`Usage: knowledge sync status|doctor|readiness|snapshot|machines|conflicts [show|propose|resolve] [id] | dry-run|pull|push|sync|export|import [--peer-workspace <path>] [--machine <ssh-alias>] [--tables <names>] [--dry-run] [--limit <n>] [--approve-write] [--approved-by <name>] [--strategy <name>] [--mode deterministic|ai] [--model <alias|provider:model>] [--fake] [--no-tailscale] [--scope local|global|project] [--verbose] [--json] - -Remote machine sync resolves peer paths through @hasna/machines when --peer-workspace is omitted.`);return}if($==="db"){console.log("Usage: knowledge db init|stats|storage status [--scope local|global|project] [--json]");return}if($==="wiki"){console.log("Usage: knowledge wiki init|compile|file-answer|lint [query|prompt] [--title <title>] [--content <answer>] [--approve-write] [--limit <n>] [--scope local|global|project] [--json]");return}if($==="app-wiki"){console.log("Usage: knowledge app-wiki init | note add|get|list | source add <source-ref> | search <query> | query <query> [--title <title>] [--content <text>] [--tag <tag>] [--source-ref <uri>] [--scope project|local|global] [--allow-global] [--json]");return}if($==="source"){console.log("Usage: knowledge source resolve <source-ref> [--purpose knowledge_answer|knowledge_index] [--limit <n>] [--scope local|global|project] [--json]");return}if($==="ingest"){console.log("Usage: knowledge ingest manifest <file|s3://bucket/key> | source <source-ref> | rules [--workspace <path>] [--owner <name>] [--dry-run] [--max-items <n>] [--limit <n>] [--purpose knowledge_index] [--scope local|global|project] [--json]");return}if($==="reindex"){console.log("Usage: knowledge reindex status|enqueue|embeddings|outbox [file|s3://bucket/key] [--full] [--fake] [--scope local|global|project] [--json]");return}if($==="search"){console.log("Usage: knowledge search <query> [--context] [--semantic] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="context"){console.log("Usage: knowledge context pack <query> [--from search|runs|loops] [--max-tokens <n>] [--max-items <n>] [--limit <n>] [--semantic] [--model openai:text-embedding-3-small] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="proposals"){console.log("Usage: knowledge proposals context --from loops --topic <text> [--since <duration|ISO>] [--dedupe] [--max-tokens <n>] [--max-items <n>] [--scope local|global|project] [--json]");return}if($==="web"){console.log("Usage: knowledge web search <query> [--provider openai|anthropic] [--model provider:model] [--domain <domain>] [--file-results] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="ask"||$==="build"){console.log("Usage: knowledge ask|build <prompt> [--generate] [--semantic] [--model default|provider:model] [--approve-write] [--scope local|global|project] [--verbose] [--json]");return}if($==="embeddings"){console.log("Usage: knowledge embeddings status|index|search [query] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="providers"){console.log("Usage: knowledge providers status|models|check [provider|model-alias] [--scope local|global|project] [--json]");return}if($==="safety"){console.log("Usage: knowledge safety status|check|approve|audit|redact [args] [--scope local|global|project] [--json]");return}if($==="events"){console.log("Usage: knowledge events emit|list|replay [args] [--json]");return}if($==="webhooks"){console.log("Usage: knowledge webhooks add|list|remove|test [args] [--json]");return}go()}function Io($){if($.noColor||process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR)return!0;return process.stdout.isTTY===!0}function h($,_,J){if(_){console.log(JSON.stringify($,null,2));return}if(typeof $==="string"){console.log($);return}if(J?.verbose){console.log(JSON.stringify($,null,2));return}let U=$.message;console.log(U?`${U} -${m_()}`:fo($))}function m_($="full details"){return`Hint: use --verbose for ${$}, or --json for machine-readable output.`}function v$($,_=120){let J=$===null||$===void 0?"":String($).replace(/\s+/g," ").trim();if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-3))}...`}function fo($){if(!$||typeof $!=="object")return String($);let _=$,J=[_.ok===!1?"Result: not ok":"Result: ok"];for(let[U,W]of Object.entries(_).slice(0,8)){if(U==="ok"||U==="message")continue;if(Array.isArray(W))J.push(`${U}: ${W.length} item(s)`);else if(W&&typeof W==="object")J.push(`${U}: ${Object.keys(W).length} field(s)`);else J.push(`${U}: ${v$(W,100)}`)}return J.push(m_()),J.join(` -`)}function Co($){let _=$.mode==="cloud"?"cloud (HTTP /v1 API)":"local (on-box store)",J=$.source.kind==="env"?`selected by ${$.source.name}=${$.source.value}`:`default (no mode var set; set ${y4[0]}=cloud to use the API)`,U=[`Knowledge mode: ${_}`,` ${J}`];if($.pointer_env_present.length>0){let W=$.pointer_ignored?"present but IGNORED for mode selection":"present";U.push(` Pointer env ${W}: ${$.pointer_env_present.join(", ")}`)}if($.network_guard_active)U.push(" Outbound guard: ACTIVE (NODE_ENV=test) \u2014 non-loopback requests are refused.");if($.warning)U.push(` Note: ${$.warning}`);return U.join(` -`)}function Po($){return[`Knowledge paths (${$.scope})`,`Home: ${$.home}`,`SQLite: ${$.knowledge_db_path}`,`JSON store: ${$.json_store_path}`,`Wiki: ${$.wiki_dir}`,m_("config and all paths")].join(` -`)}function VA($){console.log(JSON.stringify($))}function To($){let _=$.summary,J=[`Knowledge inventory (${$.scope})`,`Home: ${$.home}`,`JSON store: ${$.paths.json_store_path}${$.paths.json_store_exists?"":" (missing)"}`,`SQLite catalog: ${$.paths.knowledge_db_path}`,`Summary: ${_.legacy_items} item(s), ${_.sources} source(s), ${_.chunks} chunk(s), ${_.wiki_pages} wiki page(s), ${_.indexes} index(es), ${_.storage_objects} artifact(s), ${_.runs} run(s)`],U=(W,X,G)=>{if(X.length===0)return;J.push("",`${W}:`);for(let Y of X.slice(0,$.limit))J.push(`- ${G(Y)}`)};return U("Items",$.items,(W)=>`${W.id}: ${W.title}`),U("Sources",$.sources,(W)=>`${W.kind??"source"} ${W.uri} (${W.chunks??0} chunk(s))`),U("Chunks",$.chunks,(W)=>`${W.kind??"chunk"} ${W.id}: ${W.text_preview??""}`),U("Wiki pages",$.wiki_pages,(W)=>`${W.path}: ${W.title}`),U("Indexes",$.indexes,(W)=>`${W.kind??"index"} ${W.name}${W.shard_key?` (${W.shard_key})`:""}`),U("Artifacts",$.storage_objects,(W)=>`${W.kind??"artifact"} ${W.artifact_uri}`),U("Runs",$.runs,(W)=>`${W.type??"run"} ${W.id}: ${W.status??"unknown"}`),U("Machines",$.machines,(W)=>`${W.machine_id}${W.workspace_home?` ${W.workspace_home}`:""}`),U("Sync conflicts",$.sync_conflicts,(W)=>`${W.id}: ${W.entity_kind}/${W.entity_id} ${W.status}`),J.join(` -`)}function So($){let _=Array.isArray($.results)?$.results:[],J=[`${_.length} search result(s) for "${v$($.query,80)}"${$.mode?.semantic?" (semantic enabled)":""}`];for(let U of _.slice(0,$.limit??10)){let W=U.source?.uri??U.provenance?.source_uri??U.artifact?.path??U.artifact?.uri??U.id,X=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(J.push(`- ${U.kind??"result"} ${v$(U.title??U.id,80)}${X}`),W)J.push(` source: ${v$(W,120)}`);if(U.text)J.push(` text: ${v$(U.text,180)}`)}if(_.length===0)J.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(J.push(m_("scores, provenance, and full result objects")),!$.context)J.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return J.join(` -`)}function Zo($){let _=Array.isArray($.excerpts)?$.excerpts:[],J=Array.isArray($.citations)?$.citations:[],U=[`${_.length} context excerpt(s) for "${v$($.query??$.normalized_query,80)}"`];for(let W of _.slice(0,10)){let X=J.find((Q)=>Q.id===W.citation_id||Q.result_id===W.result_id),G=X?.source_uri??X?.artifact_path??W.result_id,Y=typeof W.score==="number"?` score=${W.score.toFixed(3)}`:"";if(U.push(`- ${W.kind??"excerpt"} ${v$(W.id,44)}${Y}`),G)U.push(` source: ${v$(G,120)}`);U.push(` text: ${v$(W.text,220)}`)}return U.push(`Citations: ${J.length}`),U.push(m_("citations, graph, notes, and full excerpts")),U.join(` -`)}function vo($){let _=Array.isArray($.results)?$.results:[],J=[`${_.length} semantic result(s) for "${v$($.query,80)}"`,`Index: ${$.provider??"unknown"}:${$.model??"unknown"} (${$.dimensions??"?"} dimensions)`];for(let U of _.slice(0,$.limit??10)){let W=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(J.push(`- ${v$(U.chunk_id,44)}${W}`),U.source_uri)J.push(` source: ${v$(U.source_uri,120)}`);if(U.text)J.push(` text: ${v$(U.text,180)}`)}return J.push(m_("provenance and full vector result objects")),J.join(` -`)}function yo($){let _=Array.isArray($.sources)?$.sources:[],J=[`${_.length} web source(s) for "${v$($.query,80)}"`,`Provider: ${$.provider??"unknown"}${$.model?` (${$.model})`:""}`];for(let U of _.slice(0,$.limit??10)){J.push(`- ${v$(U.title??U.url??U.uri??"source",100)}`);let W=U.url??U.uri??U.source_ref;if(W)J.push(` url: ${v$(W,140)}`);if(U.snippet)J.push(` snippet: ${v$(U.snippet,180)}`)}return J.push(m_("provider payloads and filed source refs")),J.join(` -`)}function ho($){let _=Array.isArray($.machines)?$.machines:[],J=[`${_.length} machine(s) discovered via ${$.source??"unknown"}`,`Adapter: ${$.adapter?.package??"@hasna/machines"} ${$.adapter?.available?"available":"unavailable"}`];for(let U of _.slice(0,10)){let W=U.local?" local":"",X=U.tailscale_dns??U.ssh_target??U.hostname??"";J.push(`- ${v$(U.machine_id??U.id??"unknown",48)}${W}${X?` -> ${v$(X,80)}`:""}`)}if(_.length>10)J.push(`... ${_.length-10} more machine(s).`);if(Array.isArray($.warnings)&&$.warnings.length>0)J.push(`Warnings: ${$.warnings.slice(0,3).join("; ")}`);return J.push(m_("full topology, route hints, and adapter evidence")),J.join(` -`)}function mo($){let _=Array.isArray($.checks)?$.checks:[],J=_.filter((X)=>X.status==="fail"||X.severity==="fail"),U=_.filter((X)=>X.status==="warn"||X.severity==="warn"),W=[`Machine preflight ${$.ok?"passed":"needs attention"} for ${$.machine_id??$.requested_machine_id??"local"}`,`Checks: ${_.length} total, ${J.length} failed, ${U.length} warning(s)`];for(let X of[...J,...U].slice(0,8))W.push(`- ${X.status??X.severity??"check"} ${v$(X.id??X.kind??"check",72)}: ${v$(X.message??X.detail??"",140)}`);return W.push(m_("all checks and repair hints")),W.join(` -`)}function xo($){return[`Sync status (${$.scope??"scope"})`,`Schema: v${$.sqlite_schema_version??"unknown"}`,`Machines: ${$.machines?.total??0}; snapshots: ${$.snapshots?.total??0}; open conflicts: ${$.conflicts?.open??0}`,`Tables: ${Object.entries($.table_counts??{}).slice(0,8).map(([J,U])=>`${J}=${U}`).join(", ")||"none"}`,m_("registry rows, clocks, snapshots, imports, and conflicts")].join(` -`)}function uo($){let _=Array.isArray($.warnings)?$.warnings:[],J=Array.isArray($.recommended_commands)?$.recommended_commands:[],U=[$.message??`Sync readiness ${$.ok?"ok":"needs attention"}`,`Storage: ${$.storage?.validation?.ok?"ok":"needs attention"}; open-files: ${$.open_files?.ok?"ok":"needs attention"}; open conflicts: ${$.sync?.open_conflicts??0}`];if(_.length>0)U.push(`Warnings: ${_.slice(0,5).join("; ")}`);for(let W of J.slice(0,5))U.push(`- next: ${v$(W.shell_command??W.command?.join(" ")??W.id,160)}`);return U.push(m_("diagnostics, route evidence, and all recommended commands")),U.join(` -`)}function no($){let _=$.snapshot??{};return[`Sync snapshot ${$.ok?"recorded":"failed"}`,`Snapshot: ${v$(_.id??_.snapshot_id??"unknown",80)} ${_.content_hash?`(${v$(_.content_hash,80)})`:""}`,`Machines upserted: ${$.machines_upserted??0}; machine: ${$.machine_id??_.machine_id??"unknown"}`,m_("snapshot payload and topology evidence")].join(` -`)}function co($){let _=Array.isArray($.conflicts)?$.conflicts:[],J=[`${_.length} sync conflict(s)`];for(let U of _.slice(0,10))J.push(`- ${v$(U.id,48)} ${U.status??"unknown"} ${U.entity_kind??""}/${v$(U.entity_id,80)}`);return J.push("Next: use `knowledge sync conflicts show <id> --json` for one conflict."),J.push(m_("full conflict objects")),J.join(` -`)}function io($){let _=Array.isArray($.machines)?$.machines:[],J=[`${_.length} registered sync machine(s)`];for(let U of _.slice(0,10))J.push(`- ${v$(U.machine_id,48)} ${v$(U.hostname??U.workspace_home??"",100)}`);return J.push(m_("machine registry rows")),J.join(` -`)}function RA($,_){let J=[`Sync ${_} ${$.ok===!1?"needs attention":"completed"}${$.dry_run?" (dry run)":""}`],U=(W,X)=>{if(!X)return;let Y=(Array.isArray(X.tables)?X.tables:[]).reduce((L,N)=>L+(N.inserted??0)+(N.updated??0)+(N.deleted??0),0),Q=X.artifacts?.copied??0,q=Array.isArray(X.errors)?X.errors.length:0;J.push(`${W}: ${Y} table row change(s), ${Q} artifact(s), ${q} error(s)`)};if(U("pull",$.pull),U("push",$.push),Array.isArray($.errors)&&$.errors.length>0)J.push(`Errors: ${$.errors.slice(0,3).map((W)=>v$(W,120)).join("; ")}`);return J.push(m_("per-table rows, artifacts, clocks, and errors")),J.join(` -`)}function lo($){let _=Array.isArray($.citations)?$.citations:[],J=Array.isArray($.context?.excerpts)?$.context.excerpts:Array.isArray($.excerpts)?$.excerpts:[],U=[$.generated?"Generated answer with citations":"Prepared citation context draft",`Citations: ${_.length}; excerpts: ${J.length}`];if($.answer)U.push(`Answer: ${v$($.answer,500)}`);for(let W of _.slice(0,5))U.push(`- ${v$(W.source_uri??W.ref??W.id,120)}`);return U.push(m_("full answer payload, context, citations, and run ledger")),U.join(` -`)}function ro($,_){return[`Export preview: ${$.length} item(s) available`,"Default output is compact to avoid terminal/context bloat.","Use --verbose or --json for a JSON object, or --format jsonl for newline-delimited records.",_!=="json"?`Requested format: ${_}`:""].filter(Boolean).join(` -`)}function KA($){return!$||$==="local"||$==="localhost"}function E2($){if(!$.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function po($,_){let J=_.sort??"created";if(J!=="created"&&J!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let U=[...$].sort((W,X)=>{if(J==="title")return W.title.localeCompare(X.title);return W.created_at.localeCompare(X.created_at)});if(_.desc)U.reverse();return{sorted:U,sort:J,direction:_.desc?"desc":"asc"}}async function oo($){if(await wo($))return;let{positional:_,flags:J}=Fo($);if(M2("debug","CLI invoked",{command:_[0],flags:{json:J.json,store:J.store}}),J.version){console.log(J.json?JSON.stringify({name:s6.name,version:s6.version},null,2):`${s6.name} ${s6.version}`);return}if(J.completions){let B=J.completions;if(B==="bash")console.log('_knowledge() { local cur; cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive --json --verbose --yes --help --version --desc --page --limit --search --sort --id --store --title --content --url --tag --rev --to --format --completions --purpose --model --dimensions --semantic --context --max-tokens --max-items --from --since --topic --dedupe --generate --approve-write --provider --mode --machine --workspace --peer-workspace --api-url --canonical-example --api-key --email --org --org-id --user-id --owner --domain --file-results --full --dry-run --fake --no-tailscale --no-artifact-content --no-color --scope --tables --archived --include-archived --project --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(B==="zsh")console.log(`#compdef knowledge -_knowledge() { _arguments -C "1: :(add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive)" "(--json)--json" "(--verbose)--verbose" "(--yes)-y" "(--help)--help" "(--version)--version" "(--desc)--desc" "(--archived)--archived" "(--include-archived)--include-archived" "(--semantic)--semantic" "(--context)--context" "(--dedupe)--dedupe" "(--generate)--generate" "(--approve-write)--approve-write" "(--canonical-example)--canonical-example" "(--file-results)--file-results" "(--full)--full" "(--dry-run)--dry-run" "(--fake)--fake" "(--no-tailscale)--no-tailscale" "(--no-artifact-content)--no-artifact-content" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(-s --search)"{-s,--search}"[search text]:text:" "(--sort)--sort"{created,title}:" "(--id)--id[item id]:id:" "(--store)--store[store path]:path:" "(--title)--title[new title]:" "(--content)--content[new content]:" "(--url)--url[source url]:" "(-t --tag)"{-t,--tag}"[tag]:tag:" "(--format)--format[json|jsonl]:" "(--completions)--completions[output completions]:shell:(bash zsh fish):" "(--purpose)--purpose[purpose]:" "(--model)--model[model ref]:" "(--dimensions)--dimensions[embedding dimensions]:number:" "(--max-tokens)--max-tokens[token budget]:number:" "(--max-items)--max-items[item budget]:number:" "(--from)--from"{search,loops,runs}:" "(--to)--to[diff target: version number or current]:" "(--rev)--rev[entry version for diff]:number:" "(--since)--since[duration or ISO time]:" "(--topic)--topic[topic text]:" "(--provider)--provider[provider]:" "(--mode)--mode"{local,hosted}:" "(--machine)--machine[machine id or SSH alias]:" "(--workspace)--workspace[repo workspace path]:path:" "(--peer-workspace)--peer-workspace[peer repo or knowledge home path]:path:" "(--api-url)--api-url[hosted API URL]:" "(--api-key)--api-key[hosted API key]:" "(--email)--email[email]:" "(--org)--org[org slug]:" "(--org-id)--org-id[org id]:" "(--user-id)--user-id[user id]:" "(--owner)--owner[provenance owner]:" "(--domain)--domain[domain]:" "(--project)--project[project id/name/slug]:" "(--source-ref)--source-ref[source ref]:" "(--no-color)--no-color[disable color]" "(--scope)--scope"{local,global,project}:" "(--tables)--tables[comma-separated DB sync tables]:" }; _knowledge`);else if(B==="fish")console.log('complete -c knowledge -f; complete -c knowledge -a "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive"; complete -c knowledge -l json; complete -c knowledge -l verbose; complete -c knowledge -l yes -s y; complete -c knowledge -l help -s h; complete -c knowledge -l version -s v; complete -c knowledge -l desc; complete -c knowledge -l archived; complete -c knowledge -l include-archived; complete -c knowledge -l semantic; complete -c knowledge -l context; complete -c knowledge -l max-tokens; complete -c knowledge -l max-items; complete -c knowledge -l from -a "search loops runs"; complete -c knowledge -l to; complete -c knowledge -l rev; complete -c knowledge -l since; complete -c knowledge -l topic; complete -c knowledge -l dedupe; complete -c knowledge -l generate; complete -c knowledge -l approve-write; complete -c knowledge -l allow-global; complete -c knowledge -l canonical-example; complete -c knowledge -l provider; complete -c knowledge -l mode; complete -c knowledge -l machine; complete -c knowledge -l workspace; complete -c knowledge -l peer-workspace; complete -c knowledge -l api-url; complete -c knowledge -l api-key; complete -c knowledge -l email; complete -c knowledge -l org; complete -c knowledge -l org-id; complete -c knowledge -l user-id; complete -c knowledge -l owner; complete -c knowledge -l domain; complete -c knowledge -l project; complete -c knowledge -l contract; complete -c knowledge -l source-ref; complete -c knowledge -l file-results; complete -c knowledge -l full; complete -c knowledge -l dry-run; complete -c knowledge -l fake; complete -c knowledge -l no-tailscale; complete -c knowledge -l no-artifact-content; complete -c knowledge -s p -l page; complete -c knowledge -s l -l limit; complete -c knowledge -s s -l search; complete -c knowledge -l sort; complete -c knowledge -l id; complete -c knowledge -l store; complete -c knowledge -l title; complete -c knowledge -l content; complete -c knowledge -l url; complete -c knowledge -s t -l tag; complete -c knowledge -l format; complete -c knowledge -l completions; complete -c knowledge -l purpose; complete -c knowledge -l model; complete -c knowledge -l dimensions; complete -c knowledge -l no-color; complete -c knowledge -l scope -a "local global project"; complete -c knowledge -l tables');else throw Error("Invalid --completions value. Use 'bash', 'zsh', or 'fish'.");return}let U=Eo(_[0]),W=1,X=_.length>1||/\s/.test(U);if(bo()&&U&&!EA.includes(U)&&X)U="ask",W=0;if(!U||J.help||U==="help"){let B=U==="help"?_[1]:U||_[1];ko(B);return}if(U==="mode"){let B=lN(process.env);h(J.json||J.verbose?{ok:!0,...B}:Co(B),J.json,J);return}iN(process.env,{storePathOverridden:Boolean(J.store)});let G=U==="project-panel"||U==="app-wiki"?J.scope??"project":J.scope,Y=$Y({scope:G});if(U==="storage"){let B=_[1]??"status";if(B==="import-legacy"){if(J.scope&&J.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let H=IY({dryRun:J.dryRun});if(h(H,J.json),!H.ok)process.exitCode=1;return}if(B==="migrate-legacy-path"||B==="migrate-legacy"||B==="migrate-path"){let H=Y.migrateLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}if(B==="merge-legacy-path"||B==="merge-legacy"||B==="merge-path"){let H=Y.mergeLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}}let Q=Boolean(J.store),q=J.store;if(!q)if(G==="project"||G==="local")q=Y.workspace.jsonStorePath;else q=B9();if(!Q&&(U==="ask"||U==="build")&&!K0())lW(q);let L=y9({storePath:q,storePathOverridden:Q});if(U==="inventory"){let B=await Y.resolveInventory({limit:J.limit,includeArchived:J.includeArchived||J.archived,storePath:K0()?void 0:q});h(J.json||J.verbose?B:To(B),J.json,J);return}if(U==="project-panel"){let B=J.project??_[1];if(!B)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let H=await MM(B,{service:Y,limit:J.limit,storePath:K0()?void 0:q,includeArchived:J.includeArchived||J.archived});h(J.json||J.contract?H:AM(H),J.json||J.contract);return}if(U==="paths"){let B=Y.paths();h(J.json||J.verbose?B:Po(B),J.json,J);return}if(U==="setup"){let B=Y.setup({mode:J.mode,apiUrl:J.apiUrl,canonicalExample:J.canonicalExample});h(B,J.json,J);return}if(U==="auth"){let B=_[1]??"whoami";if(B==="whoami"||B==="status"){let H=Y.authStatus(process.env);h({ok:!0,...H,message:H.authenticated?`Authenticated via ${H.source}`:"Not authenticated"},J.json,J);return}if(B==="login"){let H=J.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!H)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let V=Y.saveAuth({apiKey:H,email:J.email,orgSlug:J.org,orgId:J.orgId,userId:J.userId,apiUrl:J.apiUrl},process.env);h({ok:!0,authenticated:!0,email:V.email??null,org_slug:V.org_slug??null,api_url:V.api_url??Y.authStatus(process.env).api_url,auth_path:Y.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${V.email??"API key"}`},J.json,J);return}if(B==="logout"){let H=Y.clearAuth(process.env);h({ok:!0,removed:H,message:H?"Removed hosted credentials":"No hosted credentials found"},J.json,J);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(U==="storage"){let B=_[1]??"status";if(B==="status"){let H=Y.storageContract(),V=Y.validateStorage();h({ok:V.ok,...H,validation:V,message:`${H.storage_type} artifact storage at ${H.artifact_store.uri_prefix}`},J.json,J);return}if(B==="validate"){let H=Y.validateStorage();if(h({ok:H.ok,validation:H,message:H.ok?"Storage contract valid":`Storage contract invalid: ${H.errors.join("; ")}`},J.json,J),!H.ok)process.exitCode=1;return}if(B==="repair-artifact-keys"||B==="repair-keys"){let H=Y.repairArtifactManifestKeys({approveWrite:J.approveWrite,approvedBy:J.approvedBy,dryRun:J.dryRun});h(H,J.json,J);return}if(B==="migrate-legacy-path"||B==="migrate-legacy"||B==="migrate-path"){let H=Y.migrateLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}if(B==="merge-legacy-path"||B==="merge-legacy"||B==="merge-path"){let H=Y.mergeLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid storage action. Use 'status', 'validate', 'repair-artifact-keys', 'migrate-legacy-path', 'merge-legacy-path', or 'import-legacy'.")}if(U==="machines"){let B=_[1]??"topology";if(B==="topology"||B==="status"){let H=await Y.machineTopology({includeTailscale:J.tailscale!==!1});h(J.json||J.verbose?H:ho(H),J.json,J);return}if(B==="preflight"||B==="check"){let H=_[2]??J.machine??"local",V=J.workspace??process.cwd(),K=await Y.machinePreflight({machineId:H,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:s6.name,command:"knowledge",expectedVersion:s6.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:V,expectedPackageName:s6.name,expectedVersion:s6.version,required:!0}]});if(h(J.json||J.verbose?K:mo(K),J.json,J),!K.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(U==="sync"){let B=_[1]??"status",H=J.tables?J.tables.split(",").map((V)=>V.trim()).filter(Boolean):void 0;if(B==="status"){let V=Y.syncStatus();h(J.json||J.verbose?V:xo(V),J.json,J);return}if(B==="doctor"||B==="readiness"||B==="preflight"){let V=await Y.syncDoctor({machine:J.machine??null,peerWorkspace:J.peerWorkspace??null,includeTailscale:J.tailscale!==!1,tables:H}),K={package:{name:s6.name,version:s6.version},...V};if(h(J.json||J.verbose?K:uo(K),J.json,J),!V.ok&&!J.json)process.exitCode=1;return}if(B==="snapshot"||B==="record"){let V=await Y.createSyncSnapshot({includeTailscale:J.tailscale!==!1,machineId:J.machine});h(J.json||J.verbose?V:no(V),J.json,J);return}if(B==="conflicts"||B==="conflict"){let V=_[2];if(V==="show"||V==="get"){let F=_[3]??J.id;if(!F)throw Error("Usage: knowledge sync conflicts show <id>");let w=Y.syncConflict(F);h({ok:!0,conflict:w,message:`Sync conflict ${F}`},J.json,J);return}if(V==="propose"||V==="proposal"){let F=_[3]??J.id;if(!F)throw Error("Usage: knowledge sync conflicts propose <id>");h(J.mode==="ai"?await Y.proposeSyncConflictResolutionWithAi({id:F,modelRef:J.model,fake:J.fake}):Y.proposeSyncConflictResolution(F),J.json,J);return}if(V==="resolve"){let F=_[3]??J.id;if(!F)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let w=Y.resolveSyncConflict({id:F,strategy:J.strategy,approvedBy:J.approvedBy,approveWrite:J.approveWrite,proposedPatchUri:J.patchUri});if(h(w,J.json,J),!w.ok&&!J.json)process.exitCode=1;return}let K=Y.syncConflicts({status:V,limit:J.limit}),E={ok:!0,conflicts:K,message:`${K.length} sync conflict(s)`};h(J.json||J.verbose?E:co(E),J.json,J);return}if(B==="machines"||B==="registry"){let V=Y.syncMachines(),K={ok:!0,machines:V,message:`${V.length} registered sync machine(s)`};h(J.json||J.verbose?K:io(K),J.json,J);return}if(B==="export"){let V=Y.exportSyncBundle({machineId:J.machine??null,tables:H,includeArtifactContent:J.artifactContent!==!1});h(V,!0);return}if(B==="import"){let V=await Bun.stdin.text();if(!V.trim())throw Error("Usage: knowledge sync import < bundle.json");let K=await Y.importSyncBundle({bundle:JSON.parse(V),dryRun:J.dryRun,direction:"import",machineId:J.machine??null});h(J.json||J.verbose?K:RA(K,B),J.json,J);return}if(B==="dry-run"||B==="pull"||B==="push"||B==="sync"){if(!J.peerWorkspace&&KA(J.machine))throw Error(`Usage: knowledge sync ${B} --peer-workspace <repo-or-knowledge-home> [--scope project] -Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let V=B==="dry-run"?"both":B==="sync"?"both":B,K=!KA(J.machine)?await Y.syncRemotePeer({direction:V,machine:J.machine,peerWorkspace:J.peerWorkspace,tables:H,dryRun:J.dryRun===!0||B==="dry-run",includeArtifactContent:J.artifactContent!==!1,includeTailscale:J.tailscale!==!1}):await Y.syncPeer({peerWorkspace:J.peerWorkspace,direction:V,dryRun:J.dryRun===!0||B==="dry-run",tables:H,includeArtifactContent:J.artifactContent!==!1,machineId:J.machine??null});if(h(J.json||J.verbose?K:RA(K,B),J.json,J),!K.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid sync action. Use 'status', 'doctor', 'snapshot', 'conflicts', 'machines', 'dry-run', 'pull', 'push', 'sync', 'export', or 'import'.")}if(U==="db"){let B=_[1]??"init";if(B==="init"){let H=Y.initDb();h({ok:!0,...H,message:`Initialized ${H.path}`},J.json,J);return}if(B==="stats"){let H=Y.dbStats();h({ok:!0,path:Y.workspace.knowledgeDbPath,...H,message:`knowledge.db schema v${H.schema_version}`},J.json,J);return}if(B==="storage"){if((_[2]??"status")==="status"){let V=qB({scope:J.scope});h({ok:!0,...V,message:`knowledge.db storage mode ${V.mode}`},J.json,J);return}throw Error("Invalid db storage action. Only 'status' is supported. The 'push'/'pull'/'sync' Postgres sync commands were removed (DSN-on-client is forbidden); use the cloud API flip instead.")}throw Error("Invalid db action. Use 'init', 'stats', or 'storage'.")}if(U==="app-wiki"){let B=_[1]??"init";if(B==="paths"||B==="status"){h({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...Y.paths()},J.json);return}if(B==="init"||B==="open"){let H=await Y.initAppWiki({allowGlobal:J.allowGlobal});h(H,J.json);return}if(B==="note"||B==="notes"){let H=_[2]??"list";if(H==="add"||H==="create"){let V=J.title??_[3],K=J.content??_.slice(4).join(" ");if(!V||!K)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let E=await Y.addAppWikiNote({title:V,content:K,tags:J.tag,sourceRefs:J.sourceRef,allowGlobal:J.allowGlobal});h(E,J.json);return}if(H==="list"||H==="ls"){let V=Y.listAppWikiNotes({limit:J.limit});h({ok:!0,scope:Y.scope,home:Y.workspace.home,notes:V,message:`${V.length} app wiki note(s)`},J.json);return}if(H==="get"||H==="show"){let V=_[3]??J.id;if(!V)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let K=await Y.getAppWikiNote(V,{includeContent:!0});if(!K)throw Error(`App wiki note not found: ${V}`);h(K,J.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(B==="source"||B==="sources"){let H=_[2]??"add";if(H!=="add"&&H!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let V=_[3]??J.sourceRef?.[0];if(!V)throw Error("Usage: knowledge app-wiki source add <source-ref>");let K=await Y.addAppWikiSourceRef({sourceRef:V,purpose:J.purpose,allowGlobal:J.allowGlobal});h({ok:!0,...K,message:`Added app wiki source ${K.source_ref}`},J.json);return}if(B==="search"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge app-wiki search <query>");let V=await Y.searchAppWiki({query:H,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V,message:`${V.results.length} app wiki result(s)`},J.json);return}if(B==="query"||B==="context"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge app-wiki query <query>");let V=await Y.queryAppWiki({query:H,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V,message:`${V.excerpts.length} app wiki excerpt(s)`},J.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(U==="wiki"){let B=_[1]??"init";if(B==="init"){let H=await Y.initWiki();h({ok:!0,...H,message:`Initialized wiki layout in ${Y.workspace.home}`},J.json,J);return}if(B==="compile"){let H=_.slice(2),V=H.filter((F)=>/^(open-files|file|s3|https?):\/\//.test(F)),K=H.filter((F)=>!/^(open-files|file|s3|https?):\/\//.test(F)).join(" "),E=await Y.compileWiki({title:J.title,query:K||J.search,sourceRefs:V.length>0?V:void 0,limit:J.limit});h({ok:!0,...E,message:`Compiled wiki page ${E.path}`},J.json,J);return}if(B==="file-answer"||B==="answer"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!J.content)throw Error("Missing --content <answer> for wiki file-answer.");let V=await Y.fileAnswer({prompt:H,answer:J.content,approveWrite:J.approveWrite,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V},J.json,J);return}if(B==="lint"){let H=Y.lintWiki();h({ok:H.ok,...H,message:H.ok?"Wiki lint passed":`Wiki lint found ${H.issue_count} issue(s)`},J.json,J);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(U==="safety"){let B=_[1]??"status",H=Y.ensureWorkspace(),V=Y.safetyPolicy();Y.initDb();let K=m(H.knowledgeDbPath);try{if(B==="status"){h({ok:!0,mode:V.mode,workspace:H.home,allow_write_roots:V.allowWriteRoots,read_only_source_access:V.readOnlySourceAccess,network:V.network,redaction:V.redaction,approvals:V.approvals,message:`Safety policy: ${V.mode}`},J.json,J);return}if(B==="check"){let E=_[2]??"generated_write",F=_[3]??null,w;try{if(E==="web_search")fJ(V),w={action:E,target_uri:F,approval_required:!1,approved:!0,decision:"allow"};else if(E==="s3_read"){if(!F)throw Error("safety check s3_read requires an s3:// target.");M0(F,V),w={action:E,target_uri:F,approval_required:!1,approved:!0,decision:"allow"}}else w=g3(K,V,E,F);__(K,{event_type:"safety_check",action:E,target_uri:F,decision:w.decision==="allow"?"allow":"requires_approval",metadata:w}),h({ok:!0,...w,message:`Safety check ${w.decision}`},J.json,J);return}catch(A){throw __(K,{event_type:"safety_check",action:E,target_uri:F,decision:"deny",metadata:{error:A instanceof Error?A.message:String(A)}}),A}}if(B==="approve"){let E=_[2]??"generated_write",F=_[3]??null,w=u9(K,{action:E,target_uri:F,reason:"local-cli approval",metadata:{scope:J.scope??"global"}});__(K,{event_type:"approval",action:E,target_uri:F,decision:"allow",metadata:{approval_id:w.id}}),h({ok:!0,...w,action:E,target_uri:F,message:`Approved ${E}`},J.json,J);return}if(B==="audit"){let E=K.query("SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT 50").all().map((F)=>({id:F.id,event_type:F.event_type,action:F.action,target_uri:F.target_uri,decision:F.decision,metadata:JSON.parse(F.metadata_json),created_at:F.created_at}));h({ok:!0,events:E,message:`${E.length} audit event(s)`},J.json,J);return}if(B==="redact"){let E=_.slice(2).join(" ");if(!E)throw Error("Usage: knowledge safety redact <text>");let F=k_(E,V);if(F.findings.length>0)CJ(K,{source_uri:"safety://redact",findings:F.findings,metadata:{command:"safety redact"}});__(K,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:F.findings.length>0?"redacted":"allow",metadata:{findings:F.findings.length}}),h({ok:!0,text:F.text,findings:F.findings,message:`Redacted ${F.findings.length} finding(s)`},J.json,J);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{K.close()}}if(U==="source"){if((_[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let H=_[2];if(!H)throw Error("Usage: knowledge source resolve <source-ref>");let V=await Y.resolveSource(H,{purpose:J.purpose,limit:J.limit});h({ok:!0,...V,message:V.resolved?`Resolved ${V.source_ref} (${V.content.chunks_returned}/${V.content.chunks_total} chunks)`:`Source not indexed: ${H}`},J.json,J);return}if(U==="ingest"){let B=_[1]??"";if(B==="rules"||B==="global-rules"||B==="agent-rules"){let H=await Y.importRulesProvenance({root:J.workspace??process.cwd(),owner:J.owner,dryRun:J.dryRun===!0,maxItems:J.maxItems,limit:J.limit});h({ok:!0,...H},J.json);return}if(B==="manifest"){let H=_[2];if(!H)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let V=await Y.ingestManifest(H);h({ok:!0,...V,message:`Ingested ${V.items_seen} manifest item(s)`},J.json,J);return}if(B==="source"){let H=_[2];if(!H)throw Error("Usage: knowledge ingest source <source-ref>");let V=await Y.ingestSource(H,J.purpose);h({ok:!0,...V,message:`Ingested source ${V.source_ref} (${V.chunks_inserted} chunks)`},J.json,J);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(U==="reindex"){let B=_[1]??"status";if(B==="status"){let H=Y.reindexHealth({modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`${H.missing_embeddings} chunk(s) missing embeddings`},J.json,J);return}if(B==="enqueue"){let H=Y.enqueueReindex({modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Queued ${H.enqueued} embedding refresh item(s)`},J.json,J);return}if(B==="embeddings"){let H=await Y.refreshEmbeddings({full:J.full,limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Embedded ${H.indexed.chunks_embedded} chunk(s)`},J.json,J);return}if(B==="outbox"){let H=_[2];if(!H)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let V=await Y.consumeOutbox(H);h({ok:!0,...V,message:`Consumed ${V.events_seen} outbox event(s)`},J.json,J);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(U==="embeddings"){let B=_[1]??"status";if(B==="status"){let H=Y.embeddingStatus();h({ok:!0,...H,message:`${H.total_vector_entries} vector index entries`},J.json,J);return}if(B==="index"){let H=await Y.indexEmbeddings({limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Embedded ${H.chunks_embedded} chunk(s)`},J.json,J);return}if(B==="search"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge embeddings search <query>");let V=await Y.semanticSearch({query:H,limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake}),K={ok:!0,...V,message:`${V.results.length} semantic result(s)`};h(J.json||J.verbose?K:vo(K),J.json,J);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(U==="context"){if((_[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let H=J.from??"search";if(!["search","loops","runs"].includes(H))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let V=_.slice(2).join(" ")||J.topic||"",K=await Y.contextPack({source:H,purpose:H==="loops"||H==="runs"?"proposal":"agent_context",query:V,topic:J.topic,since:J.since,dedupe:J.dedupe,maxTokens:J.maxTokens,maxItems:J.maxItems,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q});VA({ok:!0,...K,message:K.message});return}if(U==="proposals"){if((_[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let H=J.from??"loops";if(!["loops","runs"].includes(H))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let V=J.topic??_.slice(2).join(" ");if(!V.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let K=await Y.contextPack({source:H,purpose:"proposal",query:V,topic:V,since:J.since,dedupe:J.dedupe??!0,maxTokens:J.maxTokens,maxItems:J.maxItems,limit:J.limit});VA({ok:!0,...K,message:K.message});return}if(U==="search"){let B=_.slice(1).join(" ");if(!B)throw Error("Usage: knowledge search <query>");if(J.context){let K=await Y.retrieveContext({query:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q}),E={ok:!0,...K,message:`${K.excerpts.length} context excerpt(s)`};h(J.json||J.verbose?E:Zo(E),J.json,J);return}let H=await Y.search({query:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q}),V={ok:!0,...H,message:`${H.results.length} search result(s)`};h(J.json||J.verbose?V:So(V),J.json,J);return}if(U==="web"){if((_[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge web search <query>");let V=await Y.webSearch({query:H,limit:J.limit,modelRef:J.model,provider:J.provider,domains:J.domain,fake:J.fake,fileResults:J.fileResults}),K={ok:!0,...V,message:`${V.sources.length} web source(s)`};h(J.json||J.verbose?K:yo(K),J.json,J);return}if(U==="ask"||U==="build"){let B=_.slice(W).join(" ");if(!B)throw Error("Usage: knowledge ask <prompt>");let H=await Y.runPrompt({prompt:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,generate:J.generate,approveWrite:J.approveWrite,legacyStorePath:q}),V={ok:!0,...H,message:H.generated?"Generated answer with citations":"Prepared citation context draft"};h(J.json||J.verbose?V:lo(V),J.json,J);return}if(U==="providers"){let B=_[1]??"status";if(B==="status"){let H=Y.providerStatus(),V=H.providers.filter((K)=>K.configured).length;h({ok:!0,...H,message:`${V}/${H.providers.length} provider credential(s) configured`},J.json,J);return}if(B==="models"){let H=Y.modelRegistry();h({ok:!0,models:H,message:`${H.length} model alias(es)`},J.json,J);return}if(B==="check"){let H=_[2]??"default",V=y6(H,Y.config()),K=w_(V),E=w1(K.provider,Y.config());h({ok:!0,target:H,model_ref:V,provider:K.provider,model:K.model,credential:E,message:`${K.provider} credentials configured`},J.json,J);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(U==="add"){let B=_[1],H=_[2];if(!B||!H)throw Error("Usage: knowledge add <title> <content>");let V=await L.create({title:B,content:H,url:J.url??null,tags:J.tag??[]});M2("info","Item added",{id:V.id,title:V.title,tags:V.tags?.length??0,transport:L.kind}),h({ok:!0,item:V,message:`Added ${V.id}`},J.json,J);return}if(U==="list"){if(J.format!==void 0&&J.format!=="table"&&J.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");let B=await L.listAll(),H=Number.isFinite(J.page)&&J.page>0?J.page:1,V=Number.isFinite(J.limit)&&J.limit>0?J.limit:20,K=J.search?String(J.search).toLowerCase():"",E=(J.tagRaw??J.tag??[]).map((E$)=>({whole:E$.trim().toLowerCase(),parts:E$.split(",").map((A_)=>A_.trim().toLowerCase()).filter((A_)=>A_.length>0)})),F=J.tag?.length?J.tag.map((E$)=>E$.toLowerCase()).join(","):"none",w=J.format==="table"||!J.json&&!J.format&&Io(J),A=J.json||J.format==="json",g=B.items;if(J.archived)g=g.filter((E$)=>E$.archived===!0);else if(!J.includeArchived)g=g.filter((E$)=>!E$.archived);if(K)g=g.filter((E$)=>E$.title.toLowerCase().includes(K)||E$.content.toLowerCase().includes(K));if(E.length>0)g=g.filter((E$)=>{let A_=new Set((E$.tags??[]).map((D_)=>D_.toLowerCase()));return E.every(({whole:D_,parts:U_})=>D_.length>0&&A_.has(D_)||U_.every((F_)=>A_.has(F_)))});let{sorted:v,sort:k,direction:u}=po(g,J),W_=(H-1)*V,c$=v.slice(W_,W_+V),z_=Math.max(1,Math.ceil(v.length/V)),K_={ok:!0,page:H,limit:V,total:v.length,total_pages:z_,sort:k,direction:u,items:c$,store_exists:B.exists};if(A){h(K_,!0);return}if(J.verbose){h(K_,!1,J);return}if(c$.length===0){h(`No items found (search=${K||"none"}, tag=${F})`,!1);return}if(w){let E$=(D_)=>D_,A_=`${E$("ID")} ${E$("TITLE")} ${E$("CREATED")} ${E$("URL")} ${E$("TAGS")}`;console.log(A_);for(let D_ of c$)console.log(`${D_.id} ${E$(v$(D_.title,80))} ${D_.created_at} ${D_.url?E$(v$(D_.url,90)):""} ${D_.tags?.length?E$(v$(`[${D_.tags.join(", ")}]`,80)):""}`);console.log(`Page ${H}/${z_} | showing ${c$.length} of ${v.length} | sort=${k} ${u} | search=${K||"none"} | tag=${F}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let E$ of c$)console.log(`${E$.id} ${v$(E$.title,80)} ${E$.created_at}${E$.url?` ${v$(E$.url,90)}`:""}${E$.tags?.length?` ${v$(`[${E$.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${H}/${z_} | showing ${c$.length} of ${v.length} | sort=${k} ${u} | search=${K||"none"} | tag=${F}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(U==="get"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);h({ok:!0,item:B,store_exists:L.exists,message:`${B.id}: ${B.title}`},J.json,J);return}if(U==="versions"){E2(J);let B=Number.isFinite(J.page)&&J.page>0?J.page:1,H=Number.isFinite(J.limit)&&J.limit>0?J.limit:void 0,V=await L.listVersions(J.id,{limit:H,offset:(B-1)*(H??50)});if(!V)throw Error(`Item not found: ${J.id}`);let K={ok:!0,id:V.item_id,current_version:V.current_version,total:V.total,page:B,store:L.location,versions:V.items,message:V.total===0?`${V.item_id} is at version ${V.current_version} with no retained prior versions`:`${V.item_id} is at version ${V.current_version}; ${V.total} prior version(s) retained`};if(J.json||J.verbose){h(K,J.json,J);return}console.log(K.message);for(let E of V.items){let F=E.actor?` by ${E.actor}`:"",w=E.reason?` (${E.reason})`:"";console.log(`v${E.version} ${E.valid_to}${F}${w} ${E.content_bytes} bytes ${E.content_hash.slice(0,12)}`)}if(V.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(U==="diff"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);if(J.rev!==void 0&&(J.from!==void 0||J.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let H=()=>({title:B.title,content:B.content,url:B.url,tags:B.tags??[],metadata:B.metadata??{},archived:B.archived??!1}),V=`v${B.version??"?"} (current)`,K=async(v)=>{if(v==="current")return{label:V,snapshot:H()};let k=Number(v);if(!Number.isInteger(k)||k<1)throw Error(`Not a version number: ${v}`);if(B.version!==void 0&&k===B.version)return{label:V,snapshot:H()};let u=await L.getVersion(B.id,k);if(!u)throw Error(`No version ${k} retained for ${B.id} (it is at version ${B.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${u.version}`,snapshot:{title:u.title,content:u.content,url:u.url,tags:u.tags,metadata:u.metadata,archived:u.archived}}},E,F;if(J.rev!==void 0){if(!Number.isInteger(J.rev)||J.rev<1)throw Error("--rev must be a positive version number.");if(J.rev===1)throw Error("Version 1 has no predecessor to diff against.");E=String(J.rev-1),F=String(J.rev)}else if(J.from!==void 0||J.to!==void 0){if(J.from===void 0||J.to===void 0)throw Error("--from and --to must be given together.");E=J.from,F=J.to}else{let v=await L.listVersions(B.id,{limit:1});if(!v)throw Error(`Item not found: ${J.id}`);if(v.items.length===0)throw Error(`${B.id} is at version ${v.current_version} with no retained prior versions to diff against.`);E=String(v.items[0].version),F="current"}let w=await K(E),A=await K(F),g=sN(w.snapshot,A.snapshot);if(J.json||J.verbose){h({ok:!0,id:B.id,from:w.label,to:A.label,...g},J.json,J);return}console.log(eN(g,`${B.id} ${w.label}`,`${B.id} ${A.label}`));return}if(U==="update"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H={};if(J.title!==void 0)H.title=J.title;if(J.content!==void 0)H.content=J.content;if(J.url!==void 0)H.url=J.url;let V;if(J.tag!==void 0){if(V=NA(B.tags,J.tag),V.length>0)H.tags=[...B.tags??[],...V]}let K=await L.update(B.id,H,{expectedVersion:B.version});h(AB({ok:!0,item:K},`Updated ${K?.id??B.id}`,V),J.json,J);return}if(U==="archive"||U==="restore"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H=await L.update(B.id,{archived:U==="archive"},{expectedVersion:B.version});h({ok:!0,item:H,message:`${U==="archive"?"Archived":"Restored"} ${H?.id??B.id}`},J.json,J);return}if(U==="untag"){if(E2(J),!J.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H=B.tags??[],V=new Set(H.map((k)=>k.toLowerCase())),K=new Set;for(let k of J.tagRaw??J.tag){let u=k.trim().toLowerCase();if(u.length>0&&V.has(u)){K.add(u);continue}for(let W_ of k.split(",").map((c$)=>c$.trim().toLowerCase()).filter((c$)=>c$.length>0))K.add(W_)}let E=H.filter((k)=>!K.has(k.toLowerCase())),F=H.length-E.length,w=[...K].filter((k)=>!V.has(k));if(F===0)throw Error(`No matching tag on ${B.id}: ${w.map((k)=>JSON.stringify(k)).join(", ")} not in [${H.map((k)=>JSON.stringify(k)).join(", ")}]`);let A=await L.update(B.id,{tags:E},{expectedVersion:B.version}),g=w.length>0?` (not found: ${w.map((k)=>JSON.stringify(k)).join(", ")})`:"",v={ok:!0,item:A,removed:F,message:`Removed ${F} tag${F===1?"":"s"} from ${A?.id??B.id}${g}`};if(w.length>0)v.not_found=w;h(v,J.json,J);return}if(U==="upsert"){let B=J.title??_[1],H=J.content??_[2],V=J.id?await L.get(J.id):null;if(!V){if(!B||!H)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let w=await L.create({id:J.id,title:B,content:H,url:J.url??null,tags:J.tag??[]});h(AB({ok:!0,created:!0,item:w},`Upserted ${w.id}`,J.tag),J.json,J);return}let K={};if(B!==void 0)K.title=B;if(H!==void 0)K.content=H;if(J.url!==void 0)K.url=J.url;let E;if(J.tag!==void 0){if(E=NA(V.tags,J.tag),E.length>0)K.tags=[...V.tags??[],...E]}let F=await L.update(V.id,K,{expectedVersion:V.version});h(AB({ok:!0,created:!1,item:F},`Upserted ${F?.id??V.id}`,E),J.json,J);return}if(U==="delete"){if(E2(J),!J.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await L.delete(J.id))throw Error(`Item not found: ${J.id}`);M2("info","Item deleted",{id:J.id,transport:L.kind}),h({ok:!0,deleted_id:J.id,message:`Deleted ${J.id}`},J.json,J);return}if(U==="export"){let B=J.format??"json";if(B!=="json"&&B!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let H=await L.listAll();if(B==="jsonl")for(let V of H.items)console.log(JSON.stringify(V));else if(J.json||J.format==="json"||J.verbose)h({ok:!0,items:H.items,store_exists:H.exists},J.json||J.format==="json",J);else h(ro(H.items,B),!1);return}if(U==="prune"){if(!J.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:B}=await L.listAll(),H=J.olderThan!==void 0?new Date(Date.now()-J.olderThan*86400000):null,V=B.filter((F)=>H!==null&&new Date(F.created_at)<H||J.empty&&F.content.trim().length===0),K=await L.deleteMany(V.map((F)=>F.id)),E=B.length-K;M2("info","Prune completed",{pruned:K,remaining:E,transport:L.kind}),h({ok:!0,pruned:K,remaining:E,message:`Pruned ${K} item(s)`},J.json,J);return}if(U==="dedupe"){if(!J.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:B}=await L.listAll(),H=new Set,V=[];for(let F of B){let w=`${F.title}\x00${F.content}`;if(H.has(w))V.push(F);else H.add(w)}let K=await L.deleteMany(V.map((F)=>F.id)),E=B.length-K;M2("info","Dedupe completed",{removed:K,remaining:E,transport:L.kind}),h({ok:!0,removed:K,remaining:E,message:`Dedupe removed ${K} duplicate(s)`},J.json,J);return}if(U==="stats"){let B=await L.listAll(),H=B.items.filter((k)=>!k.archived),V=H.length,K=B.items.length-V,E=H.filter((k)=>k.url).length,F=H.filter((k)=>k.tags&&k.tags.length>0).length,w=V>0?H.map((k)=>k.created_at).sort()[0]:null,A=V>0?H.map((k)=>k.created_at).sort()[V-1]:null,g={};for(let k of H)for(let u of k.tags||[])g[u]=(g[u]||0)+1;let v=Object.entries(g).sort((k,u)=>u[1]-k[1]).slice(0,5).map(([k,u])=>({tag:k,count:u}));h({ok:!0,total:V,archived:K,with_url:E,with_tags:F,oldest:w,newest:A,top_tags:v,store_exists:B.exists,message:`${V} items | ${E} with URL | ${F} with tags`},J.json,J);return}let N=Ao(_[0]),R=N?` Did you mean '${N}'?`:"";throw M2("warn","Unknown command",{input:_[0],suggestion:N}),Error(`Unknown command: ${_[0]}.${R} Run 'knowledge --help' for available commands.`)}function to($,_){let J=$ instanceof Error?$.message:String($);if(M2("debug","CLI error",{message:J,stack:$ instanceof Error?$.stack:void 0}),console.error(`Error: ${J}`),_.includes("--json"))h({ok:!1,error:J,message:J},!0);process.exitCode=1}if(import.meta.main){let $=process.argv.slice(2);oo($).catch((_)=>to(_,$))}export{Ao as suggestCommand,po as sortItems,oo as run,Fo as parseArgs,to as emitCliError}; + Selection is EXPLICIT-ONLY: set ${o$[0]}=sqlite|postgres. Setting only + ${uU[0]} / ${xU[0]} does NOT switch backends; + those are reported as present-but-ignored pointers. Env var NAMES are printed, never values.`);return}if(_==="setup"){console.log("Usage: knowledge setup --mode local|hosted [--api-url https://...] [--canonical-example] [--scope local|global|project] [--json]");return}if(_==="auth"){console.log("Usage: knowledge auth login|whoami|logout [--api-key <key>] [--email <email>] [--org <slug>] [--api-url https://...] [--scope local|global|project] [--json]");return}if(_==="storage"){console.log(`Usage: knowledge storage status|validate|repair-artifact-keys|migrate-legacy-path|merge-legacy-path [--approve-write --approved-by <name>] [--scope local|global|project] [--json] + knowledge storage import-legacy [--dry-run] [--scope global] [--json]`);return}if(_==="machines"){console.log("Usage: knowledge machines topology [--no-tailscale] | preflight [machine] [--workspace <repo>] [--scope local|global|project] [--verbose] [--json]");return}if(_==="sync"){console.log(`Usage: knowledge sync status|doctor|readiness|snapshot|machines|conflicts [show|propose|resolve] [id] | dry-run|pull|push|sync|export|import [--peer-workspace <path>] [--machine <ssh-alias>] [--tables <names>] [--dry-run] [--limit <n>] [--approve-write] [--approved-by <name>] [--strategy <name>] [--mode deterministic|ai] [--model <alias|provider:model>] [--fake] [--no-tailscale] [--scope local|global|project] [--verbose] [--json] + +Remote machine sync resolves peer paths through @hasna/machines when --peer-workspace is omitted.`);return}if(_==="db"){console.log("Usage: knowledge db init|stats|storage status [--scope local|global|project] [--json]");return}if(_==="wiki"){console.log("Usage: knowledge wiki init|compile|file-answer|lint [query|prompt] [--title <title>] [--content <answer>] [--approve-write] [--limit <n>] [--scope local|global|project] [--json]");return}if(_==="app-wiki"){console.log("Usage: knowledge app-wiki init | note add|get|list | source add <source-ref> | search <query> | query <query> [--title <title>] [--content <text>] [--tag <tag>] [--source-ref <uri>] [--scope project|local|global] [--allow-global] [--json]");return}if(_==="source"){console.log("Usage: knowledge source resolve <source-ref> [--purpose knowledge_answer|knowledge_index] [--limit <n>] [--scope local|global|project] [--json]");return}if(_==="ingest"){console.log("Usage: knowledge ingest manifest <file|s3://bucket/key> | source <source-ref> | rules [--workspace <path>] [--owner <name>] [--dry-run] [--max-items <n>] [--limit <n>] [--purpose knowledge_index] [--scope local|global|project] [--json]");return}if(_==="reindex"){console.log("Usage: knowledge reindex status|enqueue|embeddings|outbox [file|s3://bucket/key] [--full] [--fake] [--scope local|global|project] [--json]");return}if(_==="search"){console.log("Usage: knowledge search <query> [--context] [--semantic] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="context"){console.log("Usage: knowledge context pack <query> [--from search|runs|loops] [--max-tokens <n>] [--max-items <n>] [--limit <n>] [--semantic] [--model openai:text-embedding-3-small] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="proposals"){console.log("Usage: knowledge proposals context --from loops --topic <text> [--since <duration|ISO>] [--dedupe] [--max-tokens <n>] [--max-items <n>] [--scope local|global|project] [--json]");return}if(_==="web"){console.log("Usage: knowledge web search <query> [--provider openai|anthropic] [--model provider:model] [--domain <domain>] [--file-results] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="ask"||_==="build"){console.log("Usage: knowledge ask|build <prompt> [--generate] [--semantic] [--model default|provider:model] [--approve-write] [--scope local|global|project] [--verbose] [--json]");return}if(_==="embeddings"){console.log("Usage: knowledge embeddings status|index|search [query] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="providers"){console.log("Usage: knowledge providers status|models|check [provider|model-alias] [--scope local|global|project] [--json]");return}if(_==="safety"){console.log("Usage: knowledge safety status|check|approve|audit|redact [args] [--scope local|global|project] [--json]");return}if(_==="events"){console.log("Usage: knowledge events emit|list|replay [args] [--json]");return}if(_==="webhooks"){console.log("Usage: knowledge webhooks add|list|remove|test [args] [--json]");return}Af()}function Jf(_){if(_.noColor||process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR)return!0;return process.stdout.isTTY===!0}function r(_,$,g){if($){console.log(JSON.stringify(_,null,2));return}if(typeof _==="string"){console.log(_);return}if(g?.verbose){console.log(JSON.stringify(_,null,2));return}let U=_.message;console.log(U?`${U} +${i_()}`:Pf(_))}function i_(_="full details"){return`Hint: use --verbose for ${_}, or --json for machine-readable output.`}function g_(_,$=120){let g=_===null||_===void 0?"":String(_).replace(/\s+/g," ").trim();if(g.length<=$)return g;return`${g.slice(0,Math.max(0,$-3))}...`}function Pf(_){if(!_||typeof _!=="object")return String(_);let $=_,g=[$.ok===!1?"Result: not ok":"Result: ok"];for(let[U,D]of Object.entries($).slice(0,8)){if(U==="ok"||U==="message")continue;if(Array.isArray(D))g.push(`${U}: ${D.length} item(s)`);else if(D&&typeof D==="object")g.push(`${U}: ${Object.keys(D).length} field(s)`);else g.push(`${U}: ${g_(D,100)}`)}return g.push(i_()),g.join(` +`)}function zf(_){let $=_.mode==="postgres"?"postgres (HTTP /v1 API)":"sqlite (on-box store)",g=_.source.kind==="env"?`selected by ${_.source.name}=${_.source.value}`:`default (no mode var set; set ${o$[0]}=postgres to use the API)`,U=[`Knowledge mode: ${$}`,` ${g}`];if(_.pointer_env_present.length>0){let D=_.pointer_ignored?"present but IGNORED for mode selection":"present";U.push(` Pointer env ${D}: ${_.pointer_env_present.join(", ")}`)}if(_.network_guard_active)U.push(" Outbound guard: ACTIVE (NODE_ENV=test) \u2014 non-loopback requests are refused.");if(_.warning)U.push(` Note: ${_.warning}`);return U.join(` +`)}function Sf(_){return[`Knowledge paths (${_.scope})`,`Home: ${_.home}`,`SQLite: ${_.knowledge_db_path}`,`JSON store: ${_.json_store_path}`,`Wiki: ${_.wiki_dir}`,i_("config and all paths")].join(` +`)}function h8(_){console.log(JSON.stringify(_))}function Wf(_){let $=_.summary,g=[`Knowledge inventory (${_.scope})`,`Home: ${_.home}`,`JSON store: ${_.paths.json_store_path}${_.paths.json_store_exists?"":" (missing)"}`,`SQLite catalog: ${_.paths.knowledge_db_path}`,`Summary: ${$.legacy_items} item(s), ${$.sources} source(s), ${$.chunks} chunk(s), ${$.wiki_pages} wiki page(s), ${$.indexes} index(es), ${$.storage_objects} artifact(s), ${$.runs} run(s)`],U=(D,I,j)=>{if(I.length===0)return;g.push("",`${D}:`);for(let N of I.slice(0,_.limit))g.push(`- ${j(N)}`)};return U("Items",_.items,(D)=>`${D.id}: ${D.title}`),U("Sources",_.sources,(D)=>`${D.kind??"source"} ${D.uri} (${D.chunks??0} chunk(s))`),U("Chunks",_.chunks,(D)=>`${D.kind??"chunk"} ${D.id}: ${D.text_preview??""}`),U("Wiki pages",_.wiki_pages,(D)=>`${D.path}: ${D.title}`),U("Indexes",_.indexes,(D)=>`${D.kind??"index"} ${D.name}${D.shard_key?` (${D.shard_key})`:""}`),U("Artifacts",_.storage_objects,(D)=>`${D.kind??"artifact"} ${D.artifact_uri}`),U("Runs",_.runs,(D)=>`${D.type??"run"} ${D.id}: ${D.status??"unknown"}`),U("Machines",_.machines,(D)=>`${D.machine_id}${D.workspace_home?` ${D.workspace_home}`:""}`),U("Sync conflicts",_.sync_conflicts,(D)=>`${D.id}: ${D.entity_kind}/${D.entity_id} ${D.status}`),g.join(` +`)}function Xf(_){let $=Array.isArray(_.results)?_.results:[],g=[`${$.length} search result(s) for "${g_(_.query,80)}"${_.mode?.semantic?" (semantic enabled)":""}`];for(let U of $.slice(0,_.limit??10)){let D=U.source?.uri??U.provenance?.source_uri??U.artifact?.path??U.artifact?.uri??U.id,I=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(g.push(`- ${U.kind??"result"} ${g_(U.title??U.id,80)}${I}`),D)g.push(` source: ${g_(D,120)}`);if(U.text)g.push(` text: ${g_(U.text,180)}`)}if($.length===0)g.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(g.push(i_("scores, provenance, and full result objects")),!_.context)g.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return g.join(` +`)}function Rf(_){let $=Array.isArray(_.excerpts)?_.excerpts:[],g=Array.isArray(_.citations)?_.citations:[],U=[`${$.length} context excerpt(s) for "${g_(_.query??_.normalized_query,80)}"`];for(let D of $.slice(0,10)){let I=g.find((O)=>O.id===D.citation_id||O.result_id===D.result_id),j=I?.source_uri??I?.artifact_path??D.result_id,N=typeof D.score==="number"?` score=${D.score.toFixed(3)}`:"";if(U.push(`- ${D.kind??"excerpt"} ${g_(D.id,44)}${N}`),j)U.push(` source: ${g_(j,120)}`);U.push(` text: ${g_(D.text,220)}`)}return U.push(`Citations: ${g.length}`),U.push(i_("citations, graph, notes, and full excerpts")),U.join(` +`)}function Gf(_){let $=Array.isArray(_.results)?_.results:[],g=[`${$.length} semantic result(s) for "${g_(_.query,80)}"`,`Index: ${_.provider??"unknown"}:${_.model??"unknown"} (${_.dimensions??"?"} dimensions)`];for(let U of $.slice(0,_.limit??10)){let D=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(g.push(`- ${g_(U.chunk_id,44)}${D}`),U.source_uri)g.push(` source: ${g_(U.source_uri,120)}`);if(U.text)g.push(` text: ${g_(U.text,180)}`)}return g.push(i_("provenance and full vector result objects")),g.join(` +`)}function Yf(_){let $=Array.isArray(_.sources)?_.sources:[],g=[`${$.length} web source(s) for "${g_(_.query,80)}"`,`Provider: ${_.provider??"unknown"}${_.model?` (${_.model})`:""}`];for(let U of $.slice(0,_.limit??10)){g.push(`- ${g_(U.title??U.url??U.uri??"source",100)}`);let D=U.url??U.uri??U.source_ref;if(D)g.push(` url: ${g_(D,140)}`);if(U.snippet)g.push(` snippet: ${g_(U.snippet,180)}`)}return g.push(i_("provider payloads and filed source refs")),g.join(` +`)}function Qf(_){let $=Array.isArray(_.machines)?_.machines:[],g=[`${$.length} machine(s) discovered via ${_.source??"unknown"}`,`Adapter: ${_.adapter?.package??"@hasna/machines"} ${_.adapter?.available?"available":"unavailable"}`];for(let U of $.slice(0,10)){let D=U.local?" local":"",I=U.tailscale_dns??U.ssh_target??U.hostname??"";g.push(`- ${g_(U.machine_id??U.id??"unknown",48)}${D}${I?` -> ${g_(I,80)}`:""}`)}if($.length>10)g.push(`... ${$.length-10} more machine(s).`);if(Array.isArray(_.warnings)&&_.warnings.length>0)g.push(`Warnings: ${_.warnings.slice(0,3).join("; ")}`);return g.push(i_("full topology, route hints, and adapter evidence")),g.join(` +`)}function Tf(_){let $=Array.isArray(_.checks)?_.checks:[],g=$.filter((I)=>I.status==="fail"||I.severity==="fail"),U=$.filter((I)=>I.status==="warn"||I.severity==="warn"),D=[`Machine preflight ${_.ok?"passed":"needs attention"} for ${_.machine_id??_.requested_machine_id??"local"}`,`Checks: ${$.length} total, ${g.length} failed, ${U.length} warning(s)`];for(let I of[...g,...U].slice(0,8))D.push(`- ${I.status??I.severity??"check"} ${g_(I.id??I.kind??"check",72)}: ${g_(I.message??I.detail??"",140)}`);return D.push(i_("all checks and repair hints")),D.join(` +`)}function qf(_){return[`Sync status (${_.scope??"scope"})`,`Schema: v${_.sqlite_schema_version??"unknown"}`,`Machines: ${_.machines?.total??0}; snapshots: ${_.snapshots?.total??0}; open conflicts: ${_.conflicts?.open??0}`,`Tables: ${Object.entries(_.table_counts??{}).slice(0,8).map(([g,U])=>`${g}=${U}`).join(", ")||"none"}`,i_("registry rows, clocks, snapshots, imports, and conflicts")].join(` +`)}function Bf(_){let $=Array.isArray(_.warnings)?_.warnings:[],g=Array.isArray(_.recommended_commands)?_.recommended_commands:[],U=[_.message??`Sync readiness ${_.ok?"ok":"needs attention"}`,`Storage: ${_.storage?.validation?.ok?"ok":"needs attention"}; open-files: ${_.open_files?.ok?"ok":"needs attention"}; open conflicts: ${_.sync?.open_conflicts??0}`];if($.length>0)U.push(`Warnings: ${$.slice(0,5).join("; ")}`);for(let D of g.slice(0,5))U.push(`- next: ${g_(D.shell_command??D.command?.join(" ")??D.id,160)}`);return U.push(i_("diagnostics, route evidence, and all recommended commands")),U.join(` +`)}function Kf(_){let $=_.snapshot??{};return[`Sync snapshot ${_.ok?"recorded":"failed"}`,`Snapshot: ${g_($.id??$.snapshot_id??"unknown",80)} ${$.content_hash?`(${g_($.content_hash,80)})`:""}`,`Machines upserted: ${_.machines_upserted??0}; machine: ${_.machine_id??$.machine_id??"unknown"}`,i_("snapshot payload and topology evidence")].join(` +`)}function Vf(_){let $=Array.isArray(_.conflicts)?_.conflicts:[],g=[`${$.length} sync conflict(s)`];for(let U of $.slice(0,10))g.push(`- ${g_(U.id,48)} ${U.status??"unknown"} ${U.entity_kind??""}/${g_(U.entity_id,80)}`);return g.push("Next: use `knowledge sync conflicts show <id> --json` for one conflict."),g.push(i_("full conflict objects")),g.join(` +`)}function Ff(_){let $=Array.isArray(_.machines)?_.machines:[],g=[`${$.length} registered sync machine(s)`];for(let U of $.slice(0,10))g.push(`- ${g_(U.machine_id,48)} ${g_(U.hostname??U.workspace_home??"",100)}`);return g.push(i_("machine registry rows")),g.join(` +`)}function c8(_,$){let g=[`Sync ${$} ${_.ok===!1?"needs attention":"completed"}${_.dry_run?" (dry run)":""}`],U=(D,I)=>{if(!I)return;let N=(Array.isArray(I.tables)?I.tables:[]).reduce((L,z)=>L+(z.inserted??0)+(z.updated??0)+(z.deleted??0),0),O=I.artifacts?.copied??0,A=Array.isArray(I.errors)?I.errors.length:0;g.push(`${D}: ${N} table row change(s), ${O} artifact(s), ${A} error(s)`)};if(U("pull",_.pull),U("push",_.push),Array.isArray(_.errors)&&_.errors.length>0)g.push(`Errors: ${_.errors.slice(0,3).map((D)=>g_(D,120)).join("; ")}`);return g.push(i_("per-table rows, artifacts, clocks, and errors")),g.join(` +`)}function Mf(_){let $=Array.isArray(_.citations)?_.citations:[],g=Array.isArray(_.context?.excerpts)?_.context.excerpts:Array.isArray(_.excerpts)?_.excerpts:[],U=[_.generated?"Generated answer with citations":"Prepared citation context draft",`Citations: ${$.length}; excerpts: ${g.length}`];if(_.answer)U.push(`Answer: ${g_(_.answer,500)}`);for(let D of $.slice(0,5))U.push(`- ${g_(D.source_uri??D.ref??D.id,120)}`);return U.push(i_("full answer payload, context, citations, and run ledger")),U.join(` +`)}function Zf(_,$){return[`Export preview: ${_.length} item(s) available`,"Default output is compact to avoid terminal/context bloat.","Use --verbose or --json for a JSON object, or --format jsonl for newline-delimited records.",$!=="json"?`Requested format: ${$}`:""].filter(Boolean).join(` +`)}function n8(_){return!_||_==="local"||_==="localhost"}function _0(_){if(!_.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function bf(_,$){let g=$.sort??"created";if(g!=="created"&&g!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let U=[..._].sort((D,I)=>{if(g==="title")return D.title.localeCompare(I.title);return D.created_at.localeCompare(I.created_at)});if($.desc)U.reverse();return{sorted:U,sort:g,direction:$.desc?"desc":"asc"}}async function Hf(_){if(await Of(_))return;let{positional:$,flags:g}=Uf(_);if($0("debug","CLI invoked",{command:$[0],flags:{json:g.json,store:g.store}}),g.version){console.log(g.json?JSON.stringify({name:C$.name,version:C$.version},null,2):`${C$.name} ${C$.version}`);return}if(g.completions){let J=g.completions;if(J==="bash")console.log('_knowledge() { local cur; cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive --json --verbose --yes --help --version --desc --page --limit --search --sort --id --store --title --content --url --tag --rev --to --format --completions --purpose --model --dimensions --semantic --context --max-tokens --max-items --from --since --topic --dedupe --generate --approve-write --provider --mode --machine --workspace --peer-workspace --api-url --canonical-example --api-key --email --org --org-id --user-id --owner --domain --file-results --full --dry-run --fake --no-tailscale --no-artifact-content --no-color --scope --tables --archived --include-archived --project --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(J==="zsh")console.log(`#compdef knowledge +_knowledge() { _arguments -C "1: :(add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive)" "(--json)--json" "(--verbose)--verbose" "(--yes)-y" "(--help)--help" "(--version)--version" "(--desc)--desc" "(--archived)--archived" "(--include-archived)--include-archived" "(--semantic)--semantic" "(--context)--context" "(--dedupe)--dedupe" "(--generate)--generate" "(--approve-write)--approve-write" "(--canonical-example)--canonical-example" "(--file-results)--file-results" "(--full)--full" "(--dry-run)--dry-run" "(--fake)--fake" "(--no-tailscale)--no-tailscale" "(--no-artifact-content)--no-artifact-content" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(-s --search)"{-s,--search}"[search text]:text:" "(--sort)--sort"{created,title}:" "(--id)--id[item id]:id:" "(--store)--store[store path]:path:" "(--title)--title[new title]:" "(--content)--content[new content]:" "(--url)--url[source url]:" "(-t --tag)"{-t,--tag}"[tag]:tag:" "(--format)--format[json|jsonl]:" "(--completions)--completions[output completions]:shell:(bash zsh fish):" "(--purpose)--purpose[purpose]:" "(--model)--model[model ref]:" "(--dimensions)--dimensions[embedding dimensions]:number:" "(--max-tokens)--max-tokens[token budget]:number:" "(--max-items)--max-items[item budget]:number:" "(--from)--from"{search,loops,runs}:" "(--to)--to[diff target: version number or current]:" "(--rev)--rev[entry version for diff]:number:" "(--since)--since[duration or ISO time]:" "(--topic)--topic[topic text]:" "(--provider)--provider[provider]:" "(--mode)--mode"{local,hosted}:" "(--machine)--machine[machine id or SSH alias]:" "(--workspace)--workspace[repo workspace path]:path:" "(--peer-workspace)--peer-workspace[peer repo or knowledge home path]:path:" "(--api-url)--api-url[hosted API URL]:" "(--api-key)--api-key[hosted API key]:" "(--email)--email[email]:" "(--org)--org[org slug]:" "(--org-id)--org-id[org id]:" "(--user-id)--user-id[user id]:" "(--owner)--owner[provenance owner]:" "(--domain)--domain[domain]:" "(--project)--project[project id/name/slug]:" "(--source-ref)--source-ref[source ref]:" "(--no-color)--no-color[disable color]" "(--scope)--scope"{local,global,project}:" "(--tables)--tables[comma-separated DB sync tables]:" }; _knowledge`);else if(J==="fish")console.log('complete -c knowledge -f; complete -c knowledge -a "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive"; complete -c knowledge -l json; complete -c knowledge -l verbose; complete -c knowledge -l yes -s y; complete -c knowledge -l help -s h; complete -c knowledge -l version -s v; complete -c knowledge -l desc; complete -c knowledge -l archived; complete -c knowledge -l include-archived; complete -c knowledge -l semantic; complete -c knowledge -l context; complete -c knowledge -l max-tokens; complete -c knowledge -l max-items; complete -c knowledge -l from -a "search loops runs"; complete -c knowledge -l to; complete -c knowledge -l rev; complete -c knowledge -l since; complete -c knowledge -l topic; complete -c knowledge -l dedupe; complete -c knowledge -l generate; complete -c knowledge -l approve-write; complete -c knowledge -l allow-global; complete -c knowledge -l canonical-example; complete -c knowledge -l provider; complete -c knowledge -l mode; complete -c knowledge -l machine; complete -c knowledge -l workspace; complete -c knowledge -l peer-workspace; complete -c knowledge -l api-url; complete -c knowledge -l api-key; complete -c knowledge -l email; complete -c knowledge -l org; complete -c knowledge -l org-id; complete -c knowledge -l user-id; complete -c knowledge -l owner; complete -c knowledge -l domain; complete -c knowledge -l project; complete -c knowledge -l contract; complete -c knowledge -l source-ref; complete -c knowledge -l file-results; complete -c knowledge -l full; complete -c knowledge -l dry-run; complete -c knowledge -l fake; complete -c knowledge -l no-tailscale; complete -c knowledge -l no-artifact-content; complete -c knowledge -s p -l page; complete -c knowledge -s l -l limit; complete -c knowledge -s s -l search; complete -c knowledge -l sort; complete -c knowledge -l id; complete -c knowledge -l store; complete -c knowledge -l title; complete -c knowledge -l content; complete -c knowledge -l url; complete -c knowledge -s t -l tag; complete -c knowledge -l format; complete -c knowledge -l completions; complete -c knowledge -l purpose; complete -c knowledge -l model; complete -c knowledge -l dimensions; complete -c knowledge -l no-color; complete -c knowledge -l scope -a "local global project"; complete -c knowledge -l tables');else throw Error("Invalid --completions value. Use 'bash', 'zsh', or 'fish'.");return}let U=If($[0]),D=1,I=$.length>1||/\s/.test(U);if(Ef()&&U&&!m8.includes(U)&&I)U="ask",D=0;if(!U||g.help||U==="help"){let J=U==="help"?$[1]:U||$[1];Lf(J);return}if(U==="mode"){let J=DS(process.env);r(g.json||g.verbose?{ok:!0,...J}:zf(J),g.json,g);return}gS(process.env,{storePathOverridden:Boolean(g.store)});let j=U==="project-panel"||U==="app-wiki"?g.scope??"project":g.scope,N=UN({scope:j});if(U==="storage"){let J=$[1]??"status";if(J==="import-legacy"){if(g.scope&&g.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let P=wN({dryRun:g.dryRun});if(r(P,g.json),!P.ok)process.exitCode=1;return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:g.approveWrite,approvedBy:g.approvedBy});if(r(P,g.json),!P.ok&&!g.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:g.approveWrite,approvedBy:g.approvedBy});if(r(P,g.json),!P.ok&&!g.json)process.exitCode=1;return}}let O=Boolean(g.store),A=g.store;if(!A)if(j==="project"||j==="local")A=N.workspace.jsonStorePath;else A=HU();if(!O&&(U==="ask"||U==="build")&&!Y6())Hg(A);let L=hU({storePath:A,storePathOverridden:O});if(U==="inventory"){let J=await N.resolveInventory({limit:g.limit,includeArchived:g.includeArchived||g.archived,storePath:Y6()?void 0:A});r(g.json||g.verbose?J:Wf(J),g.json,g);return}if(U==="project-panel"){let J=g.project??$[1];if(!J)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let P=await i9(J,{service:N,limit:g.limit,storePath:Y6()?void 0:A,includeArchived:g.includeArchived||g.archived});r(g.json||g.contract?P:l9(P),g.json||g.contract);return}if(U==="paths"){let J=N.paths();r(g.json||g.verbose?J:Sf(J),g.json,g);return}if(U==="setup"){let J=N.setup({mode:g.mode,apiUrl:g.apiUrl,canonicalExample:g.canonicalExample});r(J,g.json,g);return}if(U==="auth"){let J=$[1]??"whoami";if(J==="whoami"||J==="status"){let P=N.authStatus(process.env);r({ok:!0,...P,message:P.authenticated?`Authenticated via ${P.source}`:"Not authenticated"},g.json,g);return}if(J==="login"){let P=g.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!P)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let S=N.saveAuth({apiKey:P,email:g.email,orgSlug:g.org,orgId:g.orgId,userId:g.userId,apiUrl:g.apiUrl},process.env);r({ok:!0,authenticated:!0,email:S.email??null,org_slug:S.org_slug??null,api_url:S.api_url??N.authStatus(process.env).api_url,auth_path:N.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${S.email??"API key"}`},g.json,g);return}if(J==="logout"){let P=N.clearAuth(process.env);r({ok:!0,removed:P,message:P?"Removed hosted credentials":"No hosted credentials found"},g.json,g);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(U==="storage"){let J=$[1]??"status";if(J==="status"){let P=N.storageContract(),S=N.validateStorage();r({ok:S.ok,...P,validation:S,message:`${P.storage_type} artifact storage at ${P.artifact_store.uri_prefix}`},g.json,g);return}if(J==="validate"){let P=N.validateStorage();if(r({ok:P.ok,validation:P,message:P.ok?"Storage contract valid":`Storage contract invalid: ${P.errors.join("; ")}`},g.json,g),!P.ok)process.exitCode=1;return}if(J==="repair-artifact-keys"||J==="repair-keys"){let P=N.repairArtifactManifestKeys({approveWrite:g.approveWrite,approvedBy:g.approvedBy,dryRun:g.dryRun});r(P,g.json,g);return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:g.approveWrite,approvedBy:g.approvedBy});if(r(P,g.json),!P.ok&&!g.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:g.approveWrite,approvedBy:g.approvedBy});if(r(P,g.json),!P.ok&&!g.json)process.exitCode=1;return}throw Error("Invalid storage action. Use 'status', 'validate', 'repair-artifact-keys', 'migrate-legacy-path', 'merge-legacy-path', or 'import-legacy'.")}if(U==="machines"){let J=$[1]??"topology";if(J==="topology"||J==="status"){let P=await N.machineTopology({includeTailscale:g.tailscale!==!1});r(g.json||g.verbose?P:Qf(P),g.json,g);return}if(J==="preflight"||J==="check"){let P=$[2]??g.machine??"local",S=g.workspace??process.cwd(),X=await N.machinePreflight({machineId:P,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:C$.name,command:"knowledge",expectedVersion:C$.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:S,expectedPackageName:C$.name,expectedVersion:C$.version,required:!0}]});if(r(g.json||g.verbose?X:Tf(X),g.json,g),!X.ok&&!g.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(U==="sync"){let J=$[1]??"status",P=g.tables?g.tables.split(",").map((S)=>S.trim()).filter(Boolean):void 0;if(J==="status"){let S=N.syncStatus();r(g.json||g.verbose?S:qf(S),g.json,g);return}if(J==="doctor"||J==="readiness"||J==="preflight"){let S=await N.syncDoctor({machine:g.machine??null,peerWorkspace:g.peerWorkspace??null,includeTailscale:g.tailscale!==!1,tables:P}),X={package:{name:C$.name,version:C$.version},...S};if(r(g.json||g.verbose?X:Bf(X),g.json,g),!S.ok&&!g.json)process.exitCode=1;return}if(J==="snapshot"||J==="record"){let S=await N.createSyncSnapshot({includeTailscale:g.tailscale!==!1,machineId:g.machine});r(g.json||g.verbose?S:Kf(S),g.json,g);return}if(J==="conflicts"||J==="conflict"){let S=$[2];if(S==="show"||S==="get"){let R=$[3]??g.id;if(!R)throw Error("Usage: knowledge sync conflicts show <id>");let K=N.syncConflict(R);r({ok:!0,conflict:K,message:`Sync conflict ${R}`},g.json,g);return}if(S==="propose"||S==="proposal"){let R=$[3]??g.id;if(!R)throw Error("Usage: knowledge sync conflicts propose <id>");r(g.mode==="ai"?await N.proposeSyncConflictResolutionWithAi({id:R,modelRef:g.model,fake:g.fake}):N.proposeSyncConflictResolution(R),g.json,g);return}if(S==="resolve"){let R=$[3]??g.id;if(!R)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let K=N.resolveSyncConflict({id:R,strategy:g.strategy,approvedBy:g.approvedBy,approveWrite:g.approveWrite,proposedPatchUri:g.patchUri});if(r(K,g.json,g),!K.ok&&!g.json)process.exitCode=1;return}let X=N.syncConflicts({status:S,limit:g.limit}),G={ok:!0,conflicts:X,message:`${X.length} sync conflict(s)`};r(g.json||g.verbose?G:Vf(G),g.json,g);return}if(J==="machines"||J==="registry"){let S=N.syncMachines(),X={ok:!0,machines:S,message:`${S.length} registered sync machine(s)`};r(g.json||g.verbose?X:Ff(X),g.json,g);return}if(J==="export"){let S=N.exportSyncBundle({machineId:g.machine??null,tables:P,includeArtifactContent:g.artifactContent!==!1});r(S,!0);return}if(J==="import"){let S=await Bun.stdin.text();if(!S.trim())throw Error("Usage: knowledge sync import < bundle.json");let X=await N.importSyncBundle({bundle:JSON.parse(S),dryRun:g.dryRun,direction:"import",machineId:g.machine??null});r(g.json||g.verbose?X:c8(X,J),g.json,g);return}if(J==="dry-run"||J==="pull"||J==="push"||J==="sync"){if(!g.peerWorkspace&&n8(g.machine))throw Error(`Usage: knowledge sync ${J} --peer-workspace <repo-or-knowledge-home> [--scope project] +Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let S=J==="dry-run"?"both":J==="sync"?"both":J,X=!n8(g.machine)?await N.syncRemotePeer({direction:S,machine:g.machine,peerWorkspace:g.peerWorkspace,tables:P,dryRun:g.dryRun===!0||J==="dry-run",includeArtifactContent:g.artifactContent!==!1,includeTailscale:g.tailscale!==!1}):await N.syncPeer({peerWorkspace:g.peerWorkspace,direction:S,dryRun:g.dryRun===!0||J==="dry-run",tables:P,includeArtifactContent:g.artifactContent!==!1,machineId:g.machine??null});if(r(g.json||g.verbose?X:c8(X,J),g.json,g),!X.ok&&!g.json)process.exitCode=1;return}throw Error("Invalid sync action. Use 'status', 'doctor', 'snapshot', 'conflicts', 'machines', 'dry-run', 'pull', 'push', 'sync', 'export', or 'import'.")}if(U==="db"){let J=$[1]??"init";if(J==="init"){let P=N.initDb();r({ok:!0,...P,message:`Initialized ${P.path}`},g.json,g);return}if(J==="stats"){let P=N.dbStats();r({ok:!0,path:N.workspace.knowledgeDbPath,...P,message:`knowledge.db schema v${P.schema_version}`},g.json,g);return}if(J==="storage"){if(($[2]??"status")==="status"){let S=t3({scope:g.scope});r({ok:!0,...S,message:`knowledge.db storage mode ${S.mode}`},g.json,g);return}throw Error("Invalid db storage action. Only 'status' is supported. The 'push'/'pull'/'sync' Postgres sync commands were removed (DSN-on-client is forbidden); use the cloud API flip instead.")}throw Error("Invalid db action. Use 'init', 'stats', or 'storage'.")}if(U==="app-wiki"){let J=$[1]??"init";if(J==="paths"||J==="status"){r({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...N.paths()},g.json);return}if(J==="init"||J==="open"){let P=await N.initAppWiki({allowGlobal:g.allowGlobal});r(P,g.json);return}if(J==="note"||J==="notes"){let P=$[2]??"list";if(P==="add"||P==="create"){let S=g.title??$[3],X=g.content??$.slice(4).join(" ");if(!S||!X)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let G=await N.addAppWikiNote({title:S,content:X,tags:g.tag,sourceRefs:g.sourceRef,allowGlobal:g.allowGlobal});r(G,g.json);return}if(P==="list"||P==="ls"){let S=N.listAppWikiNotes({limit:g.limit});r({ok:!0,scope:N.scope,home:N.workspace.home,notes:S,message:`${S.length} app wiki note(s)`},g.json);return}if(P==="get"||P==="show"){let S=$[3]??g.id;if(!S)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let X=await N.getAppWikiNote(S,{includeContent:!0});if(!X)throw Error(`App wiki note not found: ${S}`);r(X,g.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(J==="source"||J==="sources"){let P=$[2]??"add";if(P!=="add"&&P!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let S=$[3]??g.sourceRef?.[0];if(!S)throw Error("Usage: knowledge app-wiki source add <source-ref>");let X=await N.addAppWikiSourceRef({sourceRef:S,purpose:g.purpose,allowGlobal:g.allowGlobal});r({ok:!0,...X,message:`Added app wiki source ${X.source_ref}`},g.json);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki search <query>");let S=await N.searchAppWiki({query:P,limit:g.limit,semantic:g.semantic,modelRef:g.model,dimensions:g.dimensions,fake:g.fake});r({ok:!0,...S,message:`${S.results.length} app wiki result(s)`},g.json);return}if(J==="query"||J==="context"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki query <query>");let S=await N.queryAppWiki({query:P,limit:g.limit,semantic:g.semantic,modelRef:g.model,dimensions:g.dimensions,fake:g.fake});r({ok:!0,...S,message:`${S.excerpts.length} app wiki excerpt(s)`},g.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(U==="wiki"){let J=$[1]??"init";if(J==="init"){let P=await N.initWiki();r({ok:!0,...P,message:`Initialized wiki layout in ${N.workspace.home}`},g.json,g);return}if(J==="compile"){let P=$.slice(2),S=P.filter((R)=>/^(open-files|file|s3|https?):\/\//.test(R)),X=P.filter((R)=>!/^(open-files|file|s3|https?):\/\//.test(R)).join(" "),G=await N.compileWiki({title:g.title,query:X||g.search,sourceRefs:S.length>0?S:void 0,limit:g.limit});r({ok:!0,...G,message:`Compiled wiki page ${G.path}`},g.json,g);return}if(J==="file-answer"||J==="answer"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!g.content)throw Error("Missing --content <answer> for wiki file-answer.");let S=await N.fileAnswer({prompt:P,answer:g.content,approveWrite:g.approveWrite,limit:g.limit,semantic:g.semantic,modelRef:g.model,dimensions:g.dimensions,fake:g.fake});r({ok:!0,...S},g.json,g);return}if(J==="lint"){let P=N.lintWiki();r({ok:P.ok,...P,message:P.ok?"Wiki lint passed":`Wiki lint found ${P.issue_count} issue(s)`},g.json,g);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(U==="safety"){let J=$[1]??"status",P=N.ensureWorkspace(),S=N.safetyPolicy();N.initDb();let X=v(P.knowledgeDbPath);try{if(J==="status"){r({ok:!0,mode:S.mode,workspace:P.home,allow_write_roots:S.allowWriteRoots,read_only_source_access:S.readOnlySourceAccess,network:S.network,redaction:S.redaction,approvals:S.approvals,message:`Safety policy: ${S.mode}`},g.json,g);return}if(J==="check"){let G=$[2]??"generated_write",R=$[3]??null,K;try{if(G==="web_search")J0(S),K={action:G,target_uri:R,approval_required:!1,approved:!0,decision:"allow"};else if(G==="s3_read"){if(!R)throw Error("safety check s3_read requires an s3:// target.");q6(R,S),K={action:G,target_uri:R,approval_required:!1,approved:!0,decision:"allow"}}else K=uS(X,S,G,R);X_(X,{event_type:"safety_check",action:G,target_uri:R,decision:K.decision==="allow"?"allow":"requires_approval",metadata:K}),r({ok:!0,...K,message:`Safety check ${K.decision}`},g.json,g);return}catch(Q){throw X_(X,{event_type:"safety_check",action:G,target_uri:R,decision:"deny",metadata:{error:Q instanceof Error?Q.message:String(Q)}}),Q}}if(J==="approve"){let G=$[2]??"generated_write",R=$[3]??null,K=mU(X,{action:G,target_uri:R,reason:"local-cli approval",metadata:{scope:g.scope??"global"}});X_(X,{event_type:"approval",action:G,target_uri:R,decision:"allow",metadata:{approval_id:K.id}}),r({ok:!0,...K,action:G,target_uri:R,message:`Approved ${G}`},g.json,g);return}if(J==="audit"){let G=X.query("SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT 50").all().map((R)=>({id:R.id,event_type:R.event_type,action:R.action,target_uri:R.target_uri,decision:R.decision,metadata:JSON.parse(R.metadata_json),created_at:R.created_at}));r({ok:!0,events:G,message:`${G.length} audit event(s)`},g.json,g);return}if(J==="redact"){let G=$.slice(2).join(" ");if(!G)throw Error("Usage: knowledge safety redact <text>");let R=u_(G,S);if(R.findings.length>0)P0(X,{source_uri:"safety://redact",findings:R.findings,metadata:{command:"safety redact"}});X_(X,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:R.findings.length>0?"redacted":"allow",metadata:{findings:R.findings.length}}),r({ok:!0,text:R.text,findings:R.findings,message:`Redacted ${R.findings.length} finding(s)`},g.json,g);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{X.close()}}if(U==="source"){if(($[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let P=$[2];if(!P)throw Error("Usage: knowledge source resolve <source-ref>");let S=await N.resolveSource(P,{purpose:g.purpose,limit:g.limit});r({ok:!0,...S,message:S.resolved?`Resolved ${S.source_ref} (${S.content.chunks_returned}/${S.content.chunks_total} chunks)`:`Source not indexed: ${P}`},g.json,g);return}if(U==="ingest"){let J=$[1]??"";if(J==="rules"||J==="global-rules"||J==="agent-rules"){let P=await N.importRulesProvenance({root:g.workspace??process.cwd(),owner:g.owner,dryRun:g.dryRun===!0,maxItems:g.maxItems,limit:g.limit});r({ok:!0,...P},g.json);return}if(J==="manifest"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let S=await N.ingestManifest(P);r({ok:!0,...S,message:`Ingested ${S.items_seen} manifest item(s)`},g.json,g);return}if(J==="source"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest source <source-ref>");let S=await N.ingestSource(P,g.purpose);r({ok:!0,...S,message:`Ingested source ${S.source_ref} (${S.chunks_inserted} chunks)`},g.json,g);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(U==="reindex"){let J=$[1]??"status";if(J==="status"){let P=N.reindexHealth({modelRef:g.model,dimensions:g.dimensions,fake:g.fake});r({ok:!0,...P,message:`${P.missing_embeddings} chunk(s) missing embeddings`},g.json,g);return}if(J==="enqueue"){let P=N.enqueueReindex({modelRef:g.model,dimensions:g.dimensions,fake:g.fake});r({ok:!0,...P,message:`Queued ${P.enqueued} embedding refresh item(s)`},g.json,g);return}if(J==="embeddings"){let P=await N.refreshEmbeddings({full:g.full,limit:g.limit,modelRef:g.model,dimensions:g.dimensions,fake:g.fake});r({ok:!0,...P,message:`Embedded ${P.indexed.chunks_embedded} chunk(s)`},g.json,g);return}if(J==="outbox"){let P=$[2];if(!P)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let S=await N.consumeOutbox(P);r({ok:!0,...S,message:`Consumed ${S.events_seen} outbox event(s)`},g.json,g);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(U==="embeddings"){let J=$[1]??"status";if(J==="status"){let P=N.embeddingStatus();r({ok:!0,...P,message:`${P.total_vector_entries} vector index entries`},g.json,g);return}if(J==="index"){let P=await N.indexEmbeddings({limit:g.limit,modelRef:g.model,dimensions:g.dimensions,fake:g.fake});r({ok:!0,...P,message:`Embedded ${P.chunks_embedded} chunk(s)`},g.json,g);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge embeddings search <query>");let S=await N.semanticSearch({query:P,limit:g.limit,modelRef:g.model,dimensions:g.dimensions,fake:g.fake}),X={ok:!0,...S,message:`${S.results.length} semantic result(s)`};r(g.json||g.verbose?X:Gf(X),g.json,g);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(U==="context"){if(($[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let P=g.from??"search";if(!["search","loops","runs"].includes(P))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let S=$.slice(2).join(" ")||g.topic||"",X=await N.contextPack({source:P,purpose:P==="loops"||P==="runs"?"proposal":"agent_context",query:S,topic:g.topic,since:g.since,dedupe:g.dedupe,maxTokens:g.maxTokens,maxItems:g.maxItems,limit:g.limit,semantic:g.semantic,modelRef:g.model,dimensions:g.dimensions,fake:g.fake,legacyStorePath:A});h8({ok:!0,...X,message:X.message});return}if(U==="proposals"){if(($[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let P=g.from??"loops";if(!["loops","runs"].includes(P))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let S=g.topic??$.slice(2).join(" ");if(!S.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let X=await N.contextPack({source:P,purpose:"proposal",query:S,topic:S,since:g.since,dedupe:g.dedupe??!0,maxTokens:g.maxTokens,maxItems:g.maxItems,limit:g.limit});h8({ok:!0,...X,message:X.message});return}if(U==="search"){let J=$.slice(1).join(" ");if(!J)throw Error("Usage: knowledge search <query>");if(g.context){let X=await N.retrieveContext({query:J,limit:g.limit,semantic:g.semantic,modelRef:g.model,dimensions:g.dimensions,fake:g.fake,legacyStorePath:A}),G={ok:!0,...X,message:`${X.excerpts.length} context excerpt(s)`};r(g.json||g.verbose?G:Rf(G),g.json,g);return}let P=await N.search({query:J,limit:g.limit,semantic:g.semantic,modelRef:g.model,dimensions:g.dimensions,fake:g.fake,legacyStorePath:A}),S={ok:!0,...P,message:`${P.results.length} search result(s)`};r(g.json||g.verbose?S:Xf(S),g.json,g);return}if(U==="web"){if(($[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge web search <query>");let S=await N.webSearch({query:P,limit:g.limit,modelRef:g.model,provider:g.provider,domains:g.domain,fake:g.fake,fileResults:g.fileResults}),X={ok:!0,...S,message:`${S.sources.length} web source(s)`};r(g.json||g.verbose?X:Yf(X),g.json,g);return}if(U==="ask"||U==="build"){let J=$.slice(D).join(" ");if(!J)throw Error("Usage: knowledge ask <prompt>");let P=await N.runPrompt({prompt:J,limit:g.limit,semantic:g.semantic,modelRef:g.model,dimensions:g.dimensions,fake:g.fake,generate:g.generate,approveWrite:g.approveWrite,legacyStorePath:A}),S={ok:!0,...P,message:P.generated?"Generated answer with citations":"Prepared citation context draft"};r(g.json||g.verbose?S:Mf(S),g.json,g);return}if(U==="providers"){let J=$[1]??"status";if(J==="status"){let P=N.providerStatus(),S=P.providers.filter((X)=>X.configured).length;r({ok:!0,...P,message:`${S}/${P.providers.length} provider credential(s) configured`},g.json,g);return}if(J==="models"){let P=N.modelRegistry();r({ok:!0,models:P,message:`${P.length} model alias(es)`},g.json,g);return}if(J==="check"){let P=$[2]??"default",S=G$(P,N.config()),X=f_(S),G=D4(X.provider,N.config());r({ok:!0,target:P,model_ref:S,provider:X.provider,model:X.model,credential:G,message:`${X.provider} credentials configured`},g.json,g);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(U==="add"){let J=$[1],P=$[2];if(!J||!P)throw Error("Usage: knowledge add <title> <content>");let S=await L.create({title:J,content:P,url:g.url??null,tags:g.tag??[]});$0("info","Item added",{id:S.id,title:S.title,tags:S.tags?.length??0,transport:L.kind}),r({ok:!0,item:S,message:`Added ${S.id}`},g.json,g);return}if(U==="list"){if(g.format!==void 0&&g.format!=="table"&&g.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");let J=await L.listAll(),P=Number.isFinite(g.page)&&g.page>0?g.page:1,S=Number.isFinite(g.limit)&&g.limit>0?g.limit:20,X=g.search?String(g.search).toLowerCase():"",G=(g.tagRaw??g.tag??[]).map((p)=>({whole:p.trim().toLowerCase(),parts:p.split(",").map((r_)=>r_.trim().toLowerCase()).filter((r_)=>r_.length>0)})),R=g.tag?.length?g.tag.map((p)=>p.toLowerCase()).join(","):"none",K=g.format==="table"||!g.json&&!g.format&&Jf(g),Q=g.json||g.format==="json",T=J.items;if(g.archived)T=T.filter((p)=>p.archived===!0);else if(!g.includeArchived)T=T.filter((p)=>!p.archived);if(X)T=T.filter((p)=>p.title.toLowerCase().includes(X)||p.content.toLowerCase().includes(X));if(G.length>0)T=T.filter((p)=>{let r_=new Set((p.tags??[]).map((K_)=>K_.toLowerCase()));return G.every(({whole:K_,parts:G_})=>K_.length>0&&r_.has(K_)||G_.every((H_)=>r_.has(H_)))});let{sorted:q,sort:V,direction:Z}=bf(T,g),a=(P-1)*S,D_=q.slice(a,a+S),I_=Math.max(1,Math.ceil(q.length/S)),J_={ok:!0,page:P,limit:S,total:q.length,total_pages:I_,sort:V,direction:Z,items:D_,store_exists:J.exists};if(Q){r(J_,!0);return}if(g.verbose){r(J_,!1,g);return}if(D_.length===0){r(`No items found (search=${X||"none"}, tag=${R})`,!1);return}if(K){let p=(K_)=>K_,r_=`${p("ID")} ${p("TITLE")} ${p("CREATED")} ${p("URL")} ${p("TAGS")}`;console.log(r_);for(let K_ of D_)console.log(`${K_.id} ${p(g_(K_.title,80))} ${K_.created_at} ${K_.url?p(g_(K_.url,90)):""} ${K_.tags?.length?p(g_(`[${K_.tags.join(", ")}]`,80)):""}`);console.log(`Page ${P}/${I_} | showing ${D_.length} of ${q.length} | sort=${V} ${Z} | search=${X||"none"} | tag=${R}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let p of D_)console.log(`${p.id} ${g_(p.title,80)} ${p.created_at}${p.url?` ${g_(p.url,90)}`:""}${p.tags?.length?` ${g_(`[${p.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${P}/${I_} | showing ${D_.length} of ${q.length} | sort=${V} ${Z} | search=${X||"none"} | tag=${R}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(U==="get"){_0(g);let J=await L.get(g.id);if(!J)throw Error(`Item not found: ${g.id}`);r({ok:!0,item:J,store_exists:L.exists,message:`${J.id}: ${J.title}`},g.json,g);return}if(U==="versions"){_0(g);let J=Number.isFinite(g.page)&&g.page>0?g.page:1,P=Number.isFinite(g.limit)&&g.limit>0?g.limit:void 0,S=await L.listVersions(g.id,{limit:P,offset:(J-1)*(P??50)});if(!S)throw Error(`Item not found: ${g.id}`);let X={ok:!0,id:S.item_id,current_version:S.current_version,total:S.total,page:J,store:L.location,versions:S.items,message:S.total===0?`${S.item_id} is at version ${S.current_version} with no retained prior versions`:`${S.item_id} is at version ${S.current_version}; ${S.total} prior version(s) retained`};if(g.json||g.verbose){r(X,g.json,g);return}console.log(X.message);for(let G of S.items){let R=G.actor?` by ${G.actor}`:"",K=G.reason?` (${G.reason})`:"";console.log(`v${G.version} ${G.valid_to}${R}${K} ${G.content_bytes} bytes ${G.content_hash.slice(0,12)}`)}if(S.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(U==="diff"){_0(g);let J=await L.get(g.id);if(!J)throw Error(`Item not found: ${g.id}`);if(g.rev!==void 0&&(g.from!==void 0||g.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let P=()=>({title:J.title,content:J.content,url:J.url,tags:J.tags??[],metadata:J.metadata??{},archived:J.archived??!1}),S=`v${J.version??"?"} (current)`,X=async(q)=>{if(q==="current")return{label:S,snapshot:P()};let V=Number(q);if(!Number.isInteger(V)||V<1)throw Error(`Not a version number: ${q}`);if(J.version!==void 0&&V===J.version)return{label:S,snapshot:P()};let Z=await L.getVersion(J.id,V);if(!Z)throw Error(`No version ${V} retained for ${J.id} (it is at version ${J.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${Z.version}`,snapshot:{title:Z.title,content:Z.content,url:Z.url,tags:Z.tags,metadata:Z.metadata,archived:Z.archived}}},G,R;if(g.rev!==void 0){if(!Number.isInteger(g.rev)||g.rev<1)throw Error("--rev must be a positive version number.");if(g.rev===1)throw Error("Version 1 has no predecessor to diff against.");G=String(g.rev-1),R=String(g.rev)}else if(g.from!==void 0||g.to!==void 0){if(g.from===void 0||g.to===void 0)throw Error("--from and --to must be given together.");G=g.from,R=g.to}else{let q=await L.listVersions(J.id,{limit:1});if(!q)throw Error(`Item not found: ${g.id}`);if(q.items.length===0)throw Error(`${J.id} is at version ${q.current_version} with no retained prior versions to diff against.`);G=String(q.items[0].version),R="current"}let K=await X(G),Q=await X(R),T=OS(K.snapshot,Q.snapshot);if(g.json||g.verbose){r({ok:!0,id:J.id,from:K.label,to:Q.label,...T},g.json,g);return}console.log(AS(T,`${J.id} ${K.label}`,`${J.id} ${Q.label}`));return}if(U==="update"){_0(g);let J=await L.get(g.id);if(!J)throw Error(`Item not found: ${g.id}`);let P={};if(g.title!==void 0)P.title=g.title;if(g.content!==void 0)P.content=g.content;if(g.url!==void 0)P.url=g.url;let S;if(g.tag!==void 0){if(S=y8(J.tags,g.tag),S.length>0)P.tags=[...J.tags??[],...S]}let X=await L.update(J.id,P,{expectedVersion:J.version});r(Oz({ok:!0,item:X},`Updated ${X?.id??J.id}`,S),g.json,g);return}if(U==="archive"||U==="restore"){_0(g);let J=await L.get(g.id);if(!J)throw Error(`Item not found: ${g.id}`);let P=await L.update(J.id,{archived:U==="archive"},{expectedVersion:J.version});r({ok:!0,item:P,message:`${U==="archive"?"Archived":"Restored"} ${P?.id??J.id}`},g.json,g);return}if(U==="untag"){if(_0(g),!g.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let J=await L.get(g.id);if(!J)throw Error(`Item not found: ${g.id}`);let P=J.tags??[],S=new Set(P.map((V)=>V.toLowerCase())),X=new Set;for(let V of g.tagRaw??g.tag){let Z=V.trim().toLowerCase();if(Z.length>0&&S.has(Z)){X.add(Z);continue}for(let a of V.split(",").map((D_)=>D_.trim().toLowerCase()).filter((D_)=>D_.length>0))X.add(a)}let G=P.filter((V)=>!X.has(V.toLowerCase())),R=P.length-G.length,K=[...X].filter((V)=>!S.has(V));if(R===0)throw Error(`No matching tag on ${J.id}: ${K.map((V)=>JSON.stringify(V)).join(", ")} not in [${P.map((V)=>JSON.stringify(V)).join(", ")}]`);let Q=await L.update(J.id,{tags:G},{expectedVersion:J.version}),T=K.length>0?` (not found: ${K.map((V)=>JSON.stringify(V)).join(", ")})`:"",q={ok:!0,item:Q,removed:R,message:`Removed ${R} tag${R===1?"":"s"} from ${Q?.id??J.id}${T}`};if(K.length>0)q.not_found=K;r(q,g.json,g);return}if(U==="upsert"){let J=g.title??$[1],P=g.content??$[2],S=g.id?await L.get(g.id):null;if(!S){if(!J||!P)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let K=await L.create({id:g.id,title:J,content:P,url:g.url??null,tags:g.tag??[]});r(Oz({ok:!0,created:!0,item:K},`Upserted ${K.id}`,g.tag),g.json,g);return}let X={};if(J!==void 0)X.title=J;if(P!==void 0)X.content=P;if(g.url!==void 0)X.url=g.url;let G;if(g.tag!==void 0){if(G=y8(S.tags,g.tag),G.length>0)X.tags=[...S.tags??[],...G]}let R=await L.update(S.id,X,{expectedVersion:S.version});r(Oz({ok:!0,created:!1,item:R},`Upserted ${R?.id??S.id}`,G),g.json,g);return}if(U==="delete"){if(_0(g),!g.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await L.delete(g.id))throw Error(`Item not found: ${g.id}`);$0("info","Item deleted",{id:g.id,transport:L.kind}),r({ok:!0,deleted_id:g.id,message:`Deleted ${g.id}`},g.json,g);return}if(U==="export"){let J=g.format??"json";if(J!=="json"&&J!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let P=await L.listAll();if(J==="jsonl")for(let S of P.items)console.log(JSON.stringify(S));else if(g.json||g.format==="json"||g.verbose)r({ok:!0,items:P.items,store_exists:P.exists},g.json||g.format==="json",g);else r(Zf(P.items,J),!1);return}if(U==="prune"){if(!g.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:J}=await L.listAll(),P=g.olderThan!==void 0?new Date(Date.now()-g.olderThan*86400000):null,S=J.filter((R)=>P!==null&&new Date(R.created_at)<P||g.empty&&R.content.trim().length===0),X=await L.deleteMany(S.map((R)=>R.id)),G=J.length-X;$0("info","Prune completed",{pruned:X,remaining:G,transport:L.kind}),r({ok:!0,pruned:X,remaining:G,message:`Pruned ${X} item(s)`},g.json,g);return}if(U==="dedupe"){if(!g.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:J}=await L.listAll(),P=new Set,S=[];for(let R of J){let K=`${R.title}\x00${R.content}`;if(P.has(K))S.push(R);else P.add(K)}let X=await L.deleteMany(S.map((R)=>R.id)),G=J.length-X;$0("info","Dedupe completed",{removed:X,remaining:G,transport:L.kind}),r({ok:!0,removed:X,remaining:G,message:`Dedupe removed ${X} duplicate(s)`},g.json,g);return}if(U==="stats"){let J=await L.listAll(),P=J.items.filter((V)=>!V.archived),S=P.length,X=J.items.length-S,G=P.filter((V)=>V.url).length,R=P.filter((V)=>V.tags&&V.tags.length>0).length,K=S>0?P.map((V)=>V.created_at).sort()[0]:null,Q=S>0?P.map((V)=>V.created_at).sort()[S-1]:null,T={};for(let V of P)for(let Z of V.tags||[])T[Z]=(T[Z]||0)+1;let q=Object.entries(T).sort((V,Z)=>Z[1]-V[1]).slice(0,5).map(([V,Z])=>({tag:V,count:Z}));r({ok:!0,total:S,archived:X,with_url:G,with_tags:R,oldest:K,newest:Q,top_tags:q,store_exists:J.exists,message:`${S} items | ${G} with URL | ${R} with tags`},g.json,g);return}let z=Nf($[0]),W=z?` Did you mean '${z}'?`:"";throw $0("warn","Unknown command",{input:$[0],suggestion:z}),Error(`Unknown command: ${$[0]}.${W} Run 'knowledge --help' for available commands.`)}function kf(_,$){let g=_ instanceof Error?_.message:String(_);if($0("debug","CLI error",{message:g,stack:_ instanceof Error?_.stack:void 0}),console.error(`Error: ${g}`),$.includes("--json"))r({ok:!1,error:g,message:g},!0);process.exitCode=1}if(import.meta.main){let _=process.argv.slice(2);Hf(_).catch(($)=>kf($,_))}export{Nf as suggestCommand,bf as sortItems,Hf as run,Uf as parseArgs,kf as emitCliError}; diff --git a/bun.lock b/bun.lock index b69ccdd..67c7a04 100644 --- a/bun.lock +++ b/bun.lock @@ -20,7 +20,7 @@ }, "devDependencies": { "@electric-sql/pglite": "^0.5.4", - "@hasna/contracts": "0.5.2", + "@hasna/contracts": "0.8.5", "@types/bun": "^1.3.14", "@types/pg": "^8.15.6", }, @@ -81,7 +81,7 @@ "@electric-sql/pglite": ["@electric-sql/pglite@0.5.4", "", {}, "sha512-yYZUyyXrHU7tPlCjwZQJ6hIG9DscdCCn7Uk0mYKwC1FeHX286AbcmFveMiRBEak8e9iPupjsoVImN3yJZVed2g=="], - "@hasna/contracts": ["@hasna/contracts@0.5.2", "", { "dependencies": { "commander": "^13.1.0", "zod": "^3.25.76" }, "bin": { "contracts": "dist/cli/index.js", "contracts-cli": "dist/cli/index.js" } }, "sha512-R7NBm91oMOWQVnfIyh7QTEPuWbVycGaObzKFJd1je5RNjXsLuPASqCfr9heJ7nuugn9xxFBCCRQCxHg9/VeJrg=="], + "@hasna/contracts": ["@hasna/contracts@0.8.5", "", { "dependencies": { "commander": "^13.1.0", "zod": "^3.25.76" }, "bin": { "contracts": "dist/cli/index.js", "contracts-cli": "dist/cli/contracts-cli.js" } }, "sha512-Iyk5srD6J3R7ci2g0gkyt+MCa6Da/lghPosGtgWBRgtJeGYCIAAnHF1yweoXnnqGAWZajFuDgJEWDVH11qpUhA=="], "@hasna/events": ["@hasna/events@0.1.14", "", { "dependencies": { "commander": "^13.1.0" }, "bin": { "events": "dist/cli/index.js", "hasna-events": "dist/cli/index.js" } }, "sha512-UXzEM6/8XUeysIUHspe7U3lottNZ7Ir6zwEJn5wH3MCtTXHuh+Vva+uPCowf6RAVnhxZic3xrfYk5atVBRFyLA=="], diff --git a/dist/agent.d.ts b/dist/agent.d.ts index 251f55b..1d2c9b1 100644 --- a/dist/agent.d.ts +++ b/dist/agent.d.ts @@ -38,7 +38,7 @@ export interface KnowledgePromptOverItemsOptions extends Omit<KnowledgePromptOpt } /** * Run an `ask`/`build` prompt against an in-memory knowledge-item corpus — the - * api (self_hosted / cloud) path. Retrieval reads the shared cloud items (fetched + * postgres/API path. Retrieval reads the shared API items (fetched * through the item Store); the LLM runs client-side with the caller's provider * key. There is no local sqlite catalog, so run telemetry is not persisted to a * local db (it would be split-brain); the run id is still returned for the shape. diff --git a/dist/cloud-store.d.ts b/dist/cloud-store.d.ts index 509a71c..7afb4ae 100644 --- a/dist/cloud-store.d.ts +++ b/dist/cloud-store.d.ts @@ -75,8 +75,9 @@ export interface KnowledgeCloudStore { } /** * Resolve the cloud knowledge store from the environment. Returns a ready - * {@link KnowledgeCloudStore} when the mode is explicitly cloud, else `null` so - * the caller uses the local db.json store. Throws if cloud was requested but + * {@link KnowledgeCloudStore} when the backend is explicitly postgres, else + * `null` so the caller uses the local db.json store. Throws if postgres was + * requested but * misconfigured (never silent local drift). * * On the local path the contracts resolver is not called at all: no transport is @@ -88,7 +89,7 @@ export declare function resolveKnowledgeCloudStore(env?: NodeJS.ProcessEnv): Kno * The single mode signal the whole client uses: item commands route to the * ApiStore, and the local sqlite catalog is refused (never a silent split-brain * write). Local — the default, and the answer whenever no mode var says - * otherwise — returns false. Throws only when cloud was explicitly requested + * otherwise — returns false. Throws only when postgres was explicitly requested * but misconfigured, matching the item Store: never silent drift. */ export declare function isKnowledgeApiMode(env?: NodeJS.ProcessEnv): boolean; diff --git a/dist/db/remote-storage.d.ts b/dist/db/remote-storage.d.ts index 5fe1872..cd448c6 100644 --- a/dist/db/remote-storage.d.ts +++ b/dist/db/remote-storage.d.ts @@ -13,8 +13,8 @@ export declare const KNOWLEDGE_APP_NAME = "knowledge"; * `PgAdapterAsync` client adapter — a DSN-on-client sync engine — has been * removed to eliminate that forbidden path. * - * Requires `HASNA_KNOWLEDGE_STORAGE_MODE=cloud` and + * Requires `HASNA_KNOWLEDGE_STORAGE_MODE=postgres` and * `HASNA_KNOWLEDGE_DATABASE_URL`. Throws (without logging the URL) when the - * mode is not `cloud` or the URL is missing. + * mode is not `postgres` or the URL is missing. */ export declare function createKnowledgeCloudClient(): PoolQueryClient; diff --git a/dist/db/storage-sync.d.ts b/dist/db/storage-sync.d.ts index 1c188ae..ce8cedd 100644 --- a/dist/db/storage-sync.d.ts +++ b/dist/db/storage-sync.d.ts @@ -13,13 +13,13 @@ export declare const STORAGE_TABLES: readonly ['sources', 'wiki_pages', 'source_ export declare const KNOWLEDGE_STORAGE_TABLES: readonly ["sources", "wiki_pages", "source_revisions", "chunks", "chunk_embeddings", "wiki_backlinks", "citations", "knowledge_indexes", "runs", "run_events", "provider_usage", "redaction_findings", "storage_objects", "audit_events", "approval_gates", "vector_index_entries", "reindex_queue", "knowledge_machines", "knowledge_sync_snapshots", "knowledge_sync_changes", "knowledge_sync_conflicts", "knowledge_sync_table_clocks", "knowledge_sync_imports"]; type StorageTable = (typeof STORAGE_TABLES)[number]; /** - * Runtime storage mode per Amendment A1 (PURE REMOTE): - * - `local`: SQLite knowledge.db is authoritative. - * - `cloud`: the shared store is reached through the HTTP ApiStore. - * The legacy words `hybrid`, `remote`, and `self_hosted` are accepted only as - * deprecated aliases that normalize to `cloud`. + * Runtime storage backend: + * - `sqlite`: on-box SQLite knowledge.db is authoritative. + * - `postgres`: the shared store is reached through the HTTP ApiStore. + * The removed runtime-placement words (`local`, `cloud`, `hybrid`, `remote`, + * and `self_hosted`) are not accepted here. */ -export type StorageMode = 'local' | 'cloud'; +export type StorageMode = 'sqlite' | 'postgres'; export interface StorageSyncOptions { tables?: string[]; scope?: string; diff --git a/dist/generated/storage-kit/index.d.ts b/dist/generated/storage-kit/index.d.ts index 8580a14..47096d0 100644 --- a/dist/generated/storage-kit/index.d.ts +++ b/dist/generated/storage-kit/index.d.ts @@ -1,4 +1,4 @@ -export declare const KIT_VERSION = "0.4.0"; +export declare const KIT_VERSION = "0.8.5"; export * from "./mode.js"; export * from "./tls.js"; export * from "./query.js"; diff --git a/dist/generated/storage-kit/migrations.d.ts b/dist/generated/storage-kit/migrations.d.ts index 15e2a45..4356512 100644 --- a/dist/generated/storage-kit/migrations.d.ts +++ b/dist/generated/storage-kit/migrations.d.ts @@ -42,7 +42,6 @@ export declare class MigrationLedger { migrate(opts?: { dryRun?: boolean; }): Promise<MigrationResult>; - private applyPendingMigration; } /** Convenience: build a ledger and run all pending migrations. */ export declare function createMigrationLedger(client: TypedQueryClient, migrations: readonly Migration[], options?: MigrationRunnerOptions): MigrationLedger; diff --git a/dist/generated/storage-kit/mode.d.ts b/dist/generated/storage-kit/mode.d.ts index e374182..421861b 100644 --- a/dist/generated/storage-kit/mode.d.ts +++ b/dist/generated/storage-kit/mode.d.ts @@ -1,16 +1,13 @@ -export declare const STORAGE_MODES: readonly ["local", "cloud"]; +export declare const STORAGE_MODES: readonly ["sqlite", "postgres"]; export type StorageMode = (typeof STORAGE_MODES)[number]; -export declare const DEPRECATED_STORAGE_MODE_ALIASES: readonly ["remote", "hybrid", "self_hosted"]; export type Env = Record<string, string | undefined>; export interface StorageModeNormalization { mode: StorageMode; - /** The deprecated alias that was normalized to `cloud`, if any. */ - deprecatedAlias: string | null; } /** - * Normalize a raw storage-mode string to the `local | cloud` runtime enum. - * Accepts deprecated aliases (`remote`, `hybrid`, `self_hosted`) and maps them - * to `cloud`. Throws on any other value. + * Normalize a raw storage-backend string to the `sqlite | postgres` enum. + * `postgresql` is accepted as the long spelling of `postgres`. Throws on any + * other value with a migration hint. */ export declare function normalizeStorageMode(value: string): StorageModeNormalization; /** Upper-snake env token for an app name, e.g. `todos` -> `TODOS`. */ @@ -25,18 +22,18 @@ export interface StorageEnvKeys { export declare function storageEnvKeys(name: string): StorageEnvKeys; export interface StorageModeResolution { mode: StorageMode; - /** Env key the mode came from, or `"default"`. */ + /** Env key the backend came from, or `"default"`. */ source: string; - deprecatedAlias: string | null; databaseUrlPresent: boolean; /** Env key the database URL came from, or `null`. */ databaseUrlSource: string | null; warning: string | null; } /** - * Resolve an app's storage mode from the environment per the contract env spec. - * Precedence: `HASNA_<NAME>_STORAGE_MODE`, then `<NAME>_STORAGE_MODE`, else - * `local`. Never reads secret values — only detects DATABASE_URL presence. + * Resolve an app's storage backend from the environment per the contract env + * spec. Precedence: `HASNA_<NAME>_STORAGE_MODE`, then `<NAME>_STORAGE_MODE`; + * absent both, a present `DATABASE_URL` selects `postgres`, else `sqlite`. + * Never reads secret values — only detects DATABASE_URL presence. */ export declare function resolveStorageMode(name: string, env?: Env): StorageModeResolution; /** diff --git a/dist/generated/storage-kit/pool.d.ts b/dist/generated/storage-kit/pool.d.ts index efb1857..9840826 100644 --- a/dist/generated/storage-kit/pool.d.ts +++ b/dist/generated/storage-kit/pool.d.ts @@ -14,20 +14,21 @@ export interface CreatePgPoolOptions extends TlsResolveOptions { } /** Build a `pg.Pool` with fleet-standard TLS handling. */ export declare function createPgPool(options: CreatePgPoolOptions): Pool; -export interface CreateCloudPoolFromEnvOptions extends TlsResolveOptions { +export interface CreateServerPoolFromEnvOptions extends TlsResolveOptions { max?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; applicationName?: string; } -export interface CloudPoolFromEnv { +export interface ServerPoolFromEnv { client: PoolQueryClient; connectionSource: string; } /** - * Resolve mode + database URL from the environment and build a cloud pool. + * Resolve backend + database URL from the environment and build the server's + * PostgreSQL pool. * - * Throws when the resolved mode is not `cloud` (PURE REMOTE has no Postgres in - * `local` mode) or when the database URL is missing. Never logs the URL. + * Throws when the resolved backend is not `postgres` (the sqlite backend has + * no Postgres pool) or when the database URL is missing. Never logs the URL. */ -export declare function createCloudPoolFromEnv(appName: string, options?: CreateCloudPoolFromEnvOptions): CloudPoolFromEnv; +export declare function createServerPoolFromEnv(appName: string, options?: CreateServerPoolFromEnvOptions): ServerPoolFromEnv; diff --git a/dist/index.js b/dist/index.js index ca41938..93d7c80 100644 --- a/dist/index.js +++ b/dist/index.js @@ -74,9 +74,9 @@ function config(newConfig) { Object.assign(globalConfig, newConfig); return globalConfig; } -var _a, NEVER4, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig; +var _a, NEVER, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig; var init_core = __esm(() => { - NEVER4 = /* @__PURE__ */ Object.freeze({ + NEVER = /* @__PURE__ */ Object.freeze({ status: "aborted" }); $brand = Symbol("zod_brand"); @@ -130,11 +130,11 @@ __export(exports_util, { isObject: () => isObject, hexToUint8Array: () => hexToUint8Array, getSizableOrigin: () => getSizableOrigin, - getParsedType: () => getParsedType4, + getParsedType: () => getParsedType, getLengthableOrigin: () => getLengthableOrigin, getEnumValues: () => getEnumValues, getElementAtPath: () => getElementAtPath, - floatSafeRemainder: () => floatSafeRemainder4, + floatSafeRemainder: () => floatSafeRemainder, finalizeIssue: () => finalizeIssue, extend: () => extend, explicitlyAborted: () => explicitlyAborted, @@ -207,7 +207,7 @@ function cleanRegex(source) { const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } -function floatSafeRemainder4(val, step) { +function floatSafeRemainder(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); @@ -705,7 +705,7 @@ function uint8ArrayToHex(bytes) { class Class { constructor(..._args) {} } -var EVALUATING, captureStackTrace, allowsEval, getParsedType4 = (data) => { +var EVALUATING, captureStackTrace, allowsEval, getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": @@ -1097,8 +1097,8 @@ function datetime(args) { opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex4 = `${time2}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex4})$`); + const timeRegex = `${time2}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } function fixedBase64(bodyLength, padding) { return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); @@ -1261,7 +1261,7 @@ var init_checks = __esm(() => { inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder4(payload.value, def.value) === 0; + const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ @@ -1797,7 +1797,7 @@ function isValidBase64URL(data) { const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "="); return isValidBase64(padded); } -function isValidJWT4(token, algorithm = null) { +function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); if (tokensParts.length !== 3) @@ -1947,7 +1947,7 @@ function handleExclusiveUnionResults(results, final, inst, ctx) { } return final; } -function mergeValues4(a, b) { +function mergeValues(a, b) { if (a === b) { return { valid: true, data: a }; } @@ -1959,7 +1959,7 @@ function mergeValues4(a, b) { const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { - const sharedValue = mergeValues4(a[key], b[key]); + const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false, @@ -1978,7 +1978,7 @@ function mergeValues4(a, b) { for (let index = 0;index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; - const sharedValue = mergeValues4(itemA, itemB); + const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false, @@ -2023,7 +2023,7 @@ function handleIntersectionResults(result, left, right) { } if (aborted(result)) return result; - const merged = mergeValues4(left.value, right.value); + const merged = mergeValues(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); } @@ -2207,7 +2207,7 @@ var init_schemas = __esm(() => { }); } else { const runChecks = (payload, checks2, ctx) => { - let isAborted4 = aborted(payload); + let isAborted = aborted(payload); let asyncResult; for (const ch of checks2) { if (ch._zod.def.when) { @@ -2216,7 +2216,7 @@ var init_schemas = __esm(() => { const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; - } else if (isAborted4) { + } else if (isAborted) { continue; } const currLen = payload.issues.length; @@ -2230,15 +2230,15 @@ var init_schemas = __esm(() => { const nextLen = payload.issues.length; if (nextLen === currLen) return; - if (!isAborted4) - isAborted4 = aborted(payload, currLen); + if (!isAborted) + isAborted = aborted(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; - if (!isAborted4) - isAborted4 = aborted(payload, currLen); + if (!isAborted) + isAborted = aborted(payload, currLen); } } if (asyncResult) { @@ -2554,7 +2554,7 @@ var init_schemas = __esm(() => { $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - if (isValidJWT4(payload.value, def.alg)) + if (isValidJWT(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", @@ -4944,7 +4944,7 @@ var init_el = __esm(() => { }); // node_modules/zod/v4/locales/en.js -function en_default4() { +function en_default() { return { localeError: error10() }; @@ -9964,7 +9964,7 @@ __export(exports_locales, { fa: () => fa_default, es: () => es_default, eo: () => eo_default, - en: () => en_default4, + en: () => en_default, el: () => el_default, de: () => de_default, da: () => da_default, @@ -11960,7 +11960,7 @@ __export(exports_core2, { parse: () => parse, meta: () => meta, locales: () => exports_locales, - isValidJWT: () => isValidJWT4, + isValidJWT: () => isValidJWT, isValidBase64URL: () => isValidBase64URL, isValidBase64: () => isValidBase64, initializeContext: () => initializeContext, @@ -12106,7 +12106,7 @@ __export(exports_core2, { _array: () => _array, _any: () => _any, TimePrecision: () => TimePrecision, - NEVER: () => NEVER4, + NEVER: () => NEVER, JSONSchemaGenerator: () => JSONSchemaGenerator, JSONSchema: () => exports_json_schema, Doc: () => Doc, @@ -12346,12 +12346,12 @@ var initializer2 = (inst, issues) => { } } }); -}, ZodError4, ZodRealError; +}, ZodError, ZodRealError; var init_errors2 = __esm(() => { init_core2(); init_core2(); init_util(); - ZodError4 = /* @__PURE__ */ $constructor("ZodError", initializer2); + ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { Parent: Error }); @@ -12459,7 +12459,7 @@ __export(exports_schemas2, { discriminatedUnion: () => discriminatedUnion, describe: () => describe2, date: () => date3, - custom: () => custom4, + custom: () => custom, cuid2: () => cuid22, cuid: () => cuid3, codec: () => codec, @@ -12478,73 +12478,73 @@ __export(exports_schemas2, { _ZodString: () => _ZodString, ZodXor: () => ZodXor, ZodXID: () => ZodXID, - ZodVoid: () => ZodVoid4, - ZodUnknown: () => ZodUnknown4, - ZodUnion: () => ZodUnion4, - ZodUndefined: () => ZodUndefined4, + ZodVoid: () => ZodVoid, + ZodUnknown: () => ZodUnknown, + ZodUnion: () => ZodUnion, + ZodUndefined: () => ZodUndefined, ZodUUID: () => ZodUUID, ZodURL: () => ZodURL, ZodULID: () => ZodULID, - ZodType: () => ZodType4, - ZodTuple: () => ZodTuple4, + ZodType: () => ZodType, + ZodTuple: () => ZodTuple, ZodTransform: () => ZodTransform, ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodSymbol: () => ZodSymbol4, + ZodSymbol: () => ZodSymbol, ZodSuccess: () => ZodSuccess, ZodStringFormat: () => ZodStringFormat, - ZodString: () => ZodString4, - ZodSet: () => ZodSet4, - ZodRecord: () => ZodRecord4, - ZodReadonly: () => ZodReadonly4, - ZodPromise: () => ZodPromise4, + ZodString: () => ZodString, + ZodSet: () => ZodSet, + ZodRecord: () => ZodRecord, + ZodReadonly: () => ZodReadonly, + ZodPromise: () => ZodPromise, ZodPreprocess: () => ZodPreprocess, ZodPrefault: () => ZodPrefault, ZodPipe: () => ZodPipe, - ZodOptional: () => ZodOptional4, - ZodObject: () => ZodObject4, + ZodOptional: () => ZodOptional, + ZodObject: () => ZodObject, ZodNumberFormat: () => ZodNumberFormat, - ZodNumber: () => ZodNumber4, - ZodNullable: () => ZodNullable4, - ZodNull: () => ZodNull4, + ZodNumber: () => ZodNumber, + ZodNullable: () => ZodNullable, + ZodNull: () => ZodNull, ZodNonOptional: () => ZodNonOptional, - ZodNever: () => ZodNever4, + ZodNever: () => ZodNever, ZodNanoID: () => ZodNanoID, - ZodNaN: () => ZodNaN4, - ZodMap: () => ZodMap4, + ZodNaN: () => ZodNaN, + ZodMap: () => ZodMap, ZodMAC: () => ZodMAC, - ZodLiteral: () => ZodLiteral4, - ZodLazy: () => ZodLazy4, + ZodLiteral: () => ZodLiteral, + ZodLazy: () => ZodLazy, ZodKSUID: () => ZodKSUID, ZodJWT: () => ZodJWT, - ZodIntersection: () => ZodIntersection4, + ZodIntersection: () => ZodIntersection, ZodIPv6: () => ZodIPv6, ZodIPv4: () => ZodIPv4, ZodGUID: () => ZodGUID, - ZodFunction: () => ZodFunction4, + ZodFunction: () => ZodFunction, ZodFile: () => ZodFile, ZodExactOptional: () => ZodExactOptional, - ZodEnum: () => ZodEnum4, + ZodEnum: () => ZodEnum, ZodEmoji: () => ZodEmoji, ZodEmail: () => ZodEmail, ZodE164: () => ZodE164, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion4, - ZodDefault: () => ZodDefault4, - ZodDate: () => ZodDate4, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodDefault: () => ZodDefault, + ZodDate: () => ZodDate, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodCustom: () => ZodCustom, ZodCodec: () => ZodCodec, - ZodCatch: () => ZodCatch4, + ZodCatch: () => ZodCatch, ZodCUID2: () => ZodCUID2, ZodCUID: () => ZodCUID, ZodCIDRv6: () => ZodCIDRv6, ZodCIDRv4: () => ZodCIDRv4, - ZodBoolean: () => ZodBoolean4, + ZodBoolean: () => ZodBoolean, ZodBigIntFormat: () => ZodBigIntFormat, - ZodBigInt: () => ZodBigInt4, + ZodBigInt: () => ZodBigInt, ZodBase64URL: () => ZodBase64URL, ZodBase64: () => ZodBase64, - ZodArray: () => ZodArray4, - ZodAny: () => ZodAny4 + ZodArray: () => ZodArray, + ZodAny: () => ZodAny }); function _installLazyMethods(inst, group, methods) { const proto = Object.getPrototypeOf(inst); @@ -12583,7 +12583,7 @@ function _installLazyMethods(inst, group, methods) { } } function string2(params) { - return _string(ZodString4, params); + return _string(ZodString, params); } function email2(params) { return _email(ZodEmail, params); @@ -12679,7 +12679,7 @@ function hash(alg, params) { return _stringFormat(ZodCustomStringFormat, format, regex, params); } function number2(params) { - return _number(ZodNumber4, params); + return _number(ZodNumber, params); } function int(params) { return _int(ZodNumberFormat, params); @@ -12697,10 +12697,10 @@ function uint32(params) { return _uint32(ZodNumberFormat, params); } function boolean2(params) { - return _boolean(ZodBoolean4, params); + return _boolean(ZodBoolean, params); } function bigint2(params) { - return _bigint(ZodBigInt4, params); + return _bigint(ZodBigInt, params); } function int64(params) { return _int64(ZodBigIntFormat, params); @@ -12709,31 +12709,31 @@ function uint64(params) { return _uint64(ZodBigIntFormat, params); } function symbol(params) { - return _symbol(ZodSymbol4, params); + return _symbol(ZodSymbol, params); } function _undefined3(params) { - return _undefined2(ZodUndefined4, params); + return _undefined2(ZodUndefined, params); } function _null3(params) { - return _null2(ZodNull4, params); + return _null2(ZodNull, params); } function any() { - return _any(ZodAny4); + return _any(ZodAny); } function unknown() { - return _unknown(ZodUnknown4); + return _unknown(ZodUnknown); } function never(params) { - return _never(ZodNever4, params); + return _never(ZodNever, params); } function _void2(params) { - return _void(ZodVoid4, params); + return _void(ZodVoid, params); } function date3(params) { - return _date(ZodDate4, params); + return _date(ZodDate, params); } function array(element, params) { - return _array(ZodArray4, element, params); + return _array(ZodArray, element, params); } function keyof(schema) { const shape = schema._zod.def.shape; @@ -12745,10 +12745,10 @@ function object(shape, params) { shape: shape ?? {}, ...exports_util.normalizeParams(params) }; - return new ZodObject4(def); + return new ZodObject(def); } function strictObject(shape, params) { - return new ZodObject4({ + return new ZodObject({ type: "object", shape, catchall: never(), @@ -12756,7 +12756,7 @@ function strictObject(shape, params) { }); } function looseObject(shape, params) { - return new ZodObject4({ + return new ZodObject({ type: "object", shape, catchall: unknown(), @@ -12764,7 +12764,7 @@ function looseObject(shape, params) { }); } function union(options, params) { - return new ZodUnion4({ + return new ZodUnion({ type: "union", options, ...exports_util.normalizeParams(params) @@ -12779,7 +12779,7 @@ function xor(options, params) { }); } function discriminatedUnion(discriminator, options, params) { - return new ZodDiscriminatedUnion4({ + return new ZodDiscriminatedUnion({ type: "union", options, discriminator, @@ -12787,7 +12787,7 @@ function discriminatedUnion(discriminator, options, params) { }); } function intersection(left, right) { - return new ZodIntersection4({ + return new ZodIntersection({ type: "intersection", left, right @@ -12797,7 +12797,7 @@ function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple4({ + return new ZodTuple({ type: "tuple", items, rest, @@ -12806,14 +12806,14 @@ function tuple(items, _paramsOrRest, _params) { } function record(keyType, valueType, params) { if (!valueType || !valueType._zod) { - return new ZodRecord4({ + return new ZodRecord({ type: "record", keyType: string2(), valueType: keyType, ...exports_util.normalizeParams(valueType) }); } - return new ZodRecord4({ + return new ZodRecord({ type: "record", keyType, valueType, @@ -12823,7 +12823,7 @@ function record(keyType, valueType, params) { function partialRecord(keyType, valueType, params) { const k = clone(keyType); k._zod.values = undefined; - return new ZodRecord4({ + return new ZodRecord({ type: "record", keyType: k, valueType, @@ -12831,7 +12831,7 @@ function partialRecord(keyType, valueType, params) { }); } function looseRecord(keyType, valueType, params) { - return new ZodRecord4({ + return new ZodRecord({ type: "record", keyType, valueType, @@ -12840,7 +12840,7 @@ function looseRecord(keyType, valueType, params) { }); } function map(keyType, valueType, params) { - return new ZodMap4({ + return new ZodMap({ type: "map", keyType, valueType, @@ -12848,7 +12848,7 @@ function map(keyType, valueType, params) { }); } function set(valueType, params) { - return new ZodSet4({ + return new ZodSet({ type: "set", valueType, ...exports_util.normalizeParams(params) @@ -12856,21 +12856,21 @@ function set(valueType, params) { } function _enum2(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum4({ + return new ZodEnum({ type: "enum", entries, ...exports_util.normalizeParams(params) }); } function nativeEnum(entries, params) { - return new ZodEnum4({ + return new ZodEnum({ type: "enum", entries, ...exports_util.normalizeParams(params) }); } function literal(value, params) { - return new ZodLiteral4({ + return new ZodLiteral({ type: "literal", values: Array.isArray(value) ? value : [value], ...exports_util.normalizeParams(params) @@ -12886,7 +12886,7 @@ function transform(fn) { }); } function optional(innerType) { - return new ZodOptional4({ + return new ZodOptional({ type: "optional", innerType }); @@ -12898,7 +12898,7 @@ function exactOptional(innerType) { }); } function nullable(innerType) { - return new ZodNullable4({ + return new ZodNullable({ type: "nullable", innerType }); @@ -12907,7 +12907,7 @@ function nullish2(innerType) { return optional(nullable(innerType)); } function _default2(innerType, defaultValue) { - return new ZodDefault4({ + return new ZodDefault({ type: "default", innerType, get defaultValue() { @@ -12938,14 +12938,14 @@ function success(innerType) { }); } function _catch2(innerType, catchValue) { - return new ZodCatch4({ + return new ZodCatch({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } function nan(params) { - return _nan(ZodNaN4, params); + return _nan(ZodNaN, params); } function pipe(in_, out) { return new ZodPipe({ @@ -12974,7 +12974,7 @@ function invertCodec(codec2) { }); } function readonly(innerType) { - return new ZodReadonly4({ + return new ZodReadonly({ type: "readonly", innerType }); @@ -12987,19 +12987,19 @@ function templateLiteral(parts, params) { }); } function lazy(getter) { - return new ZodLazy4({ + return new ZodLazy({ type: "lazy", getter }); } function promise(innerType) { - return new ZodPromise4({ + return new ZodPromise({ type: "promise", innerType }); } function _function(params) { - return new ZodFunction4({ + return new ZodFunction({ type: "function", input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), output: params?.output ?? unknown() @@ -13012,7 +13012,7 @@ function check(fn) { ch._zod.check = fn; return ch; } -function custom4(fn, _params) { +function custom(fn, _params) { return _custom(ZodCustom, fn ?? (() => true), _params); } function refine(fn, _params = {}) { @@ -13056,10 +13056,10 @@ function preprocess(fn, schema) { out: schema }); } -var _installedGroups, ZodType4, _ZodString, ZodString4, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber4, ZodNumberFormat, ZodBoolean4, ZodBigInt4, ZodBigIntFormat, ZodSymbol4, ZodUndefined4, ZodNull4, ZodAny4, ZodUnknown4, ZodNever4, ZodVoid4, ZodDate4, ZodArray4, ZodObject4, ZodUnion4, ZodXor, ZodDiscriminatedUnion4, ZodIntersection4, ZodTuple4, ZodRecord4, ZodMap4, ZodSet4, ZodEnum4, ZodLiteral4, ZodFile, ZodTransform, ZodOptional4, ZodExactOptional, ZodNullable4, ZodDefault4, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch4, ZodNaN4, ZodPipe, ZodCodec, ZodPreprocess, ZodReadonly4, ZodTemplateLiteral, ZodLazy4, ZodPromise4, ZodFunction4, ZodCustom, describe2, meta2, stringbool = (...args) => _stringbool({ +var _installedGroups, ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodXor, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodCodec, ZodPreprocess, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodFunction, ZodCustom, describe2, meta2, stringbool = (...args) => _stringbool({ Codec: ZodCodec, - Boolean: ZodBoolean4, - String: ZodString4 + Boolean: ZodBoolean, + String: ZodString }, ...args); var init_schemas2 = __esm(() => { init_core2(); @@ -13070,7 +13070,7 @@ var init_schemas2 = __esm(() => { init_iso(); init_parse2(); _installedGroups = /* @__PURE__ */ new WeakMap; - ZodType4 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); Object.assign(inst["~standard"], { jsonSchema: { @@ -13201,7 +13201,7 @@ var init_schemas2 = __esm(() => { }); _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { $ZodString.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); const bag = inst._zod.bag; inst.format = bag.format ?? null; @@ -13255,7 +13255,7 @@ var init_schemas2 = __esm(() => { } }); }); - ZodString4 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { + ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); inst.email = (params) => inst.check(_email(ZodEmail, params)); @@ -13374,9 +13374,9 @@ var init_schemas2 = __esm(() => { $ZodCustomStringFormat.init(inst, def); ZodStringFormat.init(inst, def); }); - ZodNumber4 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { $ZodNumber.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); _installLazyMethods(inst, "ZodNumber", { gt(value, params) { @@ -13434,16 +13434,16 @@ var init_schemas2 = __esm(() => { }); ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); - ZodNumber4.init(inst, def); + ZodNumber.init(inst, def); }); - ZodBoolean4 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); }); - ZodBigInt4 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { + ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { $ZodBigInt.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); @@ -13465,46 +13465,46 @@ var init_schemas2 = __esm(() => { }); ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { $ZodBigIntFormat.init(inst, def); - ZodBigInt4.init(inst, def); + ZodBigInt.init(inst, def); }); - ZodSymbol4 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { + ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { $ZodSymbol.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); }); - ZodUndefined4 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { + ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { $ZodUndefined.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); }); - ZodNull4 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); }); - ZodAny4 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { + ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { $ZodAny.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); }); - ZodUnknown4 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); }); - ZodNever4 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); }); - ZodVoid4 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { + ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { $ZodVoid.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); }); - ZodDate4 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { + ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { $ZodDate.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); inst.min = (value, params) => inst.check(_gte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); @@ -13512,9 +13512,9 @@ var init_schemas2 = __esm(() => { inst.minDate = c.minimum ? new Date(c.minimum) : null; inst.maxDate = c.maximum ? new Date(c.maximum) : null; }); - ZodArray4 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); inst.element = def.element; _installLazyMethods(inst, "ZodArray", { @@ -13535,9 +13535,9 @@ var init_schemas2 = __esm(() => { } }); }); - ZodObject4 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { $ZodObjectJIT.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); exports_util.defineLazy(inst, "shape", () => { return def.shape; @@ -13577,53 +13577,53 @@ var init_schemas2 = __esm(() => { return exports_util.omit(this, mask); }, partial(...args) { - return exports_util.partial(ZodOptional4, this, args[0]); + return exports_util.partial(ZodOptional, this, args[0]); }, required(...args) { return exports_util.required(ZodNonOptional, this, args[0]); } }); }); - ZodUnion4 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); inst.options = def.options; }); ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { - ZodUnion4.init(inst, def); + ZodUnion.init(inst, def); $ZodXor.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); inst.options = def.options; }); - ZodDiscriminatedUnion4 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion4.init(inst, def); + ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); $ZodDiscriminatedUnion.init(inst, def); }); - ZodIntersection4 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); }); - ZodTuple4 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { $ZodTuple.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); inst.rest = (rest) => inst.clone({ ...inst._zod.def, rest }); }); - ZodRecord4 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); inst.keyType = def.keyType; inst.valueType = def.valueType; }); - ZodMap4 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { $ZodMap.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); inst.keyType = def.keyType; inst.valueType = def.valueType; @@ -13632,18 +13632,18 @@ var init_schemas2 = __esm(() => { inst.max = (...args) => inst.check(_maxSize(...args)); inst.size = (...args) => inst.check(_size(...args)); }); - ZodSet4 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { $ZodSet.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); inst.min = (...args) => inst.check(_minSize(...args)); inst.nonempty = (params) => inst.check(_minSize(1, params)); inst.max = (...args) => inst.check(_maxSize(...args)); inst.size = (...args) => inst.check(_size(...args)); }); - ZodEnum4 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params); inst.enum = def.entries; inst.options = Object.values(def.entries); @@ -13656,7 +13656,7 @@ var init_schemas2 = __esm(() => { } else throw new Error(`Key ${value} not found in enum`); } - return new ZodEnum4({ + return new ZodEnum({ ...def, checks: [], ...exports_util.normalizeParams(params), @@ -13671,7 +13671,7 @@ var init_schemas2 = __esm(() => { } else throw new Error(`Key ${value} not found in enum`); } - return new ZodEnum4({ + return new ZodEnum({ ...def, checks: [], ...exports_util.normalizeParams(params), @@ -13679,9 +13679,9 @@ var init_schemas2 = __esm(() => { }); }; }); - ZodLiteral4 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params); inst.values = new Set(def.values); Object.defineProperty(inst, "value", { @@ -13695,7 +13695,7 @@ var init_schemas2 = __esm(() => { }); ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { $ZodFile.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); inst.min = (size, params) => inst.check(_minSize(size, params)); inst.max = (size, params) => inst.check(_maxSize(size, params)); @@ -13703,7 +13703,7 @@ var init_schemas2 = __esm(() => { }); ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); inst._zod.parse = (payload, _ctx) => { if (_ctx.direction === "backward") { @@ -13735,64 +13735,64 @@ var init_schemas2 = __esm(() => { return payload; }; }); - ZodOptional4 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { $ZodExactOptional.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); - ZodNullable4 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); - ZodDefault4 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { $ZodSuccess.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); - ZodCatch4 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); - ZodNaN4 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { + ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { $ZodNaN.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); }); ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); inst.in = def.in; inst.out = def.out; @@ -13805,37 +13805,37 @@ var init_schemas2 = __esm(() => { ZodPipe.init(inst, def); $ZodPreprocess.init(inst, def); }); - ZodReadonly4 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { $ZodTemplateLiteral.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); }); - ZodLazy4 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { + ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { $ZodLazy.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.getter(); }); - ZodPromise4 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { + ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { $ZodPromise.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); - ZodFunction4 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { + ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { $ZodFunction.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); }); ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); - ZodType4.init(inst, def); + ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); }); describe2 = describe; @@ -13843,18 +13843,18 @@ var init_schemas2 = __esm(() => { }); // node_modules/zod/v4/classic/compat.js -function setErrorMap4(map2) { +function setErrorMap(map2) { config({ customError: map2 }); } -function getErrorMap4() { +function getErrorMap() { return config().customError; } -var ZodIssueCode4, ZodFirstPartyTypeKind4; +var ZodIssueCode, ZodFirstPartyTypeKind; var init_compat = __esm(() => { init_core2(); - ZodIssueCode4 = { + ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", @@ -13867,7 +13867,7 @@ var init_compat = __esm(() => { invalid_value: "invalid_value", custom: "custom" }; - (function(ZodFirstPartyTypeKind5) {})(ZodFirstPartyTypeKind4 || (ZodFirstPartyTypeKind4 = {})); + (function(ZodFirstPartyTypeKind2) {})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); }); // node_modules/zod/v4/classic/from-json-schema.js @@ -14355,19 +14355,19 @@ __export(exports_coerce, { bigint: () => bigint3 }); function string3(params) { - return _coercedString(ZodString4, params); + return _coercedString(ZodString, params); } function number3(params) { - return _coercedNumber(ZodNumber4, params); + return _coercedNumber(ZodNumber, params); } function boolean3(params) { - return _coercedBoolean(ZodBoolean4, params); + return _coercedBoolean(ZodBoolean, params); } function bigint3(params) { - return _coercedBigint(ZodBigInt4, params); + return _coercedBigint(ZodBigInt, params); } function date4(params) { - return _coercedDate(ZodDate4, params); + return _coercedDate(ZodDate, params); } var init_coerce = __esm(() => { init_core2(); @@ -14375,8 +14375,8 @@ var init_coerce = __esm(() => { }); // node_modules/zod/v4/classic/external.js -var exports_external4 = {}; -__export(exports_external4, { +var exports_external = {}; +__export(exports_external, { xor: () => xor, xid: () => xid2, void: () => _void2, @@ -14411,7 +14411,7 @@ __export(exports_external4, { startsWith: () => _startsWith, slugify: () => _slugify, size: () => _size, - setErrorMap: () => setErrorMap4, + setErrorMap: () => setErrorMap, set: () => set, safeParseAsync: () => safeParseAsync2, safeParse: () => safeParse2, @@ -14491,7 +14491,7 @@ __export(exports_external4, { gte: () => _gte, gt: () => _gt, globalRegistry: () => globalRegistry, - getErrorMap: () => getErrorMap4, + getErrorMap: () => getErrorMap, function: () => _function, fromJSONSchema: () => fromJSONSchema, formatError: () => formatError, @@ -14512,7 +14512,7 @@ __export(exports_external4, { decodeAsync: () => decodeAsync2, decode: () => decode2, date: () => date3, - custom: () => custom4, + custom: () => custom, cuid2: () => cuid22, cuid: () => cuid3, core: () => exports_core2, @@ -14535,47 +14535,47 @@ __export(exports_external4, { _ZodString: () => _ZodString, ZodXor: () => ZodXor, ZodXID: () => ZodXID, - ZodVoid: () => ZodVoid4, - ZodUnknown: () => ZodUnknown4, - ZodUnion: () => ZodUnion4, - ZodUndefined: () => ZodUndefined4, + ZodVoid: () => ZodVoid, + ZodUnknown: () => ZodUnknown, + ZodUnion: () => ZodUnion, + ZodUndefined: () => ZodUndefined, ZodUUID: () => ZodUUID, ZodURL: () => ZodURL, ZodULID: () => ZodULID, - ZodType: () => ZodType4, - ZodTuple: () => ZodTuple4, + ZodType: () => ZodType, + ZodTuple: () => ZodTuple, ZodTransform: () => ZodTransform, ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodSymbol: () => ZodSymbol4, + ZodSymbol: () => ZodSymbol, ZodSuccess: () => ZodSuccess, ZodStringFormat: () => ZodStringFormat, - ZodString: () => ZodString4, - ZodSet: () => ZodSet4, - ZodRecord: () => ZodRecord4, + ZodString: () => ZodString, + ZodSet: () => ZodSet, + ZodRecord: () => ZodRecord, ZodRealError: () => ZodRealError, - ZodReadonly: () => ZodReadonly4, - ZodPromise: () => ZodPromise4, + ZodReadonly: () => ZodReadonly, + ZodPromise: () => ZodPromise, ZodPreprocess: () => ZodPreprocess, ZodPrefault: () => ZodPrefault, ZodPipe: () => ZodPipe, - ZodOptional: () => ZodOptional4, - ZodObject: () => ZodObject4, + ZodOptional: () => ZodOptional, + ZodObject: () => ZodObject, ZodNumberFormat: () => ZodNumberFormat, - ZodNumber: () => ZodNumber4, - ZodNullable: () => ZodNullable4, - ZodNull: () => ZodNull4, + ZodNumber: () => ZodNumber, + ZodNullable: () => ZodNullable, + ZodNull: () => ZodNull, ZodNonOptional: () => ZodNonOptional, - ZodNever: () => ZodNever4, + ZodNever: () => ZodNever, ZodNanoID: () => ZodNanoID, - ZodNaN: () => ZodNaN4, - ZodMap: () => ZodMap4, + ZodNaN: () => ZodNaN, + ZodMap: () => ZodMap, ZodMAC: () => ZodMAC, - ZodLiteral: () => ZodLiteral4, - ZodLazy: () => ZodLazy4, + ZodLiteral: () => ZodLiteral, + ZodLazy: () => ZodLazy, ZodKSUID: () => ZodKSUID, ZodJWT: () => ZodJWT, - ZodIssueCode: () => ZodIssueCode4, - ZodIntersection: () => ZodIntersection4, + ZodIssueCode: () => ZodIssueCode, + ZodIntersection: () => ZodIntersection, ZodISOTime: () => ZodISOTime, ZodISODuration: () => ZodISODuration, ZodISODateTime: () => ZodISODateTime, @@ -14583,35 +14583,35 @@ __export(exports_external4, { ZodIPv6: () => ZodIPv6, ZodIPv4: () => ZodIPv4, ZodGUID: () => ZodGUID, - ZodFunction: () => ZodFunction4, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind4, + ZodFunction: () => ZodFunction, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFile: () => ZodFile, ZodExactOptional: () => ZodExactOptional, - ZodError: () => ZodError4, - ZodEnum: () => ZodEnum4, + ZodError: () => ZodError, + ZodEnum: () => ZodEnum, ZodEmoji: () => ZodEmoji, ZodEmail: () => ZodEmail, ZodE164: () => ZodE164, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion4, - ZodDefault: () => ZodDefault4, - ZodDate: () => ZodDate4, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodDefault: () => ZodDefault, + ZodDate: () => ZodDate, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodCustom: () => ZodCustom, ZodCodec: () => ZodCodec, - ZodCatch: () => ZodCatch4, + ZodCatch: () => ZodCatch, ZodCUID2: () => ZodCUID2, ZodCUID: () => ZodCUID, ZodCIDRv6: () => ZodCIDRv6, ZodCIDRv4: () => ZodCIDRv4, - ZodBoolean: () => ZodBoolean4, + ZodBoolean: () => ZodBoolean, ZodBigIntFormat: () => ZodBigIntFormat, - ZodBigInt: () => ZodBigInt4, + ZodBigInt: () => ZodBigInt, ZodBase64URL: () => ZodBase64URL, ZodBase64: () => ZodBase64, - ZodArray: () => ZodArray4, - ZodAny: () => ZodAny4, + ZodArray: () => ZodArray, + ZodAny: () => ZodAny, TimePrecision: () => TimePrecision, - NEVER: () => NEVER4, + NEVER: () => NEVER, $output: () => $output, $input: () => $input, $brand: () => $brand @@ -14632,13 +14632,13 @@ var init_external = __esm(() => { init_errors2(); init_parse2(); init_compat(); - config(en_default4()); + config(en_default()); }); // node_modules/zod/index.js var exports_zod = {}; __export(exports_zod, { - z: () => exports_external4, + z: () => exports_external, xor: () => xor, xid: () => xid2, void: () => _void2, @@ -14673,7 +14673,7 @@ __export(exports_zod, { startsWith: () => _startsWith, slugify: () => _slugify, size: () => _size, - setErrorMap: () => setErrorMap4, + setErrorMap: () => setErrorMap, set: () => set, safeParseAsync: () => safeParseAsync2, safeParse: () => safeParse2, @@ -14753,7 +14753,7 @@ __export(exports_zod, { gte: () => _gte, gt: () => _gt, globalRegistry: () => globalRegistry, - getErrorMap: () => getErrorMap4, + getErrorMap: () => getErrorMap, function: () => _function, fromJSONSchema: () => fromJSONSchema, formatError: () => formatError, @@ -14775,7 +14775,7 @@ __export(exports_zod, { decodeAsync: () => decodeAsync2, decode: () => decode2, date: () => date3, - custom: () => custom4, + custom: () => custom, cuid2: () => cuid22, cuid: () => cuid3, core: () => exports_core2, @@ -14798,47 +14798,47 @@ __export(exports_zod, { _ZodString: () => _ZodString, ZodXor: () => ZodXor, ZodXID: () => ZodXID, - ZodVoid: () => ZodVoid4, - ZodUnknown: () => ZodUnknown4, - ZodUnion: () => ZodUnion4, - ZodUndefined: () => ZodUndefined4, + ZodVoid: () => ZodVoid, + ZodUnknown: () => ZodUnknown, + ZodUnion: () => ZodUnion, + ZodUndefined: () => ZodUndefined, ZodUUID: () => ZodUUID, ZodURL: () => ZodURL, ZodULID: () => ZodULID, - ZodType: () => ZodType4, - ZodTuple: () => ZodTuple4, + ZodType: () => ZodType, + ZodTuple: () => ZodTuple, ZodTransform: () => ZodTransform, ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodSymbol: () => ZodSymbol4, + ZodSymbol: () => ZodSymbol, ZodSuccess: () => ZodSuccess, ZodStringFormat: () => ZodStringFormat, - ZodString: () => ZodString4, - ZodSet: () => ZodSet4, - ZodRecord: () => ZodRecord4, + ZodString: () => ZodString, + ZodSet: () => ZodSet, + ZodRecord: () => ZodRecord, ZodRealError: () => ZodRealError, - ZodReadonly: () => ZodReadonly4, - ZodPromise: () => ZodPromise4, + ZodReadonly: () => ZodReadonly, + ZodPromise: () => ZodPromise, ZodPreprocess: () => ZodPreprocess, ZodPrefault: () => ZodPrefault, ZodPipe: () => ZodPipe, - ZodOptional: () => ZodOptional4, - ZodObject: () => ZodObject4, + ZodOptional: () => ZodOptional, + ZodObject: () => ZodObject, ZodNumberFormat: () => ZodNumberFormat, - ZodNumber: () => ZodNumber4, - ZodNullable: () => ZodNullable4, - ZodNull: () => ZodNull4, + ZodNumber: () => ZodNumber, + ZodNullable: () => ZodNullable, + ZodNull: () => ZodNull, ZodNonOptional: () => ZodNonOptional, - ZodNever: () => ZodNever4, + ZodNever: () => ZodNever, ZodNanoID: () => ZodNanoID, - ZodNaN: () => ZodNaN4, - ZodMap: () => ZodMap4, + ZodNaN: () => ZodNaN, + ZodMap: () => ZodMap, ZodMAC: () => ZodMAC, - ZodLiteral: () => ZodLiteral4, - ZodLazy: () => ZodLazy4, + ZodLiteral: () => ZodLiteral, + ZodLazy: () => ZodLazy, ZodKSUID: () => ZodKSUID, ZodJWT: () => ZodJWT, - ZodIssueCode: () => ZodIssueCode4, - ZodIntersection: () => ZodIntersection4, + ZodIssueCode: () => ZodIssueCode, + ZodIntersection: () => ZodIntersection, ZodISOTime: () => ZodISOTime, ZodISODuration: () => ZodISODuration, ZodISODateTime: () => ZodISODateTime, @@ -14846,35 +14846,35 @@ __export(exports_zod, { ZodIPv6: () => ZodIPv6, ZodIPv4: () => ZodIPv4, ZodGUID: () => ZodGUID, - ZodFunction: () => ZodFunction4, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind4, + ZodFunction: () => ZodFunction, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFile: () => ZodFile, ZodExactOptional: () => ZodExactOptional, - ZodError: () => ZodError4, - ZodEnum: () => ZodEnum4, + ZodError: () => ZodError, + ZodEnum: () => ZodEnum, ZodEmoji: () => ZodEmoji, ZodEmail: () => ZodEmail, ZodE164: () => ZodE164, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion4, - ZodDefault: () => ZodDefault4, - ZodDate: () => ZodDate4, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodDefault: () => ZodDefault, + ZodDate: () => ZodDate, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodCustom: () => ZodCustom, ZodCodec: () => ZodCodec, - ZodCatch: () => ZodCatch4, + ZodCatch: () => ZodCatch, ZodCUID2: () => ZodCUID2, ZodCUID: () => ZodCUID, ZodCIDRv6: () => ZodCIDRv6, ZodCIDRv4: () => ZodCIDRv4, - ZodBoolean: () => ZodBoolean4, + ZodBoolean: () => ZodBoolean, ZodBigIntFormat: () => ZodBigIntFormat, - ZodBigInt: () => ZodBigInt4, + ZodBigInt: () => ZodBigInt, ZodBase64URL: () => ZodBase64URL, ZodBase64: () => ZodBase64, - ZodArray: () => ZodArray4, - ZodAny: () => ZodAny4, + ZodArray: () => ZodArray, + ZodAny: () => ZodAny, TimePrecision: () => TimePrecision, - NEVER: () => NEVER4, + NEVER: () => NEVER, $output: () => $output, $input: () => $input, $brand: () => $brand @@ -14883,7 +14883,7 @@ var zod_default; var init_zod = __esm(() => { init_external(); init_external(); - zod_default = exports_external4; + zod_default = exports_external; }); // src/knowledge-db.ts @@ -15069,24519 +15069,8582 @@ function writeKnowledgeConfig(path, config) { } // node_modules/@hasna/contracts/dist/client/storage.js -var __defProp2 = Object.defineProperty; -var __returnValue2 = (v) => v; -function __exportSetter2(name, newValue) { - this[name] = __returnValue2.bind(null, newValue); +import { isIP } from "net"; +import { readFileSync as readFileSync2, statSync } from "fs"; +import { join as join2 } from "path"; +function envToken(name) { + return name.toUpperCase().replace(/-/g, "_"); } -var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter2.bind(all, name) - }); -}; -var exports_external = {}; -__export2(exports_external, { - void: () => voidType, - util: () => util, - unknown: () => unknownType, - union: () => unionType, - undefined: () => undefinedType, - tuple: () => tupleType, - transformer: () => effectsType, - symbol: () => symbolType, - string: () => stringType, - strictObject: () => strictObjectType, - setErrorMap: () => setErrorMap, - set: () => setType, - record: () => recordType, - quotelessJson: () => quotelessJson, - promise: () => promiseType, - preprocess: () => preprocessType, - pipeline: () => pipelineType, - ostring: () => ostring, - optional: () => optionalType, - onumber: () => onumber, - oboolean: () => oboolean, - objectUtil: () => objectUtil, - object: () => objectType, - number: () => numberType, - nullable: () => nullableType, - null: () => nullType, - never: () => neverType, - nativeEnum: () => nativeEnumType, - nan: () => nanType, - map: () => mapType, - makeIssue: () => makeIssue, - literal: () => literalType, - lazy: () => lazyType, - late: () => late, - isValid: () => isValid, - isDirty: () => isDirty, - isAsync: () => isAsync, - isAborted: () => isAborted, - intersection: () => intersectionType, - instanceof: () => instanceOfType, - getParsedType: () => getParsedType, - getErrorMap: () => getErrorMap, - function: () => functionType, - enum: () => enumType, - effect: () => effectsType, - discriminatedUnion: () => discriminatedUnionType, - defaultErrorMap: () => en_default, - datetimeRegex: () => datetimeRegex, - date: () => dateType, - custom: () => custom, - coerce: () => coerce, - boolean: () => booleanType, - bigint: () => bigIntType, - array: () => arrayType, - any: () => anyType, - addIssueToContext: () => addIssueToContext, - ZodVoid: () => ZodVoid, - ZodUnknown: () => ZodUnknown, - ZodUnion: () => ZodUnion, - ZodUndefined: () => ZodUndefined, - ZodType: () => ZodType, - ZodTuple: () => ZodTuple, - ZodTransformer: () => ZodEffects, - ZodSymbol: () => ZodSymbol, - ZodString: () => ZodString, - ZodSet: () => ZodSet, - ZodSchema: () => ZodType, - ZodRecord: () => ZodRecord, - ZodReadonly: () => ZodReadonly, - ZodPromise: () => ZodPromise, - ZodPipeline: () => ZodPipeline, - ZodParsedType: () => ZodParsedType, - ZodOptional: () => ZodOptional, - ZodObject: () => ZodObject, - ZodNumber: () => ZodNumber, - ZodNullable: () => ZodNullable, - ZodNull: () => ZodNull, - ZodNever: () => ZodNever, - ZodNativeEnum: () => ZodNativeEnum, - ZodNaN: () => ZodNaN, - ZodMap: () => ZodMap, - ZodLiteral: () => ZodLiteral, - ZodLazy: () => ZodLazy, - ZodIssueCode: () => ZodIssueCode, - ZodIntersection: () => ZodIntersection, - ZodFunction: () => ZodFunction, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodError: () => ZodError, - ZodEnum: () => ZodEnum, - ZodEffects: () => ZodEffects, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodDefault: () => ZodDefault, - ZodDate: () => ZodDate, - ZodCatch: () => ZodCatch, - ZodBranded: () => ZodBranded, - ZodBoolean: () => ZodBoolean, - ZodBigInt: () => ZodBigInt, - ZodArray: () => ZodArray, - ZodAny: () => ZodAny, - Schema: () => ZodType, - ParseStatus: () => ParseStatus, - OK: () => OK, - NEVER: () => NEVER, - INVALID: () => INVALID, - EMPTY_PATH: () => EMPTY_PATH, - DIRTY: () => DIRTY, - BRAND: () => BRAND -}); -var util; -(function(util2) { - util2.assertEqual = (_) => {}; - function assertIs(_arg) {} - util2.assertIs = assertIs; - function assertNever(_x) { - throw new Error; - } - util2.assertNever = assertNever; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; +function normalizeStorageMode(value) { + const normalized = value.trim().toLowerCase().replace(/-/g, "_"); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); +} +function clientTransportEnvKeys(name) { + const envSegment = envToken(name); + return { + modeKeys: [ + `HASNA_${envSegment}_STORAGE_MODE`, + `HASNA_${envSegment}_MODE`, + `${envSegment}_STORAGE_MODE`, + `${envSegment}_MODE` + ], + apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], + apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; +} +function credentialOverrideEnvKey(name) { + return `HASNA_${envToken(name)}_API_KEY_OVERRIDE`; +} +var CREDENTIAL_PROFILE_ENV_KEY = "HASNA_PROFILE"; + +class CredentialResolutionError extends Error { + appName; + attempted; + constructor(appName, message, attempted) { + super(message); + this.name = "CredentialResolutionError"; + this.appName = appName; + this.attempted = attempted; + } +} +var HASNA_STATE_DIR = ".hasna"; +var FLEET_CREDENTIAL_DIR = "cloud"; +var CONFIG_DIR = ".config"; +var CONFIG_NAMESPACE = "hasna"; +var MAX_CREDENTIAL_FILE_BYTES = 64 * 1024; +var SAFE_APP_SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/; +var SAFE_PROFILE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/; +var ILLEGAL_IN_HEADER_VALUE = /[^\t\x20-\x7e]/; +function homeDir(env) { + const home = env.HOME?.trim(); + return home ? home : null; +} +function credentialDiskSources(name, env) { + return profileDiskSources(name, env, null); +} +function profileDiskSources(name, env, profile) { + const home = homeDir(env); + if (!home || !SAFE_APP_SLUG.test(name)) + return []; + const stem = profile ? `${name}.${profile}` : name; + const configStem = profile ? `${name}-${profile}` : name; + return [ + join2(home, HASNA_STATE_DIR, FLEET_CREDENTIAL_DIR, `${stem}.env`), + join2(home, CONFIG_DIR, CONFIG_NAMESPACE, `${configStem}-cloud.env`) + ]; +} +function parseEnvFile(text) { + const values = new Map; + for (const rawLine of text.split(/\r?\n/)) { + const line = rawLine.trim(); + if (line.length === 0 || line.startsWith("#")) + continue; + const withoutExport = line.startsWith("export ") ? line.slice("export ".length).trim() : line; + const equals = withoutExport.indexOf("="); + if (equals <= 0) + continue; + const key = withoutExport.slice(0, equals).trim(); + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) + continue; + let value = withoutExport.slice(equals + 1).trim(); + const quote = value[0]; + if (quote === '"' || quote === "'") { + if (value.length < 2 || !value.endsWith(quote)) + continue; + value = value.slice(1, -1); } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; + if (value.length === 0) + continue; + values.set(key, value); + } + return values; +} +function readCredentialFile(path, apiKeyKeys) { + let text; + try { + const stats = statSync(path); + if (!stats.isFile() || stats.size > MAX_CREDENTIAL_FILE_BYTES) + return null; + text = readFileSync2(path, "utf8"); + } catch { + return null; + } + const values = parseEnvFile(text); + for (const key of apiKeyKeys) { + const value = values.get(key)?.trim(); + if (value) + return value; + } + return null; +} +function assertUsableCredential(appName, source, value) { + if (!ILLEGAL_IN_HEADER_VALUE.test(value)) + return; + throw new CredentialResolutionError(appName, `The credential from ${source} contains characters that cannot be sent in an HTTP header ` + `(a control character or non-ASCII byte). A file written with CR-only line endings is the usual ` + `cause. Rewrite that credential file with one LF-terminated KEY=value line. ` + `The value is not shown here, and is deliberately never logged.`, [source]); +} +var INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom"); +function sealCredential(fields) { + const { apiKey, ...visible } = fields; + const sealed = { ...visible }; + Object.defineProperty(sealed, "apiKey", { + value: apiKey, + enumerable: false, + writable: false, + configurable: false + }); + Object.defineProperty(sealed, INSPECT_CUSTOM, { + value: () => ({ ...visible, apiKey: "[redacted]" }), + enumerable: false, + writable: false, + configurable: false + }); + return sealed; +} +function explicitCredential(appName, apiKey) { + const source = "explicit apiKey option"; + assertUsableCredential(appName, source, apiKey); + return sealCredential({ + apiKey, + tier: "argument", + source, + deliberate: true, + deprecated: false, + diskCandidates: [], + warning: null + }); +} +function firstEnvValue(env, keys) { + for (const key of keys) { + const value = env[key]?.trim(); + if (value) + return { key, value }; + } + return null; +} +var DEPRECATION_REGISTRY = Symbol.for("hasna:contracts:credentialDeprecationNotices"); +function deprecationNotified() { + const host = globalThis; + const existing = host[DEPRECATION_REGISTRY]; + if (existing instanceof Set) + return existing; + const created = new Set; + host[DEPRECATION_REGISTRY] = created; + return created; +} +function defaultDeprecationSink(message) { + if (typeof process !== "undefined" && process.stderr) { + process.stderr.write(`${message} +`); + } +} +function resolveCredential(name, env, options = {}) { + const { apiKeyKeys } = clientTransportEnvKeys(name); + const diskPaths = credentialDiskSources(name, env); + const explicitKey = options.apiKey?.trim(); + if (explicitKey) { + assertUsableCredential(name, "the explicit apiKey argument", explicitKey); + return sealCredential({ + apiKey: explicitKey, + tier: "argument", + source: "explicit apiKey argument", + deliberate: true, + deprecated: false, + diskCandidates: diskPaths, + warning: null }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); + } + const overrideKeyName = credentialOverrideEnvKey(name); + const overrideRaw = env[overrideKeyName]; + if (overrideRaw !== undefined) { + const override = overrideRaw.trim(); + if (!override) { + throw new CredentialResolutionError(name, `${overrideKeyName} is set but empty. It is a deliberate override, so it is not resolved around: ` + `either give it a real key or unset it to fall back to the credential on disk.`, [overrideKeyName]); + } + assertUsableCredential(name, overrideKeyName, override); + return sealCredential({ + apiKey: override, + tier: "override", + source: overrideKeyName, + deliberate: true, + deprecated: false, + diskCandidates: diskPaths, + warning: null + }); + } + const profile = options.profile?.trim() || env[CREDENTIAL_PROFILE_ENV_KEY]?.trim(); + if (profile) { + const profileSource = options.profile?.trim() ? "explicit profile argument" : CREDENTIAL_PROFILE_ENV_KEY; + if (!SAFE_PROFILE.test(profile)) { + throw new CredentialResolutionError(name, `Profile name from ${profileSource} is not usable in a path. ` + `Use letters, digits, dot, dash, or underscore.`, [profileSource]); + } + const paths = profileDiskSources(name, env, profile); + for (const path of paths) { + const value = readCredentialFile(path, apiKeyKeys); + if (value) { + assertUsableCredential(name, path, value); + return sealCredential({ + apiKey: value, + tier: "profile", + source: path, + deliberate: true, + deprecated: false, + diskCandidates: paths, + warning: null + }); } } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + throw new CredentialResolutionError(name, `Profile '${profile}' (from ${profileSource}) has no ${apiKeyKeys[0]} for '${name}'. ` + `Looked in: ${paths.join(", ") || "<no HOME in this environment>"}. ` + `A profile names WHICH identity to use, so it is never resolved around \u2014 ` + `create the profile's credential file or unset ${CREDENTIAL_PROFILE_ENV_KEY}.`, paths); } - util2.joinValues = joinValues; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { + const diskHits = diskPaths.map((path) => ({ path, value: readCredentialFile(path, apiKeyKeys) })).filter((hit) => hit.value !== null); + if (diskHits.length > 0) { + const winner = diskHits[0]; + assertUsableCredential(name, winner.path, winner.value); + const divergentSources = [ + ...diskHits.slice(1).filter((hit) => hit.value !== winner.value).map((hit) => hit.path), + ...(() => { + const legacyHit = firstEnvValue(env, apiKeyKeys); + return legacyHit && legacyHit.value !== winner.value ? [legacyHit.key] : []; + })() + ]; + const warning = divergentSources.length > 0 ? `Credential sources disagree for '${name}': ${winner.path} and ` + `${divergentSources.join(", ")} hold different keys. ${winner.path} wins, because a file on ` + `disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 ` + `a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.` : null; + return sealCredential({ + apiKey: winner.value, + tier: "disk", + source: winner.path, + deliberate: false, + deprecated: false, + diskCandidates: diskPaths, + warning + }); + } + const legacy = firstEnvValue(env, apiKeyKeys); + if (legacy) { + assertUsableCredential(name, legacy.key, legacy.value); + const where = diskPaths.length > 0 ? `Put the current key in ${diskPaths[0]} \u2014 it is re-read on every call, so rotations take effect immediately.` : `This environment has no HOME, so no credential file could be consulted at all; the disk tier is ` + `unavailable here and this process will keep using the environment snapshot.`; + const message = `[${name}] DEPRECATED: the API key came from ${legacy.key} in this process's environment. ` + `Environment variables are a snapshot taken when this process started, so a shell that started ` + `before a key rotation keeps using the old key until it exits. ${where}`; + const sink = options.onDeprecation ?? defaultDeprecationSink; + const notified = deprecationNotified(); + if (!notified.has(name)) { + notified.add(name); + sink(message); + } + return sealCredential({ + apiKey: legacy.value, + tier: "legacy-env", + source: legacy.key, + deliberate: false, + deprecated: true, + diskCandidates: diskPaths, + warning: message + }); + } + return null; +} +var FLEET_API_DOMAIN_ENV_KEY = "HASNA_FLEET_API_DOMAIN"; +var NEUTRAL_FLEET_API_DOMAIN = "your-deployment.example"; +var ASCII_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/; +var DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/; +function isValidDnsDomain(value) { + if (value.length === 0 || value.length > 253 || ASCII_CONTROL_PATTERN.test(value) || /[^\x00-\x7f]/.test(value)) { + return false; + } + return value.split(".").every((label) => label.length <= 63 && !label.startsWith("xn--") && DNS_LABEL_PATTERN.test(label)); +} +function resolveFleetApiDomain(env) { + const raw = env[FLEET_API_DOMAIN_ENV_KEY]; + if (raw === undefined) { return { - ...first, - ...second + domain: NEUTRAL_FLEET_API_DOMAIN, + source: "default", + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} is not set; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` + }; + } + const configured = raw.trim().toLowerCase(); + if (ASCII_CONTROL_PATTERN.test(raw) || !isValidDnsDomain(configured)) { + return { + domain: NEUTRAL_FLEET_API_DOMAIN, + source: FLEET_API_DOMAIN_ENV_KEY, + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} is blank or invalid; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` }; + } + return { + domain: configured, + source: FLEET_API_DOMAIN_ENV_KEY, + misconfigured: false, + warning: null }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; +} +function validateAppSlug(name) { + if (name.length > 63 || !DNS_LABEL_PATTERN.test(name)) { + throw new Error("App name must be one lowercase DNS label."); } -}; -var ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; - -class ZodError extends Error { - get errors() { - return this.issues; + return name; +} +function composeCloudHostname(name, domain) { + const hostname = `${validateAppSlug(name)}.${domain}`; + if (!isValidDnsDomain(hostname)) { + throw new Error("Composed cloud hostname must be a valid DNS domain"); } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; + return hostname; +} +function resolveDefaultCloudBaseUrl(name, env) { + const appSlug = validateAppSlug(name); + const fleetDomain = resolveFleetApiDomain(env); + const configuredHostname = `${appSlug}.${fleetDomain.domain}`; + if (isValidDnsDomain(configuredHostname)) { + return { + baseUrl: `https://${configuredHostname}`, + source: fleetDomain.source, + misconfigured: fleetDomain.misconfigured, + warning: fleetDomain.warning }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); + } + const fallbackHostname = composeCloudHostname(appSlug, NEUTRAL_FLEET_API_DOMAIN); + return { + baseUrl: `https://${fallbackHostname}`, + source: fleetDomain.source, + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} cannot form a valid composed cloud hostname for app '${appSlug}'; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` + }; +} +function firstEnv2(env, keys, options = {}) { + for (const key of keys) { + const raw = env[key]; + const value = raw?.trim(); + if (value) + return { key, value: options.preserveRaw ? raw : value }; + } + return null; +} +function rawAuthority(value) { + const match = /^[a-z][a-z0-9+.-]*:\/\//i.exec(value); + if (!match) + throw new Error("API URL must be absolute."); + const afterScheme = value.slice(match[0].length); + const boundary = afterScheme.search(/[/?#]/); + const authority = boundary === -1 ? afterScheme : afterScheme.slice(0, boundary); + if (!authority) + throw new Error("API URL must include a hostname."); + return authority; +} +function assertCanonicalPort(port) { + if (!/^[0-9]+$/.test(port) || port.length > 1 && port.startsWith("0")) { + throw new Error("API URL authority must contain a canonical port between 1 and 65535."); + } + const numericPort = Number(port); + if (!Number.isSafeInteger(numericPort) || numericPort < 1 || numericPort > 65535) { + throw new Error("API URL authority must contain a canonical port between 1 and 65535."); + } +} +function canonicalAuthorityHostname(authority) { + let rawHostname; + if (authority.startsWith("[")) { + const closingBracket = authority.indexOf("]"); + if (closingBracket === -1) { + throw new Error("API URL authority must contain a canonical hostname."); + } + rawHostname = authority.slice(0, closingBracket + 1); + const portSuffix = authority.slice(closingBracket + 1); + if (portSuffix) { + if (!portSuffix.startsWith(":")) { + throw new Error("API URL authority must contain a canonical hostname and port."); + } + assertCanonicalPort(portSuffix.slice(1)); + } + if (isIP(rawHostname.slice(1, -1)) !== 6) { + throw new Error("API URL authority must contain a canonical IPv6 literal."); + } + } else { + const firstColon = authority.indexOf(":"); + const lastColon = authority.lastIndexOf(":"); + if (firstColon !== lastColon) { + throw new Error("IPv6 API URL authorities must use brackets."); + } + if (lastColon !== -1) { + const port = authority.slice(lastColon + 1); + assertCanonicalPort(port); + rawHostname = authority.slice(0, lastColon); } else { - this.__proto__ = actualProto; + rawHostname = authority; + } + const ipVersion = isIP(rawHostname); + const numericAddressParts = rawHostname.split("."); + const looksLikeNonCanonicalIpv4 = numericAddressParts.every((part) => /^(?:0x[0-9a-f]+|[0-9]+)$/i.test(part)); + if (ipVersion !== 4 && looksLikeNonCanonicalIpv4 || ipVersion !== 4 && !isValidDnsDomain(rawHostname.toLowerCase())) { + throw new Error("API URL authority must contain a canonical ASCII hostname."); } - this.name = "ZodError"; - this.issues = issues; } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; + return rawHostname.toLowerCase(); +} +function isDeliberateLoopbackHttpAuthority(authority) { + return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(authority); +} +function toV1BaseUrl(apiUrl) { + if (ASCII_CONTROL_PATTERN.test(apiUrl)) { + throw new Error("API URL must not contain ASCII control characters."); } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } + const input = apiUrl.trim(); + const authority = rawAuthority(input); + if (authority.includes("@") || authority.includes("\\") || authority.includes("%") || /[^\x00-\x7f]/.test(authority)) { + throw new Error("API URL authority must be canonical ASCII without credentials."); } - toString() { - return this.message; + const canonicalHostname = canonicalAuthorityHostname(authority); + const url = new URL(input); + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("API URL must use http or https."); } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + if (url.username || url.password) { + throw new Error("API URL must not include credentials."); } - get isEmpty() { - return this.issues.length === 0; + if (!url.hostname || url.hostname.endsWith(".")) { + throw new Error("API URL must include a canonical hostname."); } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; + if (url.hostname.toLowerCase() !== canonicalHostname) { + throw new Error("API URL authority must not rely on parser hostname normalization."); } - get formErrors() { - return this.flatten(); + if (url.hostname.split(".").some((label) => label.toLowerCase().startsWith("xn--"))) { + throw new Error("API URL must not use IDN or punycode hostnames."); } -} -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); + if (url.protocol === "http:" && !isDeliberateLoopbackHttpAuthority(authority)) { + throw new Error("API URL may use http only for an exact loopback authority."); } - return { message }; -}; -var en_default = errorMap; -var overrideErrorMap = en_default; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; + if (url.search || url.hash) { + throw new Error("API URL must not include a query string or fragment."); + } + let path = url.pathname.replace(/\/+$/, ""); + if (path.endsWith("/v1")) + path = path.slice(0, -"/v1".length); + url.pathname = `${path}/v1`; + return url.toString().replace(/\/+$/, ""); } -var makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { +function resolveClientTransport(name, env = process.env, options = {}) { + const keys = clientTransportEnvKeys(name); + const modeHit = firstEnv2(env, keys.modeKeys); + const urlHit = firstEnv2(env, keys.apiUrlKeys, { preserveRaw: true }); + const keyHit = firstEnv2(env, keys.apiKeyKeys); + let mode = "sqlite"; + let modeSource = "default"; + const warnings = []; + let credential; + if (modeHit) { + mode = normalizeStorageMode(modeHit.value).mode; + modeSource = modeHit.key; + } else if (urlHit) { + credential = resolveCredential(name, env, options.credentials); + if (credential) { + mode = "postgres"; + modeSource = `${urlHit.key}+${credential.source}`; + } + } + if (mode === "sqlite") { return { - ...issueData, - path: fullPath, - message: issueData.message + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: Boolean(keyHit), + apiKeySource: keyHit ? keyHit.key : null, + apiKeyTier: null, + misconfigured: false, + warning: warnings.length > 0 ? warnings.join(" ") : null }; } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + if (credential === undefined) + credential = resolveCredential(name, env, options.credentials); + if (!credential) { + const diskHint = credentialDiskSourcesForMessage(name, env); + warnings.push(`${modeSource}=postgres but no API key could be resolved for '${name}'. A client reaches server data ` + `over HTTP only; refusing to route. Using the local sqlite store. ` + `Looked for a credential file at ${diskHint}, then for ${keys.apiKeyKeys[0]} in the environment.`); + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: false, + apiKeySource: null, + apiKeyTier: null, + misconfigured: true, + warning: warnings.join(" ") + }; + } + if (credential.warning) + warnings.push(credential.warning); + let defaultBaseUrl = null; + let apiUrlSource = urlHit?.key ?? (env[FLEET_API_DOMAIN_ENV_KEY] === undefined ? "default" : FLEET_API_DOMAIN_ENV_KEY); + let baseUrl; + try { + if (!urlHit) { + defaultBaseUrl = resolveDefaultCloudBaseUrl(name, env); + apiUrlSource = defaultBaseUrl.source; + } + const rawUrl = urlHit?.value ?? defaultBaseUrl.baseUrl; + baseUrl = toV1BaseUrl(rawUrl); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + warnings.push(`Invalid API URL from ${apiUrlSource}: ${message}. Using local store.`); + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: true, + apiKeySource: credential.source, + apiKeyTier: credential.tier, + misconfigured: true, + warning: warnings.join(" ") + }; } + if (defaultBaseUrl?.warning) + warnings.push(defaultBaseUrl.warning); return { - ...issueData, - path: fullPath, - message: errorMessage + transport: "http", + mode, + modeSource, + baseUrl, + apiUrlSource, + apiKeyPresent: true, + apiKeySource: credential.source, + apiKeyTier: credential.tier, + misconfigured: defaultBaseUrl?.misconfigured ?? false, + warning: warnings.length > 0 ? warnings.join(" ") : null }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default ? undefined : en_default - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); +} +function credentialDiskSourcesForMessage(name, env) { + const paths = credentialDiskSources(name, env); + return paths.length > 0 ? paths.join(" or ") : "<no HOME set in this environment, so no credential file was consulted>"; } -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; +class HasnaHttpError extends Error { + status; + method; + path; + body; + credentialSource; + credentialTier; + constructor(method, path, status, body, credential) { + const guidance = credential ? `. ${credential.guidance}` : ""; + super(`Hasna cloud request failed: ${method} ${path} -> ${status}${guidance}`); + this.name = "HasnaHttpError"; + this.status = status; + this.method = method; + this.path = path; + this.body = body; + this.credentialSource = credential?.source ?? null; + this.credentialTier = credential?.tier ?? null; } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); +} +function currentCredential(name, apiKey) { + if (typeof apiKey === "function") + return apiKey(); + return explicitCredential(name, apiKey); +} +function authFailureGuidance(credential) { + const origin = `The API key for this request came from ${credential.source}`; + if (credential.deliberate) { + return `${origin} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: ` + `falling back here would authenticate as a different principal than the one you named, which is ` + `exactly the failure an override exists to prevent. Rotate that key, or unset the override to use ` + `the credential on disk.`; } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; + if (credential.deprecated) { + const target = credential.diskCandidates[0]; + const remedy = target ? `Write the CURRENT key to ${target} \u2014 that file is re-read on every call, so rotations take ` + `effect immediately and in every shell. Do not simply unset ${credential.source}: nothing was ` + `found on disk, so that would leave this client with no credential at all.` : `This environment has no HOME, so no credential file could be consulted; the disk tier is ` + `unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.`; + return `${origin}, a variable in this process's environment \u2014 which is a snapshot taken when the process ` + `started. A STALE SHELL is the most common cause of this error: this shell exported the key before ` + `it was rotated, and will keep sending the old one until it exits. ${remedy}`; } + return `${origin}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. ` + `The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution ` + `so this machine gets the current key.`; } -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x) => x.status === "aborted"; -var isDirty = (x) => x.status === "dirty"; -var isValid = (x) => x.status === "valid"; -var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; +var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504]; +var IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); +var AUTHORITY_OVERRIDE_HEADERS = new Set([ + "host", + ":authority", + "forwarded", + "x-forwarded-host", + "x-original-host" +]); +function assertNoAuthorityOverrideHeaders(headers, source) { + if (!headers) + return; + const forbidden = Object.keys(headers).find((name) => AUTHORITY_OVERRIDE_HEADERS.has(name.trim().toLowerCase())); + if (forbidden) { + throw new Error(`Authenticated ${source} headers must not set authority header '${forbidden}'.`); } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); +} +function appendQuery(path, query) { + if (!query) + return path; + const params = query instanceof URLSearchParams ? query : new URLSearchParams; + if (!(query instanceof URLSearchParams)) { + for (const [key, value] of Object.entries(query)) { + if (value === null || value === undefined) + continue; + if (Array.isArray(value)) { + for (const v of value) + params.append(key, String(v)); } else { - this._cachedPath.push(...this._path, this._key); + params.append(key, String(value)); } } - return this._cachedPath; } + const qs = params.toString(); + if (!qs) + return path; + return `${path}${path.includes("?") ? "&" : "?"}${qs}`; } -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } +var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); +function createHasnaHttpTransport(options) { + const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init)); + const base = toV1BaseUrl(options.baseUrl); + const timeoutMs = options.timeoutMs ?? 30000; + const sleep = options.sleepImpl ?? defaultSleep; + const defaultRetry = options.retry; + function resolveRetry(callRetry) { + const chosen = callRetry !== undefined ? callRetry : defaultRetry; + if (chosen === false) + return null; + const r = chosen ?? {}; return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } + retries: r.retries ?? 2, + baseDelayMs: r.baseDelayMs ?? 200, + maxDelayMs: r.maxDelayMs ?? 2000, + retryStatuses: r.retryStatuses ?? [...DEFAULT_RETRY_STATUSES] }; } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; + async function once(method, rel, url, body, opts, credential) { + assertNoAuthorityOverrideHeaders(options.headers, "transport"); + assertNoAuthorityOverrideHeaders(opts.headers, "request"); + const headers = { + "x-api-key": credential.apiKey, + Authorization: `Bearer ${credential.apiKey}`, + Accept: "application/json", + ...options.headers ?? {}, + ...opts.headers ?? {} + }; + if (opts.idempotencyKey) + headers["Idempotency-Key"] = opts.idempotencyKey; + const init = { + method, + headers, + redirect: "manual" + }; + if (body !== undefined) { + headers["Content-Type"] = "application/json"; + init.body = JSON.stringify(body); } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; + const controller = new AbortController; + const onAbort = () => controller.abort(); + if (opts.signal) { + if (opts.signal.aborted) + controller.abort(); + else + opts.signal.addEventListener("abort", onAbort, { once: true }); } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; + const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? timeoutMs); + init.signal = controller.signal; + let response; + try { + response = await fetchImpl(url, init); + } catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + if (opts.signal?.aborted) + return { ok: false, retryable: false, error: err }; + return { ok: false, retryable: true, error: err }; + } finally { + clearTimeout(timer); + if (opts.signal) + opts.signal.removeEventListener("abort", onAbort); + } + const text = await response.text(); + let parsed = undefined; + if (text.length > 0) { + try { + parsed = JSON.parse(text); + } catch { + parsed = text; + } + } + if (!response.ok) { + if (response.status >= 300 && response.status < 400) { + return { + ok: false, + retryable: false, + error: new HasnaHttpError(method, rel, response.status, parsed) + }; + } + if (response.status === 401 || response.status === 403) { + return { + ok: false, + retryable: false, + error: new HasnaHttpError(method, rel, response.status, parsed, { + source: credential.source, + tier: credential.tier, + guidance: authFailureGuidance(credential) + }) + }; + } + const retry = resolveRetry(opts.retry); + const retryable = retry ? retry.retryStatuses.includes(response.status) : false; + return { ok: false, retryable, error: new HasnaHttpError(method, rel, response.status, parsed) }; + } + return { ok: true, value: parsed }; + } + async function request(method, path, body, opts = {}) { + const upper = method.toUpperCase(); + const rel = appendQuery(path.startsWith("/") ? path : `/${path}`, opts.query); + const url = `${base}${rel}`; + const retry = resolveRetry(opts.retry); + const methodRetryable = IDEMPOTENT_METHODS.has(upper) || Boolean(opts.idempotencyKey); + const maxAttempts = retry && methodRetryable ? retry.retries + 1 : 1; + const credential = currentCredential(options.name, options.apiKey); + let last = null; + for (let attempt = 1;attempt <= maxAttempts; attempt++) { + const result = await once(upper, rel, url, body, opts, credential); + if (result.ok) + return result.value; + last = result; + const canRetry = retry !== null && methodRetryable && result.retryable && attempt < maxAttempts; + if (!canRetry) + break; + const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1)); + const jitter = Math.floor(Math.random() * (backoff / 2 + 1)); + await sleep(backoff + jitter); + } + throw last.error; + } + return { + baseUrl: base, + request, + get: (path, opts) => request("GET", path, undefined, opts), + post: (path, body, opts) => request("POST", path, body, opts), + put: (path, body, opts) => request("PUT", path, body, opts), + patch: (path, body, opts) => request("PATCH", path, body, opts), + del: (path, body, opts) => request("DELETE", path, body, opts) }; - return { errorMap: customMap, description }; } - -class ZodType { - get description() { - return this._def.description; +function createClientTransport(name, env = process.env, overrides) { + const credentialOptions = overrides?.credentials; + const resolution = resolveClientTransport(name, env, { ...credentialOptions ? { credentials: credentialOptions } : {} }); + if (resolution.misconfigured) { + throw new Error(resolution.warning ?? `Client for '${name}' is misconfigured for the API client.`); } - _getType(input) { - return getParsedType(input.data); + if (resolution.transport === "sqlite" || !resolution.baseUrl) { + return { transport: "sqlite", client: null, resolution }; } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; + const credentialProvider = () => { + const resolved = resolveCredential(name, env, credentialOptions); + if (!resolved) { + throw new Error(`Client for '${name}' resolved to the http transport but no API key is available any more. ` + `Looked at ${credentialDiskSourcesForMessage(name, env)}, then the environment. ` + `A credential file that was removed after this client was built is the usual cause.`); + } + return resolved; + }; + return { + transport: "http", + client: createHasnaHttpTransport({ + name, + baseUrl: resolution.baseUrl, + apiKey: credentialProvider, + ...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {}, + ...overrides?.headers ? { headers: overrides.headers } : {}, + ...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {}, + ...overrides?.retry !== undefined ? { retry: overrides.retry } : {}, + ...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {} + }), + resolution + }; +} +function resourcePath(resource) { + const trimmed = resource.replace(/^\/+|\/+$/g, ""); + if (!trimmed) + throw new Error("resource must be a non-empty path segment"); + return `/${trimmed}`; +} +function entityPath(resource, id) { + if (id === undefined || id === null || `${id}`.length === 0) { + throw new Error("id must be a non-empty string"); } - _processInputParams(input) { - return { - status: new ParseStatus, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; + return `${resourcePath(resource)}/${encodeURIComponent(String(id))}`; +} +function newIdempotencyKey() { + const g = globalThis; + if (g.crypto?.randomUUID) + return g.crypto.randomUUID(); + return `idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`; +} +function extractItems(raw) { + if (Array.isArray(raw)) + return raw; + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["items", "data", "results", "rows", "records"]) { + if (Array.isArray(obj[key])) + return obj[key]; + } } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); + return []; +} +function extractTotal(raw) { + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["total", "count", "totalCount", "total_count"]) { + if (typeof obj[key] === "number") + return obj[key]; } - return result; } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); + return null; +} +function extractCursor(raw) { + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["cursor", "nextCursor", "next_cursor", "next"]) { + if (typeof obj[key] === "string") + return obj[key]; + } } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { + return null; +} +function createHasnaStorageClient(name, transport) { + return { + name, + baseUrl: transport.baseUrl, + transport, + async list(resource, options = {}) { + const raw = await transport.get(resourcePath(resource), options); + return { + items: extractItems(raw), + total: extractTotal(raw), + cursor: extractCursor(raw), + raw + }; + }, + async get(resource, id, options = {}) { try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; + return await transport.get(entityPath(resource, id), options); + } catch (error) { + if (error instanceof HasnaHttpError && error.status === 404) + return null; + throw error; } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) + }, + async create(resource, body, options = {}) { + const { idempotencyKey, ...rest } = options; + return transport.post(resourcePath(resource), body, { + ...rest, + idempotencyKey: idempotencyKey ?? newIdempotencyKey() }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; + }, + async update(resource, id, patch, options = {}) { + const { method = "PATCH", idempotencyKey, ...rest } = options; + const call = method === "PUT" ? transport.put : transport.patch; + return call(entityPath(resource, id), patch, { ...rest, ...idempotencyKey ? { idempotencyKey } : {} }); + }, + async delete(resource, id, options = {}) { + try { + await transport.del(entityPath(resource, id), undefined, options); + } catch (error) { + if (error instanceof HasnaHttpError && error.status === 404) + return; + throw error; } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); + } + }; +} +function resolveStorageClient(name, env = process.env, overrides) { + const wired = createClientTransport(name, env, overrides); + if (wired.transport === "http") { + return { transport: "http", client: createHasnaStorageClient(name, wired.client) }; } - superRefine(refinement) { - return this._refinement(refinement); + return { transport: "sqlite", client: null }; +} + +// node_modules/@hasna/contracts/dist/client/transport.js +function envToken2(name) { + return name.toUpperCase().replace(/-/g, "_"); +} +function clientTransportEnvKeys2(name) { + const envSegment = envToken2(name); + return { + modeKeys: [ + `HASNA_${envSegment}_STORAGE_MODE`, + `HASNA_${envSegment}_MODE`, + `${envSegment}_STORAGE_MODE`, + `${envSegment}_MODE` + ], + apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], + apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] + }; +} +var MAX_CREDENTIAL_FILE_BYTES2 = 64 * 1024; +var INSPECT_CUSTOM2 = Symbol.for("nodejs.util.inspect.custom"); +var DEPRECATION_REGISTRY2 = Symbol.for("hasna:contracts:credentialDeprecationNotices"); +var IDEMPOTENT_METHODS2 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); +var AUTHORITY_OVERRIDE_HEADERS2 = new Set([ + "host", + ":authority", + "forwarded", + "x-forwarded-host", + "x-original-host" +]); + +// node_modules/@hasna/contracts/dist/mode.js +function normalizeStorageMode2(value) { + const normalized = value.trim().toLowerCase().replace(/-/g, "_"); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); +} + +// src/generated/storage-kit/mode.ts +function normalizeStorageMode3(value) { + const normalized = value.trim().toLowerCase().replace(/-/g, "_"); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); +} +function envToken3(name) { + return name.toUpperCase().replace(/-/g, "_"); +} +function storageEnvKeys(name) { + const token = envToken3(name); + return { + modeKeys: [`HASNA_${token}_STORAGE_MODE`, `${token}_STORAGE_MODE`], + databaseUrlKeys: [`HASNA_${token}_DATABASE_URL`, `${token}_DATABASE_URL`] + }; +} +function firstEnv(env, keys) { + for (const key of keys) { + const value = env[key]?.trim(); + if (value) + return { key, value }; } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) + return null; +} +function resolveStorageMode(name, env = process.env) { + const { modeKeys, databaseUrlKeys } = storageEnvKeys(name); + const dbHit = firstEnv(env, databaseUrlKeys); + const databaseUrlPresent = Boolean(dbHit); + const databaseUrlSource = dbHit ? dbHit.key : null; + const modeHit = firstEnv(env, modeKeys); + if (!modeHit) { + return { + mode: databaseUrlPresent ? "postgres" : "sqlite", + source: databaseUrlPresent ? databaseUrlSource : "default", + databaseUrlPresent, + databaseUrlSource, + warning: null }; } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); + const { mode } = normalizeStorageMode3(modeHit.value); + const warnings = []; + if (mode === "postgres" && !databaseUrlPresent) { + warnings.push(`postgres storage needs ${databaseUrlKeys[0]} (reads and writes go to PostgreSQL).`); } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); + if (modeHit.key !== modeKeys[0]) { + warnings.push(`Using alias env ${modeHit.key}; the canonical key is ${modeKeys[0]}.`); } - pipe(target) { - return ZodPipeline.create(this, target); + return { + mode, + source: modeHit.key, + databaseUrlPresent, + databaseUrlSource, + warning: warnings.length > 0 ? warnings.join(" ") : null + }; +} +function resolveDatabaseUrl(name, env = process.env) { + const { databaseUrlKeys } = storageEnvKeys(name); + const hit = firstEnv(env, databaseUrlKeys); + return hit ? hit.value : null; +} +// src/generated/storage-kit/tls.ts +import { readFileSync as readFileSync3 } from "fs"; +function sslModeFromConnectionString(connectionString) { + const queryStart = connectionString.indexOf("?"); + const params = new URLSearchParams(queryStart === -1 ? "" : connectionString.slice(queryStart + 1)); + const sslmode = params.get("sslmode")?.trim().toLowerCase(); + if (sslmode) { + switch (sslmode) { + case "disable": + case "prefer": + case "require": + case "verify-ca": + case "verify-full": + return sslmode; + case "allow": + return "prefer"; + default: + throw new Error(`Unknown sslmode '${sslmode}' in connection string.`); + } } - readonly() { - return ZodReadonly.create(this); + const ssl = params.get("ssl")?.trim().toLowerCase(); + if (ssl && ["1", "true", "yes", "on", "require"].includes(ssl)) + return "require"; + return "disable"; +} +function loadCaBundle(options) { + const env = options.env ?? process.env; + if (options.ca && options.ca.trim()) + return options.ca; + const path = options.caCertPath ?? env.PGSSLROOTCERT ?? env.NODE_EXTRA_CA_CERTS; + if (path && path.trim()) + return readFileSync3(path.trim(), "utf8"); + return null; +} +function resolveTlsConfig(connectionString, options = {}) { + const mode = sslModeFromConnectionString(connectionString); + if (mode === "disable" || mode === "prefer") { + return; } - isOptional() { - return this.safeParse(undefined).success; + const ca = loadCaBundle(options); + if (mode === "require") { + return ca ? { rejectUnauthorized: false, ca } : { rejectUnauthorized: false }; } - isNullable() { - return this.safeParse(null).success; + if (!ca) { + throw new Error(`sslmode=${mode} requires a CA bundle. Set PGSSLROOTCERT (or pass caCertPath/ca) to the ` + `Amazon RDS global bundle: https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem`); } + return { rejectUnauthorized: true, ca }; } -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?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)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?: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])$/; -var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\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])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +// src/generated/storage-kit/query.ts +function wrapExecutor(executor) { + return { + async query(sql, params) { + const result = await executor.query(sql, params); + return { rows: result.rows, rowCount: result.rowCount ?? result.rows.length }; + }, + async many(sql, params) { + const result = await executor.query(sql, params); + return result.rows; + }, + async get(sql, params) { + const result = await executor.query(sql, params); + return result.rows[0] ?? null; + }, + async one(sql, params) { + const result = await executor.query(sql, params); + if (result.rows.length !== 1) { + throw new Error(`Expected exactly one row, got ${result.rows.length}.`); + } + return result.rows[0]; + }, + async execute(sql, params) { + await executor.query(sql, params); + } + }; } -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); +function createQueryClient(pool) { + const base = wrapExecutor(pool); + return { + ...base, + pool, + async transaction(fn) { + const client = await pool.connect(); + try { + await client.query("BEGIN"); + const result = await fn(wrapExecutor(client)); + await client.query("COMMIT"); + return result; + } catch (error) { + try { + await client.query("ROLLBACK"); + } catch {} + throw error; + } finally { + client.release(); + } + }, + async close() { + await pool.end(); + } + }; } -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); +// src/generated/storage-kit/pool.ts +import pg from "pg"; +function createPgPool(options) { + const ssl = resolveTlsConfig(options.connectionString, { + ...options.ca !== undefined ? { ca: options.ca } : {}, + ...options.caCertPath !== undefined ? { caCertPath: options.caCertPath } : {}, + ...options.env !== undefined ? { env: options.env } : {} + }); + const config = { connectionString: options.connectionString }; + if (ssl !== undefined) + config.ssl = ssl; + if (options.max !== undefined) + config.max = options.max; + if (options.idleTimeoutMillis !== undefined) + config.idleTimeoutMillis = options.idleTimeoutMillis; + if (options.connectionTimeoutMillis !== undefined) + config.connectionTimeoutMillis = options.connectionTimeoutMillis; + if (options.applicationName !== undefined) + config.application_name = options.applicationName; + return new pg.Pool(config); } -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; +function createServerPoolFromEnv(appName, options = {}) { + const env = options.env ?? process.env; + const resolution = resolveStorageMode(appName, env); + if (resolution.mode !== "postgres") { + throw new Error(`createServerPoolFromEnv requires ${appName} storage mode 'postgres', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=postgres.`); } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; + const connectionString = resolveDatabaseUrl(appName, env); + if (!connectionString) { + throw new Error(`postgres storage for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); } - return false; + const pool = createPgPool({ + connectionString, + ...options.ca !== undefined ? { ca: options.ca } : {}, + ...options.caCertPath !== undefined ? { caCertPath: options.caCertPath } : {}, + env, + ...options.max !== undefined ? { max: options.max } : {}, + ...options.idleTimeoutMillis !== undefined ? { idleTimeoutMillis: options.idleTimeoutMillis } : {}, + ...options.connectionTimeoutMillis !== undefined ? { connectionTimeoutMillis: options.connectionTimeoutMillis } : {}, + ...options.applicationName !== undefined ? { applicationName: options.applicationName } : {} + }); + return { + client: createQueryClient(pool), + connectionSource: resolution.databaseUrlSource ?? "unknown" + }; } -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } +// src/generated/storage-kit/migrations.ts +import { createHash } from "crypto"; +var DEFAULT_MIGRATION_LEDGER_TABLE = "schema_migrations"; +function checksumSql(sql) { + const normalized = sql.trim().replace(/\r\n/g, ` +`); + return `sha256:${createHash("sha256").update(normalized).digest("hex")}`; } -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; +function defineMigration(id, sql) { + return Object.freeze({ id, sql: sql.trim(), checksum: checksumSql(sql) }); } -class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } +class MigrationLedger { + client; + migrations; + ledgerTable; + constructor(client, migrations, options = {}) { + this.client = client; + this.migrations = migrations; + this.ledgerTable = options.ledgerTable ?? DEFAULT_MIGRATION_LEDGER_TABLE; + const seen = new Set; + for (const migration of migrations) { + if (seen.has(migration.id)) + throw new Error(`Duplicate migration id: ${migration.id}`); + seen.add(migration.id); } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + async ensureLedger() { + await this.client.execute(`CREATE TABLE IF NOT EXISTS ${this.ledgerTable} ( + id TEXT PRIMARY KEY, + checksum TEXT NOT NULL, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now() + )`); } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + async listApplied() { + await this.ensureLedger(); + return this.readApplied(); } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + async readApplied() { + const rows = await this.client.many(`SELECT id, checksum, applied_at FROM ${this.ledgerTable} ORDER BY id ASC`); + return rows.map((row) => ({ + id: row.id, + checksum: row.checksum, + appliedAt: row.applied_at instanceof Date ? row.applied_at.toISOString() : String(row.applied_at) + })); } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + buildPlan(applied) { + const known = new Set(this.migrations.map((m) => m.id)); + for (const row of applied) { + if (!known.has(row.id)) { + throw new Error(`Applied migration '${row.id}' is not recognized by this build (downgrade?).`); + } + } + const appliedById = new Map(applied.map((row) => [row.id, row])); + for (const migration of this.migrations) { + const existing = appliedById.get(migration.id); + if (existing && existing.checksum !== migration.checksum) { + throw new Error(`Migration checksum mismatch for '${migration.id}': the SQL changed after it was applied.`); + } + } + return this.migrations.map((migration) => ({ + migration, + state: appliedById.has(migration.id) ? "already_applied" : "pending" + })); } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + async migrate(opts = {}) { + const dryRun = opts.dryRun === true; + await this.ensureLedger(); + const applied = await this.readApplied(); + const plan = this.buildPlan(applied); + if (dryRun) + return { dryRun, applied, plan }; + for (const item of plan) { + if (item.state === "already_applied") + continue; + await this.client.execute(item.migration.sql); + await this.client.execute(`INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, [item.migration.id, item.migration.checksum]); + } + return { dryRun, applied: await this.readApplied(), plan }; } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); +} +function createMigrationLedger(client, migrations, options = {}) { + return new MigrationLedger(client, migrations, options); +} +// src/generated/storage-kit/health.ts +async function checkHealth(client) { + const start = Date.now(); + try { + await client.get("SELECT 1 AS ok"); + return { ok: true, latencyMs: Date.now() - start }; + } catch (error) { + return { + ok: false, + latencyMs: Date.now() - start, + error: error instanceof Error ? error.message : String(error) + }; } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); +} +async function checkReady(client, migrations, options = {}) { + const start = Date.now(); + try { + const ledger = new MigrationLedger(client, migrations, options); + const result = await ledger.migrate({ dryRun: true }); + const pending = result.plan.filter((item) => item.state === "pending").map((item) => item.migration.id); + return { ok: pending.length === 0, latencyMs: Date.now() - start, pendingMigrations: pending }; + } catch (error) { + return { + ok: false, + latencyMs: Date.now() - start, + pendingMigrations: [], + error: error instanceof Error ? error.message : String(error) + }; } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); +} + +// src/generated/storage-kit/index.ts +var KIT_VERSION = "0.8.5"; + +// src/net-guard.ts +var NETWORK_GUARD_ENV = "NODE_ENV"; + +class KnowledgeNetworkGuardError extends Error { + scheme; + port; + constructor(message, details) { + super(message); + this.name = "KnowledgeNetworkGuardError"; + this.scheme = details.scheme; + this.port = details.port; } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); +} +function isNetworkGuardActive(env = process.env) { + return (env[NETWORK_GUARD_ENV] ?? "").trim().toLowerCase() === "test"; +} +function isIpv4Loopback(hostname) { + const parts = hostname.split("."); + if (parts.length !== 4) + return false; + if (!parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)) + return false; + return parts[0] === "127"; +} +function isLoopbackHostname(hostname) { + const host = hostname.trim().toLowerCase(); + if (host.length === 0) + return false; + if (host === "localhost" || host.endsWith(".localhost")) + return true; + if (isIpv4Loopback(host)) + return true; + if (!host.startsWith("[") || !host.endsWith("]")) + return false; + const v6 = host.slice(1, -1); + if (v6 === "::1" || /^(0:){7}1$/.test(v6)) + return true; + const tail = v6.split(":").pop() ?? ""; + if (/^(::ffff:|::)/.test(v6) && isIpv4Loopback(tail)) + return true; + return /^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(v6); +} +function targetUrl(input) { + if (typeof input === "string") + return input; + if (input instanceof URL) + return input.href; + return input.url; +} +function assertOutboundRequestAllowed(input, env = process.env) { + if (!isNetworkGuardActive(env)) + return; + const raw = targetUrl(input); + let url; + try { + url = new URL(raw); + } catch { + throw new KnowledgeNetworkGuardError(`knowledge: refused an outbound request with an unparseable target while ${NETWORK_GUARD_ENV}=test. ` + "Under test, only loopback requests are permitted.", { scheme: "unknown", port: "" }); } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + if (isLoopbackHostname(url.hostname)) + return; + throw new KnowledgeNetworkGuardError(`knowledge: refused a non-loopback ${url.protocol.replace(":", "")} request while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). This process resolved to the cloud backend under test, which means a " + "read or write was about to leave the machine and reach the live store. Select the mode explicitly " + `(${"HASNA_KNOWLEDGE_STORAGE_MODE"}=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`, { scheme: url.protocol.replace(":", ""), port: url.port }); +} +var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); +var MAX_GUARDED_REDIRECTS = 5; +function requestMethod(input, init) { + if (init?.method) + return init.method.toUpperCase(); + if (typeof input !== "string" && !(input instanceof URL)) + return input.method.toUpperCase(); + return "GET"; +} +async function guardedFetch(input, init) { + assertOutboundRequestAllowed(input); + if (!isNetworkGuardActive() || init?.redirect !== undefined) { + return fetch(input, init); } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); + let from = targetUrl(input); + let method = requestMethod(input, init); + let body = init?.body; + let response = await fetch(input, { ...init ?? {}, redirect: "manual" }); + for (let hop = 0;REDIRECT_STATUSES.has(response.status); hop++) { + const location = response.headers.get("location"); + if (!location) + return response; + const next = new URL(location, from).href; + assertOutboundRequestAllowed(next); + if (hop >= MAX_GUARDED_REDIRECTS) { + const url = new URL(next); + throw new KnowledgeNetworkGuardError(`knowledge: refused to follow more than ${MAX_GUARDED_REDIRECTS} redirects while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). Under test the guard follows redirects itself so every hop is " + "checked, and a chain this long is a loop, not a route.", { scheme: url.protocol.replace(":", ""), port: url.port }); } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); + if (response.status === 303 || (response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD") { + method = "GET"; + body = undefined; } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); + const hopInit = { ...init ?? {}, method, redirect: "manual" }; + if (body === undefined) + delete hopInit.body; + else + hopInit.body = body; + response = await fetch(next, hopInit); + from = next; } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + return response; +} + +// src/knowledge-mode.ts +var KNOWLEDGE_APP_SLUG = "knowledge"; +var ENV_KEYS = clientTransportEnvKeys2(KNOWLEDGE_APP_SLUG); +var KNOWLEDGE_MODE_ENV_KEYS = ENV_KEYS.modeKeys; +var KNOWLEDGE_API_URL_ENV_KEYS = ENV_KEYS.apiUrlKeys; +var KNOWLEDGE_API_KEY_ENV_KEYS = ENV_KEYS.apiKeyKeys; +function presentEnvNames(env, keys) { + return keys.filter((key) => (env[key] ?? "").trim().length > 0); +} +function resolveKnowledgeModeSelection(env = process.env) { + const pointers = [ + ...presentEnvNames(env, KNOWLEDGE_API_URL_ENV_KEYS), + ...presentEnvNames(env, KNOWLEDGE_API_KEY_ENV_KEYS) + ]; + const canonicalModeKey = KNOWLEDGE_MODE_ENV_KEYS[0]; + for (const name of KNOWLEDGE_MODE_ENV_KEYS) { + const value = env[name]?.trim(); + if (!value) + continue; + let normalized; + try { + normalized = normalizeStorageMode3(value); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`knowledge: ${name}=${value} is not a valid mode. ${message}`); + } + const warnings = []; + if (name !== canonicalModeKey) { + warnings.push(`Using alias env ${name}; the canonical key is ${canonicalModeKey}.`); + } + if (normalized.mode === "sqlite" && pointers.length > 0) { + warnings.push(`${name}=sqlite pins the on-box store; ${pointers.join(", ")} are set but ignored.`); + } + return { + mode: normalized.mode, + source: { kind: "env", name, value }, + pointer_env_present: pointers, + pointer_ignored: normalized.mode === "sqlite" && pointers.length > 0, + warning: warnings.length > 0 ? warnings.join(" ") : null + }; } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; + return { + mode: "sqlite", + source: { kind: "default", name: null, value: null }, + pointer_env_present: pointers, + pointer_ignored: pointers.length > 0, + warning: pointers.length > 0 ? `${pointers.join(", ")} are set but do NOT select a backend: mode is sqlite by default. ` + `Set ${canonicalModeKey}=postgres to route reads and writes to the API, or unset those vars to silence this note.` : null + }; +} +var SERVER_MODE_CANDIDATES = ["postgres"]; +var LOCAL_MODE_CANDIDATES = ["sqlite"]; +var derivedTokenCache = new Map; +function deriveToken(candidates, normalize, constantName) { + const useCache = normalize === normalizeStorageMode2; + if (useCache) { + const hit = derivedTokenCache.get(candidates); + if (hit !== undefined) + return hit; } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; + for (const candidate of candidates) { + try { + normalize(candidate); + if (useCache) + derivedTokenCache.set(candidates, candidate); + return candidate; + } catch {} } + throw new Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts ` + `(tried ${candidates.join(", ")}). The storage-mode enum has changed; add the new ` + `token to ${constantName} in src/knowledge-mode.ts.`); } -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; +function serverStorageMode(normalize = normalizeStorageMode2) { + return deriveToken(SERVER_MODE_CANDIDATES, normalize, "SERVER_MODE_CANDIDATES"); +} +function localStorageMode(normalize = normalizeStorageMode2) { + return deriveToken(LOCAL_MODE_CANDIDATES, normalize, "LOCAL_MODE_CANDIDATES"); +} +function contractsStorageModeFor(mode2, normalize = normalizeStorageMode2) { + return mode2 === "postgres" ? serverStorageMode(normalize) : localStorageMode(normalize); +} +function pinnedTransportEnv(env, mode2) { + return { ...env, [KNOWLEDGE_MODE_ENV_KEYS[0]]: contractsStorageModeFor(mode2) }; +} +function knowledgeModeReport(env = process.env) { + const resolution = resolveKnowledgeModeSelection(env); + return { + ...resolution, + store_transport: resolution.mode === "postgres" ? "api" : "local", + api_key_present: presentEnvNames(env, KNOWLEDGE_API_KEY_ENV_KEYS).length > 0, + network_guard_active: isNetworkGuardActive(env) + }; } -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; +// src/cloud-store.ts +function transportOverrides(env) { + return { + fetchImpl: guardedFetch, + ...isNetworkGuardActive(env) ? { retry: false } : {} + }; +} +var KNOWLEDGE_RESOURCE = "notes"; + +class KnowledgeVersionConflictError extends Error { + expected; + current; + code = "version_conflict"; + constructor(expected, current) { + super(`version_conflict: this edit was written against version ${expected} but the stored entry is now at version ${current}. ` + "Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions."); + this.expected = expected; + this.current = current; + this.name = "KnowledgeVersionConflictError"; } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType +} +function toQuery(options) { + const q = {}; + if (options.search) + q.search = options.search; + if (options.limit !== undefined) + q.limit = options.limit; + if (options.offset !== undefined) + q.offset = options.offset; + if (options.includeArchived || options.archivedOnly) + q.includeArchived = true; + return q; +} +function wrap(client) { + return { + baseUrl: client.baseUrl, + async list(options = {}) { + const wantLimit = options.limit ?? 200; + const query2 = toQuery({ ...options, limit: Math.min(Math.max(wantLimit, 1), 200) }); + const res = await client.list(KNOWLEDGE_RESOURCE, { query: query2 }); + let items = res.items; + if (options.archivedOnly) + items = items.filter((x) => x.archived === true); + if (options.tag) { + const t = options.tag.toLowerCase(); + items = items.filter((x) => (x.tags ?? []).some((tag) => tag.toLowerCase() === t)); + } + return { items, total: res.total }; + }, + async get(idOrShort) { + return client.get(KNOWLEDGE_RESOURCE, idOrShort); + }, + async create(input) { + return client.create(KNOWLEDGE_RESOURCE, { + ...input.id ? { id: input.id } : {}, + title: input.title, + content: input.content, + url: input.url ?? null, + tags: input.tags ?? [], + ...input.metadata ? { metadata: input.metadata } : {} }); - return INVALID; - } - let ctx = undefined; - const status = new ParseStatus; - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); + }, + async update(idOrShort, patch, options = {}) { + try { + return await client.update(KNOWLEDGE_RESOURCE, idOrShort, patch, { + ...options.expectedVersion !== undefined ? { headers: { "if-match": String(options.expectedVersion) } } : {} + }); + } catch (error) { + if (isNotFound(error)) + return null; + const conflict = asVersionConflict(error); + if (conflict) + throw conflict; + throw error; } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + }, + async delete(idOrShort) { + const existing = await client.get(KNOWLEDGE_RESOURCE, idOrShort); + if (!existing) + return false; + await client.delete(KNOWLEDGE_RESOURCE, existing.id); + return true; + }, + async listVersions(idOrShort, options = {}) { + try { + return await client.transport.get(`/${KNOWLEDGE_RESOURCE}/${encodeURIComponent(idOrShort)}/versions`, { query: { limit: options.limit, offset: options.offset } }); + } catch (error) { + if (isNotFound(error)) + return null; + throw error; } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + }, + async getVersion(idOrShort, version) { + try { + return await client.transport.get(`/${KNOWLEDGE_RESOURCE}/${encodeURIComponent(idOrShort)}/versions/${version}`); + } catch (error) { + if (isNotFound(error)) + return null; + throw error; } } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + }; +} +function asVersionConflict(error) { + if (!error || typeof error !== "object") + return null; + if (error.status !== 409) + return null; + const body = error.body; + const parsed = typeof body === "string" ? safeJson(body) : body; + const shape = parsed ?? {}; + if (shape.error !== "version_conflict") + return null; + return new KnowledgeVersionConflictError(Number(shape.expected ?? 0), Number(shape.current ?? 0)); +} +function safeJson(value) { + try { + return JSON.parse(value); + } catch { + return null; } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); +} +function isNotFound(error) { + return Boolean(error && typeof error === "object" && error.status === 404); +} +function resolveKnowledgeCloudStore(env = process.env) { + if (resolveKnowledgeModeSelection(env).mode !== "postgres") + return null; + const resolved = resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "postgres"), transportOverrides(env)); + if (resolved.transport !== "http") + return null; + return wrap(resolved.client); +} +function isKnowledgeApiMode(env = process.env) { + if (resolveKnowledgeModeSelection(env).mode !== "postgres") + return false; + return resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "postgres"), transportOverrides(env)).transport === "http"; +} +async function fetchAllCloudItems(store) { + const pageSize = 200; + const all = []; + for (let offset = 0;; offset += pageSize) { + const { items } = await store.list({ includeArchived: true, limit: pageSize, offset }); + all.push(...items); + if (items.length < pageSize) + break; + if (offset > 1e5) + break; } + return all; } -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus; - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; +// src/knowledge-db.ts +function assertLocalCatalogMode(operation = "catalog") { + if (isKnowledgeApiMode()) { + const modeKey = KNOWLEDGE_MODE_ENV_KEYS[0]; + throw new Error(`knowledge: ${operation} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, ` + `wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in ` + `cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item ` + `commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${modeKey}=local ` + `(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see ` + `which variable selected the current backend.`); } } -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; +var CURRENT_SCHEMA_VERSION = 10; +var CHUNKS_FTS_TOKENIZE = "porter unicode61 remove_diacritics 2"; +var MIGRATION_1 = ` +PRAGMA journal_mode = WAL; +PRAGMA foreign_keys = ON; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS schema_versions ( + version INTEGER PRIMARY KEY, + applied_at TEXT NOT NULL +); -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS sources ( + id TEXT PRIMARY KEY, + uri TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL, + title TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + acl_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS source_revisions ( + id TEXT PRIMARY KEY, + source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE, + revision TEXT NOT NULL, + hash TEXT, + extracted_text_uri TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + UNIQUE(source_id, revision) +); -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS chunks ( + id TEXT PRIMARY KEY, + source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, + wiki_page_id TEXT, + kind TEXT NOT NULL, + ordinal INTEGER NOT NULL, + text TEXT NOT NULL, + token_count INTEGER, + start_offset INTEGER, + end_offset INTEGER, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS chunk_embeddings ( + id TEXT PRIMARY KEY, + chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + model TEXT NOT NULL, + dimensions INTEGER NOT NULL, + vector_json TEXT NOT NULL, + created_at TEXT NOT NULL, + UNIQUE(chunk_id, provider, model) +); -class ZodAny extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS wiki_pages ( + id TEXT PRIMARY KEY, + path TEXT NOT NULL UNIQUE, + title TEXT NOT NULL, + artifact_uri TEXT, + content_hash TEXT, + status TEXT NOT NULL DEFAULT 'active', + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS wiki_backlinks ( + from_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, + to_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, + label TEXT, + created_at TEXT NOT NULL, + PRIMARY KEY(from_page_id, to_page_id) +); -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -} -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS citations ( + id TEXT PRIMARY KEY, + wiki_page_id TEXT REFERENCES wiki_pages(id) ON DELETE CASCADE, + chunk_id TEXT REFERENCES chunks(id) ON DELETE SET NULL, + source_uri TEXT NOT NULL, + quote TEXT, + start_offset INTEGER, + end_offset INTEGER, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS knowledge_indexes ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + name TEXT NOT NULL, + artifact_uri TEXT, + shard_key TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE(kind, name, shard_key) +); -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} +CREATE TABLE IF NOT EXISTS runs ( + id TEXT PRIMARY KEY, + type TEXT NOT NULL, + prompt TEXT, + status TEXT NOT NULL, + provider TEXT, + model TEXT, + cost_tokens INTEGER NOT NULL DEFAULT 0, + cost_usd REAL NOT NULL DEFAULT 0, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -} -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS run_events ( + id TEXT PRIMARY KEY, + run_id TEXT NOT NULL REFERENCES runs(id) ON DELETE CASCADE, + level TEXT NOT NULL, + event TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -} -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [undefined]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; +CREATE TABLE IF NOT EXISTS provider_usage ( + id TEXT PRIMARY KEY, + run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, + provider TEXT NOT NULL, + model TEXT NOT NULL, + input_tokens INTEGER NOT NULL DEFAULT 0, + output_tokens INTEGER NOT NULL DEFAULT 0, + cost_usd REAL NOT NULL DEFAULT 0, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -} -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} +CREATE TABLE IF NOT EXISTS redaction_findings ( + id TEXT PRIMARY KEY, + source_uri TEXT, + run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, + severity TEXT NOT NULL, + finding_type TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS storage_objects ( + id TEXT PRIMARY KEY, + artifact_uri TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL, + content_type TEXT, + hash TEXT, + size_bytes INTEGER, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest - }); - } -} -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; +CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( + text, + title, + source_uri, + content='', + tokenize='porter unicode61' +); -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -} +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (1, datetime('now')); +`; +var MIGRATION_2 = ` +DROP TABLE IF EXISTS chunks_fts; -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; +CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( + chunk_id UNINDEXED, + text, + title, + source_uri, + tokenize='porter unicode61' +); -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (2, datetime('now')); +`; +var MIGRATION_3 = ` +CREATE TABLE IF NOT EXISTS audit_events ( + id TEXT PRIMARY KEY, + event_type TEXT NOT NULL, + action TEXT NOT NULL, + target_uri TEXT, + decision TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -} +CREATE TABLE IF NOT EXISTS approval_gates ( + id TEXT PRIMARY KEY, + action TEXT NOT NULL, + target_uri TEXT, + status TEXT NOT NULL, + reason TEXT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; +CREATE INDEX IF NOT EXISTS idx_audit_events_action ON audit_events(action); +CREATE INDEX IF NOT EXISTS idx_audit_events_target ON audit_events(target_uri); +CREATE INDEX IF NOT EXISTS idx_audit_events_created ON audit_events(created_at); +CREATE INDEX IF NOT EXISTS idx_approval_gates_action ON approval_gates(action); +CREATE INDEX IF NOT EXISTS idx_approval_gates_status ON approval_gates(status); -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (3, datetime('now')); +`; +var MIGRATION_4 = ` +CREATE TABLE IF NOT EXISTS vector_index_entries ( + id TEXT PRIMARY KEY, + chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, + source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + model TEXT NOT NULL, + dimensions INTEGER NOT NULL, + vector_json TEXT NOT NULL, + vector_norm REAL NOT NULL, + source_uri TEXT, + source_ref TEXT, + revision TEXT, + hash TEXT, + start_offset INTEGER, + end_offset INTEGER, + token_count INTEGER, + status TEXT NOT NULL DEFAULT 'active', + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE(chunk_id, provider, model) +); -class ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum.create = createZodEnum; - -class ZodNativeEnum extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; +CREATE INDEX IF NOT EXISTS idx_vector_index_provider_model ON vector_index_entries(provider, model); +CREATE INDEX IF NOT EXISTS idx_vector_index_source_revision ON vector_index_entries(source_revision_id); +CREATE INDEX IF NOT EXISTS idx_vector_index_source_uri ON vector_index_entries(source_uri); +CREATE INDEX IF NOT EXISTS idx_vector_index_status ON vector_index_entries(status); -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (4, datetime('now')); +`; +var MIGRATION_5 = ` +CREATE TABLE IF NOT EXISTS reindex_queue ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + target_id TEXT NOT NULL, + source_uri TEXT, + reason TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + attempts INTEGER NOT NULL DEFAULT 0, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE(kind, target_id, reason) +); -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util.assertNever(effect); - } -} -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; +CREATE INDEX IF NOT EXISTS idx_reindex_queue_status ON reindex_queue(status); +CREATE INDEX IF NOT EXISTS idx_reindex_queue_kind_target ON reindex_queue(kind, target_id); +CREATE INDEX IF NOT EXISTS idx_reindex_queue_source_uri ON reindex_queue(source_uri); -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (5, datetime('now')); +`; +var MIGRATION_6 = ` +CREATE TABLE IF NOT EXISTS knowledge_machines ( + machine_id TEXT PRIMARY KEY, + hostname TEXT, + platform TEXT, + user_label TEXT, + workspace_home TEXT, + tailscale_dns TEXT, + tailscale_ips_json TEXT NOT NULL DEFAULT '[]', + ssh_target TEXT, + last_seen_at TEXT, + capabilities_json TEXT NOT NULL DEFAULT '{}', + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS knowledge_sync_snapshots ( + id TEXT PRIMARY KEY, + machine_id TEXT NOT NULL, + scope TEXT NOT NULL, + workspace_home TEXT NOT NULL, + sqlite_schema_version INTEGER NOT NULL, + artifact_root_uri TEXT NOT NULL, + content_hash TEXT NOT NULL, + tables_json TEXT NOT NULL, + artifact_hashes_json TEXT NOT NULL, + created_at TEXT NOT NULL +); -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS knowledge_sync_changes ( + id TEXT PRIMARY KEY, + origin_machine_id TEXT NOT NULL, + updated_by_machine_id TEXT NOT NULL, + entity_kind TEXT NOT NULL, + entity_id TEXT NOT NULL, + operation TEXT NOT NULL, + base_hash TEXT, + next_hash TEXT, + source_ref TEXT, + source_revision_id TEXT, + artifact_uri TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; +CREATE TABLE IF NOT EXISTS knowledge_sync_conflicts ( + id TEXT PRIMARY KEY, + entity_kind TEXT NOT NULL, + entity_id TEXT NOT NULL, + local_machine_id TEXT NOT NULL, + remote_machine_id TEXT NOT NULL, + local_hash TEXT, + remote_hash TEXT, + base_hash TEXT, + status TEXT NOT NULL, + resolution_strategy TEXT, + proposed_patch_uri TEXT, + approved_by TEXT, + resolved_at TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL +); -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = Symbol("zod_brand"); +CREATE INDEX IF NOT EXISTS idx_knowledge_machines_last_seen ON knowledge_machines(last_seen_at); +CREATE INDEX IF NOT EXISTS idx_sync_snapshots_machine_created ON knowledge_sync_snapshots(machine_id, created_at); +CREATE INDEX IF NOT EXISTS idx_sync_snapshots_hash ON knowledge_sync_snapshots(content_hash); +CREATE INDEX IF NOT EXISTS idx_sync_changes_entity ON knowledge_sync_changes(entity_kind, entity_id); +CREATE INDEX IF NOT EXISTS idx_sync_changes_origin ON knowledge_sync_changes(origin_machine_id); +CREATE INDEX IF NOT EXISTS idx_sync_changes_created ON knowledge_sync_changes(created_at); +CREATE INDEX IF NOT EXISTS idx_sync_conflicts_status ON knowledge_sync_conflicts(status); +CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON knowledge_sync_conflicts(entity_kind, entity_id); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (6, datetime('now')); +`; +var MIGRATION_7_TABLES_AND_INDEXES = ` +CREATE TABLE IF NOT EXISTS knowledge_sync_table_clocks ( + table_name TEXT NOT NULL, + machine_id TEXT NOT NULL, + logical_clock INTEGER NOT NULL DEFAULT 0, + high_water_hash TEXT, + high_water_bundle_id TEXT, + origin_machine_id TEXT, + updated_by_machine_id TEXT, + last_applied_at TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY(table_name, machine_id) +); -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -} +CREATE TABLE IF NOT EXISTS knowledge_sync_imports ( + bundle_id TEXT PRIMARY KEY, + source_machine_id TEXT NOT NULL, + target_machine_id TEXT NOT NULL, + direction TEXT NOT NULL, + status TEXT NOT NULL, + content_hash TEXT NOT NULL, + table_clocks_json TEXT NOT NULL, + tables_json TEXT NOT NULL, + generated_at TEXT NOT NULL, + applied_at TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}' +); -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; +CREATE INDEX IF NOT EXISTS idx_sync_changes_bundle ON knowledge_sync_changes(bundle_id); +CREATE INDEX IF NOT EXISTS idx_sync_changes_clock ON knowledge_sync_changes(entity_kind, logical_clock); +CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_machine ON knowledge_sync_table_clocks(machine_id); +CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_updated ON knowledge_sync_table_clocks(updated_at); +CREATE INDEX IF NOT EXISTS idx_sync_imports_source ON knowledge_sync_imports(source_machine_id, applied_at); +CREATE INDEX IF NOT EXISTS idx_sync_imports_target ON knowledge_sync_imports(target_machine_id, applied_at); +CREATE INDEX IF NOT EXISTS idx_sync_imports_status ON knowledge_sync_imports(status); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (7, datetime('now')); +`; +var MIGRATION_8_TABLES_AND_INDEXES = ` +CREATE INDEX IF NOT EXISTS idx_wiki_pages_lifecycle_status ON wiki_pages(status, valid_to); +CREATE INDEX IF NOT EXISTS idx_wiki_pages_last_verified ON wiki_pages(last_verified_at); +CREATE INDEX IF NOT EXISTS idx_wiki_pages_supersedes ON wiki_pages(supersedes); +CREATE INDEX IF NOT EXISTS idx_wiki_pages_superseded_by ON wiki_pages(superseded_by); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (8, datetime('now')); +`; +var MIGRATION_9_REBUILD_FTS = ` +BEGIN; + +CREATE TEMP TABLE _chunks_fts_backup AS + SELECT chunk_id, text, title, source_uri FROM chunks_fts; + +DROP TABLE chunks_fts; + +CREATE VIRTUAL TABLE chunks_fts USING fts5( + chunk_id UNINDEXED, + text, + title, + source_uri, + tokenize='${CHUNKS_FTS_TOKENIZE}' +); + +INSERT INTO chunks_fts (chunk_id, text, title, source_uri) + SELECT chunk_id, text, title, source_uri FROM _chunks_fts_backup; + +DROP TABLE _chunks_fts_backup; + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (9, datetime('now')); + +COMMIT; +`; +var MIGRATION_10_PROMOTION_INBOX = ` +CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + source_kind TEXT NOT NULL, + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'pending', + requires_approval INTEGER NOT NULL DEFAULT 0, + checks_json TEXT NOT NULL DEFAULT '{}', + idempotency_key TEXT NOT NULL UNIQUE, + duplicate_of TEXT, + approved_by TEXT, + promoted_record_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + reviewed_at TEXT, + promoted_at TEXT +); + +CREATE TABLE IF NOT EXISTS durable_knowledge_records ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + confidence REAL, + valid_from TEXT NOT NULL, + valid_to TEXT, + promoted_from_candidate_id TEXT NOT NULL UNIQUE + REFERENCES knowledge_promotion_candidates(id) ON DELETE RESTRICT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_status + ON knowledge_promotion_candidates(status, updated_at); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_kind_key + ON knowledge_promotion_candidates(record_kind, canonical_key); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_hash + ON knowledge_promotion_candidates(record_kind, content_hash); +CREATE INDEX IF NOT EXISTS idx_durable_records_kind_key + ON durable_knowledge_records(record_kind, canonical_key, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_hash + ON durable_knowledge_records(record_kind, content_hash, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_validity + ON durable_knowledge_records(status, valid_to); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (10, datetime('now')); +`; +function openKnowledgeDb(path) { + assertLocalCatalogMode("opening the local knowledge.db catalog"); + ensureParentDir(path); + const db = new Database(path); + db.exec("PRAGMA foreign_keys = ON;"); + db.exec("PRAGMA busy_timeout = 5000;"); + return db; +} +function openKnowledgeDbReadonly(path) { + assertLocalCatalogMode("reading the local knowledge.db catalog"); + return new Database(path, { readonly: true }); +} +function migrateKnowledgeDb(path) { + const db = openKnowledgeDb(path); + try { + db.exec(MIGRATION_1); + if (getSchemaVersion(db) < 2) + db.exec(MIGRATION_2); + if (getSchemaVersion(db) < 3) + db.exec(MIGRATION_3); + if (getSchemaVersion(db) < 4) + db.exec(MIGRATION_4); + if (getSchemaVersion(db) < 5) + db.exec(MIGRATION_5); + if (getSchemaVersion(db) < 6) + db.exec(MIGRATION_6); + if (needsMigration7(db)) + applyMigration7(db); + if (needsMigration8(db)) + applyMigration8(db); + if (needsMigration9(db)) + applyMigration9(db); + if (needsMigration10(db)) + applyMigration10(db); + return { path, schema_version: getSchemaVersion(db) }; + } finally { + db.close(); } } -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; +function getSchemaVersion(db) { + const row = db.query("SELECT MAX(version) AS version FROM schema_versions").get(); + return row?.version ?? 0; } -function custom(check, _params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); +function count(db, table) { + const row = db.query(`SELECT COUNT(*) AS n FROM ${table}`).get(); + return row?.n ?? 0; } -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: (arg) => ZodString.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), - date: (arg) => ZodDate.create({ ...arg, coerce: true }) -}; -var NEVER = INVALID; -var SCHEMA_IDS = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema = exports_external.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema = exports_external.string().datetime(); -var NonEmptyStringSchema = exports_external.string().trim().min(1); -var UriSchema = NonEmptyStringSchema.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema = exports_external.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema = exports_external.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema = exports_external.record(exports_external.unknown()); -var TagsSchema = exports_external.array(exports_external.string().min(1)).default([]); -var OptionalTimestampSchema = TimestampSchema.nullable().optional(); -var TerminalStatuses = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema = exports_external.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema(schema) { - return exports_external.object({ - schema: exports_external.literal(schema), - id: exports_external.string().min(1), - createdAt: TimestampSchema, - updatedAt: OptionalTimestampSchema, - metadata: MetadataSchema.optional() - }).strict(); +function quoteIdentifier(identifier) { + return `"${identifier.replaceAll('"', '""')}"`; } -var ContractEnvelopeSchema = exports_external.object({ - schema: SchemaIdSchema, - id: exports_external.string().min(1), - createdAt: TimestampSchema, - updatedAt: OptionalTimestampSchema, - metadata: MetadataSchema.optional() -}).strict(); -var ActorKindSchema = exports_external.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema = contractBaseSchema(SCHEMA_IDS.actorRef).extend({ - kind: ActorKindSchema, - name: exports_external.string().min(1).optional(), - provider: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - machineId: exports_external.string().min(1).optional(), - capabilities: exports_external.array(exports_external.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema = exports_external.object({ - kind: ActorKindSchema, - id: exports_external.string().min(1), - name: exports_external.string().min(1).optional(), - provider: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - machineId: exports_external.string().min(1).optional() -}).strict(); -var ResourceKindSchema = exports_external.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema = contractBaseSchema(SCHEMA_IDS.resourceRef).extend({ - kind: ResourceKindSchema, - name: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema = exports_external.object({ - kind: ResourceKindSchema, - id: exports_external.string().min(1), - name: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema = exports_external.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema = exports_external.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema = contractBaseSchema(SCHEMA_IDS.evidenceRef).extend({ - kind: EvidenceKindSchema, - uri: UriSchema, - sha256: Sha256DigestSchema.optional(), - summary: exports_external.string().min(1).optional(), - contentType: exports_external.string().min(1).optional(), - sizeBytes: exports_external.number().int().nonnegative().optional(), - redaction: RedactionStateSchema.default("unknown"), - producer: ActorPointerSchema.optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - tags: TagsSchema -}).strict(); -var EvidencePointerSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: EvidenceKindSchema.optional(), - uri: UriSchema.optional(), - sha256: Sha256DigestSchema.optional(), - summary: exports_external.string().min(1).optional() -}).strict(); -var CostEstimateSchema = contractBaseSchema(SCHEMA_IDS.costEstimate).extend({ - currency: exports_external.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external.number().int().nonnegative(), - provider: exports_external.string().min(1).optional(), - model: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - promptTokens: exports_external.number().int().nonnegative().optional(), - completionTokens: exports_external.number().int().nonnegative().optional(), - totalTokens: exports_external.number().int().nonnegative().optional(), - basis: exports_external.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); +function tableExists(db, table) { + const row = db.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get(table); + return Boolean(row); +} +function columnExists(db, table, column) { + if (!tableExists(db, table)) + return false; + const columns = db.query(`PRAGMA table_info(${quoteIdentifier(table)})`).all(); + return columns.some((row) => row.name === column); +} +function ensureColumn(db, table, column, definition) { + if (!columnExists(db, table, column)) { + db.exec(`ALTER TABLE ${quoteIdentifier(table)} ADD COLUMN ${quoteIdentifier(column)} ${definition};`); } -}); -var DecisionStatusSchema = exports_external.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.decisionEnvelope).extend({ - decisionType: exports_external.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema, - actor: ActorPointerSchema.optional(), - traceId: exports_external.string().min(1).optional(), - inputHash: HashStringSchema.optional(), - policyBundleId: exports_external.string().min(1).optional(), - selected: exports_external.array(ResourcePointerSchema).default([]), - skipped: exports_external.array(ResourcePointerSchema).default([]), - reason: exports_external.string().min(1), - obligations: exports_external.array(exports_external.string().min(1)).default([]), - redactions: exports_external.array(exports_external.string().min(1)).default([]), - costEstimate: CostEstimateSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); +} +function needsMigration7(db) { + return getSchemaVersion(db) < 7 || !columnExists(db, "knowledge_sync_changes", "logical_clock") || !columnExists(db, "knowledge_sync_changes", "bundle_id") || !tableExists(db, "knowledge_sync_table_clocks") || !tableExists(db, "knowledge_sync_imports"); +} +function applyMigration7(db) { + if (!tableExists(db, "knowledge_sync_changes")) + db.exec(MIGRATION_6); + ensureColumn(db, "knowledge_sync_changes", "logical_clock", "INTEGER NOT NULL DEFAULT 0"); + ensureColumn(db, "knowledge_sync_changes", "bundle_id", "TEXT"); + db.exec(MIGRATION_7_TABLES_AND_INDEXES); +} +function needsMigration8(db) { + return getSchemaVersion(db) < 8 || !columnExists(db, "wiki_pages", "valid_from") || !columnExists(db, "wiki_pages", "valid_to") || !columnExists(db, "wiki_pages", "supersedes") || !columnExists(db, "wiki_pages", "superseded_by") || !columnExists(db, "wiki_pages", "confidence") || !columnExists(db, "wiki_pages", "last_verified_at"); +} +function applyMigration8(db) { + if (!tableExists(db, "wiki_pages")) + db.exec(MIGRATION_1); + ensureColumn(db, "wiki_pages", "valid_from", "TEXT"); + ensureColumn(db, "wiki_pages", "valid_to", "TEXT"); + ensureColumn(db, "wiki_pages", "supersedes", "TEXT"); + ensureColumn(db, "wiki_pages", "superseded_by", "TEXT"); + ensureColumn(db, "wiki_pages", "confidence", "REAL"); + ensureColumn(db, "wiki_pages", "last_verified_at", "TEXT"); + db.exec(` + UPDATE wiki_pages + SET valid_from = COALESCE(valid_from, created_at), + last_verified_at = COALESCE(last_verified_at, updated_at), + confidence = COALESCE(confidence, 0.8) + WHERE valid_from IS NULL OR last_verified_at IS NULL OR confidence IS NULL; + `); + db.exec(MIGRATION_8_TABLES_AND_INDEXES); +} +function ftsUsesDiacriticFolding(db) { + const row = db.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts"); + return Boolean(row?.sql && row.sql.includes("remove_diacritics")); +} +function needsMigration9(db) { + if (!tableExists(db, "chunks_fts")) + return false; + return getSchemaVersion(db) < 9 || !ftsUsesDiacriticFolding(db); +} +function applyMigration9(db) { + if (!tableExists(db, "chunks_fts")) + return; + if (ftsUsesDiacriticFolding(db)) { + db.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));"); + return; } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); + db.exec(MIGRATION_9_REBUILD_FTS); +} +function needsMigration10(db) { + return getSchemaVersion(db) < 10 || !tableExists(db, "knowledge_promotion_candidates") || !tableExists(db, "durable_knowledge_records"); +} +function applyMigration10(db) { + db.exec(MIGRATION_10_PROMOTION_INBOX); +} +function getKnowledgeDbStats(path) { + const db = openKnowledgeDb(path); + try { + return { + schema_version: getSchemaVersion(db), + sources: count(db, "sources"), + source_revisions: count(db, "source_revisions"), + chunks: count(db, "chunks"), + wiki_pages: count(db, "wiki_pages"), + citations: count(db, "citations"), + indexes: count(db, "knowledge_indexes"), + runs: count(db, "runs"), + run_events: count(db, "run_events"), + redaction_findings: count(db, "redaction_findings"), + audit_events: count(db, "audit_events"), + approval_gates: count(db, "approval_gates"), + storage_objects: count(db, "storage_objects"), + embeddings: count(db, "chunk_embeddings"), + vector_entries: count(db, "vector_index_entries"), + reindex_queue: count(db, "reindex_queue"), + knowledge_machines: count(db, "knowledge_machines"), + sync_snapshots: count(db, "knowledge_sync_snapshots"), + sync_changes: count(db, "knowledge_sync_changes"), + sync_conflicts: count(db, "knowledge_sync_conflicts"), + sync_table_clocks: count(db, "knowledge_sync_table_clocks"), + sync_imports: count(db, "knowledge_sync_imports"), + promotion_candidates: count(db, "knowledge_promotion_candidates"), + durable_records: count(db, "durable_knowledge_records") + }; + } finally { + db.close(); } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema = contractBaseSchema(SCHEMA_IDS.capabilityCard).extend({ - kind: exports_external.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external.string().min(1), - version: exports_external.string().min(1).optional(), - status: exports_external.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external.array(exports_external.string().min(1)).default([]), - limitations: exports_external.array(exports_external.string().min(1)).default([]), - riskLevel: exports_external.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict(); -var ProviderModeSchema = exports_external.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema = exports_external.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema = exports_external.object({ - refName: NonEmptyStringSchema, - requiredForModes: exports_external.array(ProviderModeSchema).min(1), - allowedSecretInputs: exports_external.array(exports_external.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema, - revocationCheck: exports_external.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema = exports_external.object({ - operation: NonEmptyStringSchema, - supportedModes: exports_external.array(ProviderModeSchema).min(1), - sideEffectClass: ProviderSideEffectClassSchema, - requiresApproval: exports_external.boolean().default(false), - requiresIdempotencyKey: exports_external.boolean().default(false), - requiresSandboxEvidence: exports_external.boolean().default(false), - requiresRollbackOrRevocation: exports_external.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema.optional(), - noSideEffectSmoke: NonEmptyStringSchema.optional(), - reconciliation: NonEmptyStringSchema.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema = exports_external.object({ - providerId: NonEmptyStringSchema, - appId: NonEmptyStringSchema, - adapterId: NonEmptyStringSchema, - ownerPackage: NonEmptyStringSchema, - modes: exports_external.array(ProviderModeSchema).min(1), - defaultMode: ProviderModeSchema, - credentialRequirements: exports_external.array(CredentialRequirementSchema).default([]), - operations: exports_external.array(ProviderOperationCardSchema).min(1), - rateLimitPosture: NonEmptyStringSchema, - costPosture: NonEmptyStringSchema.optional(), - auditEvents: exports_external.array(NonEmptyStringSchema).default([]), - redactionRules: exports_external.array(NonEmptyStringSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema = exports_external.object({ - appId: NonEmptyStringSchema, - repo: NonEmptyStringSchema, - priority: exports_external.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external.array(NonEmptyStringSchema).min(1), - firstOperations: exports_external.array(NonEmptyStringSchema).min(1), - blockedUntil: exports_external.array(NonEmptyStringSchema).default([]) -}).strict(); -var ProviderLiveModeStandardSchema = contractBaseSchema(SCHEMA_IDS.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema, - version: NonEmptyStringSchema, - modes: exports_external.array(ProviderModeSchema).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external.array(NonEmptyStringSchema).min(1), - liveMutationGate: exports_external.object({ - requiredMode: exports_external.literal("live_mutating"), - requiredChecks: exports_external.array(NonEmptyStringSchema).min(1), - forbiddenBypassSignals: exports_external.array(NonEmptyStringSchema).min(1), - disabledLiveSmoke: NonEmptyStringSchema - }).strict(), - noSideEffectSmoke: exports_external.object({ - requiredForModes: exports_external.array(ProviderModeSchema).min(1), - commandEvidence: exports_external.array(NonEmptyStringSchema).min(1), - secretOutputScan: exports_external.boolean().default(true) - }).strict(), - credentialPolicy: exports_external.object({ - acceptedInputs: exports_external.array(exports_external.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external.literal(false), - missingCredentialBehavior: exports_external.literal("fail_closed"), - revocationCheckRequired: exports_external.boolean().default(true) - }).strict(), - operationCards: exports_external.array(ProviderCapabilityCardSchema).min(1), - firstAdoptionTargets: exports_external.array(ProviderLiveModeTargetSchema).min(1), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema = exports_external.object({ - id: exports_external.string().min(1), - title: exports_external.string().min(1).optional(), - summary: exports_external.string().min(1), - text: exports_external.string().optional(), - tokens: exports_external.number().int().nonnegative().optional(), - source: EvidencePointerSchema, - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict(); -var ContextPackSchema = contractBaseSchema(SCHEMA_IDS.contextPack).extend({ - objective: exports_external.string().min(1), - budget: exports_external.object({ - maxTokens: exports_external.number().int().positive().optional(), - maxBytes: exports_external.number().int().positive().optional() - }).strict().optional(), - items: exports_external.array(ContextPackItemSchema).default([]), - citations: exports_external.array(EvidencePointerSchema).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external.array(exports_external.string().min(1)).default([]), - redactions: exports_external.array(exports_external.string().min(1)).default([]), - conflicts: exports_external.array(exports_external.string().min(1)).default([]), - uncertainty: exports_external.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema = NonEmptyStringSchema.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema = exports_external.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema = exports_external.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema = exports_external.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema = exports_external.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema = contractBaseSchema(SCHEMA_IDS.integrationRef).extend({ - kind: ProjectIntegrationKindSchema, - name: exports_external.string().min(1), - projectId: ProjectSlugSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - uri: UriSchema.optional(), - enabled: exports_external.boolean().default(true), - readOnly: exports_external.boolean().default(true), - capabilities: exports_external.array(exports_external.string().min(1)).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - config: MetadataSchema.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema = exports_external.object({ - schemaRoot: RelativeProjectPathSchema.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema.default("documents"), - reportsDir: RelativeProjectPathSchema.default("reports"), - evidenceDir: RelativeProjectPathSchema.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema = contractBaseSchema(SCHEMA_IDS.projectManifest).extend({ - projectId: ProjectSlugSchema, - slug: ProjectSlugSchema, - name: exports_external.string().min(1), - summary: exports_external.string().min(1).optional(), - status: ProjectStatusSchema.default("active"), - classification: ProjectClassificationSchema.default("private"), - owner: ActorPointerSchema.optional(), - layout: ProjectLayoutSchema.default({}), - integrations: exports_external.array(IntegrationRefSchema).default([]), - renderManifests: exports_external.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema = exports_external.enum(["local", "package", "provider", "url"]); -var RenderImportSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: RenderImportKindSchema, - specifier: exports_external.string().min(1), - path: RelativeProjectPathSchema.optional(), - packageName: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - provider: ProjectIntegrationKindSchema.optional(), - schemaId: SchemaIdSchema.optional(), - integrity: HashStringSchema.optional(), - resourceRef: ResourcePointerSchema.optional(), - optional: exports_external.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema = exports_external.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema = exports_external.object({ - id: exports_external.string().min(1), - title: exports_external.string().min(1), - kind: RenderViewKindSchema, - default: exports_external.boolean().default(false), - entry: RelativeProjectPathSchema.optional(), - imports: exports_external.array(RenderImportSchema).default([]), - panelRefs: exports_external.array(ResourcePointerSchema).default([]), - dataRefs: exports_external.array(ResourcePointerSchema).default([]), - layout: MetadataSchema.optional() -}).strict(); -var RenderManifestSchema = contractBaseSchema(SCHEMA_IDS.renderManifest).extend({ - projectId: ProjectSlugSchema, - name: exports_external.string().min(1), - version: exports_external.string().min(1), - manifestPath: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), - renderer: exports_external.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external.array(RenderViewSchema).min(1), - imports: exports_external.array(RenderImportSchema).default([]), - theme: MetadataSchema.optional(), - compatibility: exports_external.object({ - minProjectsVersion: exports_external.string().min(1).optional(), - minContractsVersion: exports_external.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema = exports_external.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema = exports_external.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema = exports_external.object({ - id: exports_external.string().min(1), - label: exports_external.string().min(1), - value: exports_external.union([exports_external.string(), exports_external.number(), exports_external.boolean()]), - unit: exports_external.string().min(1).optional(), - status: exports_external.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict(); -var ProjectPanelItemSchema = exports_external.object({ - id: exports_external.string().min(1), - title: exports_external.string().min(1), - summary: exports_external.string().min(1).optional(), - status: exports_external.string().min(1).optional(), - priority: exports_external.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema.optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - metadata: MetadataSchema.optional() -}).strict(); -var ProjectRenderFragmentSchema = exports_external.object({ - renderer: exports_external.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external.string().min(1).optional(), - entry: RelativeProjectPathSchema.optional(), - imports: exports_external.array(RenderImportSchema).default([]), - spec: MetadataSchema.default({}) -}).strict(); -var ProjectPanelSchema = contractBaseSchema(SCHEMA_IDS.projectPanel).extend({ - projectId: ProjectSlugSchema, - provider: exports_external.object({ - kind: ProjectIntegrationKindSchema, - id: exports_external.string().min(1), - name: exports_external.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema.optional(), - externalId: NonEmptyStringSchema.optional() - }).strict(), - kind: ProjectPanelKindSchema, - title: exports_external.string().min(1), - summary: exports_external.string().min(1).optional(), - state: ProjectPanelStateSchema.default("ready"), - stateReason: exports_external.string().min(1).optional(), - generatedAt: TimestampSchema, - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external.array(ProjectPanelMetricSchema).default([]), - items: exports_external.array(ProjectPanelItemSchema).default([]), - actions: exports_external.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - renderFragment: ProjectRenderFragmentSchema.optional(), - warnings: exports_external.array(exports_external.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema = contractBaseSchema(SCHEMA_IDS.projectSnapshot).extend({ - projectId: ProjectSlugSchema, - generatedAt: TimestampSchema, - status: ContractStatusSchema.default("unknown"), - manifestRef: ResourcePointerSchema, - renderManifestRef: ResourcePointerSchema.optional(), - panels: exports_external.array(ProjectPanelSchema).default([]), - contextPacks: exports_external.array(ContextPackSchema).default([]), - proofBundleRefs: exports_external.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - warnings: exports_external.array(exports_external.string().min(1)).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: exports_external.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external.boolean().default(true), - command: exports_external.string().min(1).optional(), - expected: exports_external.string().min(1).optional(), - timeoutMs: exports_external.number().int().positive().optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema = contractBaseSchema(SCHEMA_IDS.validationPlan).extend({ - objective: exports_external.string().min(1), - subject: ResourcePointerSchema.optional(), - checks: exports_external.array(ValidationCheckSchema).min(1), - verifier: ActorPointerSchema.optional(), - requiredEvidenceKinds: exports_external.array(EvidenceKindSchema).default([]) -}).strict(); -var ScaffoldTypeSchema = exports_external.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema = exports_external.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema = exports_external.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema = exports_external.object({ - key: exports_external.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external.string().min(1), - required: exports_external.boolean().default(false), - ["secret"]: exports_external.boolean().default(false), - group: exports_external.string().min(1).optional(), - default: exports_external.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema = exports_external.object({ - name: exports_external.string().min(1), - command: exports_external.string().min(1), - description: exports_external.string().min(1).optional(), - required: exports_external.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema = exports_external.object({ - packageManager: exports_external.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external.array(exports_external.string().min(1)).default([]), - requiredFiles: exports_external.array(exports_external.string().min(1)).default([]), - requiredDirectories: exports_external.array(exports_external.string().min(1)).default([]), - optionalDirectories: exports_external.array(exports_external.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema = contractBaseSchema(SCHEMA_IDS.scaffoldManifest).extend({ - name: exports_external.string().min(1), - version: exports_external.string().min(1), - summary: exports_external.string().min(1), - type: ScaffoldTypeSchema, - status: ScaffoldStatusSchema.default("draft"), - capabilities: exports_external.array(ScaffoldCapabilitySchema).default([]), - techStack: exports_external.array(exports_external.string().min(1)).default([]), - tags: TagsSchema, - source: ResourcePointerSchema.optional(), - output: ScaffoldOutputShapeSchema, - env: exports_external.array(ScaffoldEnvVarSchema).default([]), - scripts: exports_external.array(ScaffoldScriptSchema).default([]), - validationChecks: exports_external.array(ValidationCheckSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema = exports_external.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema = contractBaseSchema(SCHEMA_IDS.scaffoldInstallRecord).extend({ - scaffoldId: exports_external.string().min(1), - scaffoldVersion: exports_external.string().min(1).optional(), - manifestRef: ResourcePointerSchema.optional(), - target: ResourcePointerSchema, - status: ScaffoldInstallStatusSchema, - installedAt: TimestampSchema.optional(), - installer: ActorPointerSchema.optional(), - packageManager: exports_external.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema.optional(), - generatedFiles: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - proofBundleRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema = exports_external.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema = exports_external.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema = exports_external.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema = exports_external.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema = NonEmptyStringSchema.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema = exports_external.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema = exports_external.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema = exports_external.object({ - transport: exports_external.enum(["http", "stdio"]).default("http"), - bin: exports_external.string().min(1).optional(), - url: UriSchema.optional() -}).strict(); -var AppHttpSurfaceSchema = exports_external.object({ - healthPath: exports_external.string().min(1).default("/health"), - port: exports_external.number().int().positive().optional(), - baseUrl: UriSchema.optional() -}).strict(); -var AppSurfacesSchema = exports_external.object({ - bins: exports_external.array(exports_external.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema.optional(), - http: AppHttpSurfaceSchema.optional() -}).strict(); -var AppSchema = contractBaseSchema(SCHEMA_IDS.app).extend({ - appId: AppIdSchema, - npmName: NpmPackageNameSchema, - repoFolder: AppIdSchema, - githubUrl: GithubUrlSchema, - projectSlug: ProjectSlugSchema, - surfaces: AppSurfacesSchema.default({}), - lifecycle: AppLifecycleSchema, - releaseChannel: ReleaseChannelSchema.default("stable"), - summary: exports_external.string().min(1).optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema = exports_external.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema = contractBaseSchema(SCHEMA_IDS.release).extend({ - appId: AppIdSchema, - package: NpmPackageNameSchema, - version: SemverSchema, - gitSha: GitShaSchema, - publishedAt: TimestampSchema, - publishPath: PublishPathSchema, - changelogRef: ResourcePointerSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema = exports_external.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema = exports_external.object({ - cliVersion: exports_external.string().min(1).optional(), - mcpHealth: exports_external.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema = contractBaseSchema(SCHEMA_IDS.rolloutRecord).extend({ - appId: AppIdSchema, - package: NpmPackageNameSchema, - version: SemverSchema, - machine: NonEmptyStringSchema, - action: RolloutActionSchema, - result: ContractStatusSchema, - verifiedBy: RolloutVerificationSchema.optional(), - at: TimestampSchema, - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema = exports_external.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema = exports_external.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema = exports_external.object({ - channel: AnnouncementChannelKindSchema, - status: AnnouncementDeliveryStatusSchema, - deliveredAt: TimestampSchema.optional(), - detail: exports_external.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema = contractBaseSchema(SCHEMA_IDS.announcement).extend({ - campaignId: NonEmptyStringSchema, - appId: AppIdSchema.optional(), - releaseRef: ResourcePointerSchema.optional(), - channels: exports_external.array(AnnouncementChannelSchema).min(1), - audienceRef: ResourcePointerSchema, - sentAt: TimestampSchema -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema = exports_external.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema = exports_external.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema = exports_external.union([exports_external.string(), exports_external.number(), exports_external.boolean()]); -var AudiencePredicateSchema = exports_external.object({ - kind: AudiencePredicateKindSchema, - key: exports_external.string().min(1).optional(), - op: AudiencePredicateOpSchema.default("eq"), - value: AudiencePredicateValueSchema.optional(), - values: exports_external.array(AudiencePredicateValueSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema = exports_external.object({ - match: exports_external.enum(["all", "any"]).default("all"), - predicates: exports_external.array(AudiencePredicateSchema).min(1) -}).strict(); -var ConsentPolicySchema = exports_external.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema = contractBaseSchema(SCHEMA_IDS.audience).extend({ - audienceId: AppIdSchema, - name: NonEmptyStringSchema, - definition: AudienceDefinitionSchema, - consentPolicy: ConsentPolicySchema, - suppressionSyncedAt: OptionalTimestampSchema -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema = exports_external.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema = exports_external.object({ - id: exports_external.string().min(1), - provider: AppCloudProviderSchema, - kind: exports_external.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external.string().min(1), - region: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - machineScoped: exports_external.boolean().default(false) -}).strict(); -var AppCloudManifestSchema = contractBaseSchema(SCHEMA_IDS.appCloudManifest).extend({ - packageName: exports_external.string().min(1), - packageVersion: exports_external.string().min(1).optional(), - appId: exports_external.string().min(1), - repository: ResourcePointerSchema.optional(), - storageMode: exports_external.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external.array(AppCloudResourceSchema).default([]), - localCache: exports_external.object({ - path: exports_external.string().min(1).optional(), - pullMode: exports_external.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external.array(exports_external.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES]), - dependencies: exports_external.array(exports_external.string().min(1)).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema = exports_external.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema = exports_external.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: NoCloudCheckKindSchema, - severity: NoCloudFindingSeveritySchema, - path: exports_external.string().min(1).optional(), - packageName: exports_external.string().min(1).optional(), - pattern: exports_external.string().min(1), - message: exports_external.string().min(1), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict(); -var NoCloudCheckResultSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: NoCloudCheckKindSchema, - status: ContractStatusSchema, - target: exports_external.string().min(1), - command: exports_external.string().min(1).optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - findings: exports_external.array(NoCloudFindingSchema).default([]) -}).strict(); -var NoCloudEvidencePackSchema = contractBaseSchema(SCHEMA_IDS.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema, - packageName: exports_external.string().min(1).optional(), - packageVersion: exports_external.string().min(1).optional(), - generatedBy: ActorPointerSchema.optional(), - scanMode: exports_external.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema, - verdict: exports_external.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema.optional(), - checks: exports_external.array(NoCloudCheckResultSchema).min(1), - findings: exports_external.array(NoCloudFindingSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check) => check.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check) => check.status !== "succeeded")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check) => check.status === "failed")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check, index) => { - const checkBlockingFindings = check.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema = exports_external.object({ - checkId: exports_external.string().min(1), - status: ContractStatusSchema, - summary: exports_external.string().min(1).optional(), - startedAt: OptionalTimestampSchema, - finishedAt: OptionalTimestampSchema, - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict(); -var ProofBundleSchema = contractBaseSchema(SCHEMA_IDS.proofBundle).extend({ - subject: ResourcePointerSchema, - validationPlanRef: ResourcePointerSchema.optional(), - status: ContractStatusSchema, - verdict: exports_external.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external.array(ProofCheckResultSchema).default([]), - verifier: ActorPointerSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - residualRisks: exports_external.array(exports_external.string().min(1)).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check, index) => { - if (check.status !== "succeeded") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check) => check.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check) => check.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema = contractBaseSchema(SCHEMA_IDS.workRun).extend({ - objective: exports_external.string().min(1), - status: ContractStatusSchema, - actor: ActorPointerSchema, - traceId: exports_external.string().min(1).optional(), - startedAt: OptionalTimestampSchema, - finishedAt: OptionalTimestampSchema, - constraints: exports_external.array(exports_external.string().min(1)).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - decisions: exports_external.array(DecisionEnvelopeSchema).default([]), - costEstimates: exports_external.array(CostEstimateSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - validationPlanRefs: exports_external.array(ResourcePointerSchema).default([]), - proofBundleRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema = exports_external.object({ - id: exports_external.string().min(1), - at: TimestampSchema, - kind: exports_external.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external.string().min(1), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - costEstimate: CostEstimateSchema.optional() -}).strict(); -var AgentTrajectorySchema = contractBaseSchema(SCHEMA_IDS.agentTrajectory).extend({ - actor: ActorPointerSchema, - workRunRef: ResourcePointerSchema.optional(), - events: exports_external.array(TrajectoryEventSchema).default([]), - outcome: exports_external.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION = "v1"; -var RepoClassSchema = exports_external.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema = exports_external.enum(DEPLOYMENT_MODES); -var ServiceSurfaceStatusSchema = exports_external.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema = exports_external.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema = exports_external.object({ - method: exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external.boolean().default(false), - description: exports_external.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: exports_external.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external.boolean().default(true), - command: exports_external.string().min(1).optional(), - evidenceRef: EvidencePointerSchema.optional(), - status: exports_external.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema = exports_external.object({ - name: exports_external.string().min(1), - status: ServiceSurfaceStatusSchema, - bin: exports_external.string().min(1).optional(), - mcpBin: exports_external.string().min(1).optional(), - authMode: ServiceAuthModeSchema, - deploymentModes: exports_external.array(DeploymentModeSchema).min(1), - health: ServiceEndpointSchema.optional(), - readiness: ServiceEndpointSchema.optional(), - version: ServiceEndpointSchema.optional(), - apiBasePath: exports_external.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external.string().min(1).optional(), - readinessGates: exports_external.array(DeploymentReadinessGateSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES = ["local", "cloud"]; -var StorageModeSchema = exports_external.enum(STORAGE_MODES); -var DEPRECATED_STORAGE_MODE_ALIASES = ["remote", "hybrid", "self_hosted"]; -var AppNameSchema = exports_external.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName(name) { - return ALLOWED_BIN_SUFFIXES.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema = exports_external.object({ - mode: StorageModeSchema, - envPrefix: exports_external.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema = exports_external.object({ - $schema: exports_external.string().min(1).optional(), - schema: exports_external.literal(SCHEMA_IDS.serviceContract), - name: AppNameSchema, - class: RepoClassSchema, - contractVersion: exports_external.literal(SERVICE_CONTRACT_VERSION), - kitVersion: exports_external.string().min(1), - description: exports_external.string().min(1).optional(), - bins: exports_external.array(exports_external.string().min(1)).default([]), - storage: StorageContractSchema.optional(), - deploymentModes: exports_external.array(DeploymentModeSchema).default(["local"]), - serviceSurfaces: exports_external.array(ServiceSurfaceSchema).default([]), - metadata: MetadataSchema.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor(value.name)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } - } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); - } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } - } - } -}); -var HealthResponseSchema = exports_external.object({ - status: exports_external.enum(["ok", "degraded", "unavailable"]), - version: exports_external.string().min(1), - mode: StorageModeSchema -}).strict(); -var ReadyResponseSchema = exports_external.object({ - ready: exports_external.boolean(), - reason: exports_external.string().min(1).optional() -}).strict(); -var VersionResponseSchema = exports_external.object({ - version: exports_external.string().min(1) -}).strict(); -var CommsSeveritySchema = exports_external.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema = exports_external.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); -var COMMS_SEVERITY_TAGS = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema = exports_external.enum(COMMS_SEVERITY_TAGS); -var CommsScopeSchema = exports_external.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.commsEventEnvelope).extend({ - type: CommsEventTypeSchema, - severity: CommsSeveritySchema, - scope: CommsScopeSchema, - summary: exports_external.string().min(1).optional(), - source: ActorPointerSchema.optional(), - affected_packages: exports_external.array(NonEmptyStringSchema).default([]), - affected_machines: exports_external.array(NonEmptyStringSchema).default([]), - action_required: exports_external.boolean().default(false), - ack_by: TimestampSchema.optional(), - dedupe_key: NonEmptyStringSchema, - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); - } - } -}); -var CommsChannelClassSchema = exports_external.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema = exports_external.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema = NonEmptyStringSchema.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); -var CommsChannelMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsChannelMetadata).extend({ - class: CommsChannelClassSchema, - noise: CommsChannelNoiseSchema.optional(), - owner: NonEmptyStringSchema.optional(), - until: CommsUntilHorizonSchema.optional(), - successor: NonEmptyStringSchema.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); - } - } -}); -var COMMS_SEVERITY_TAG_INFO = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema, - envelope: CommsEventEnvelopeSchema -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] - }); - } - } -}); -var ContractSchemaRegistry = { - [SCHEMA_IDS.actorRef]: ActorRefSchema, - [SCHEMA_IDS.resourceRef]: ResourceRefSchema, - [SCHEMA_IDS.evidenceRef]: EvidenceRefSchema, - [SCHEMA_IDS.workRun]: WorkRunSchema, - [SCHEMA_IDS.decisionEnvelope]: DecisionEnvelopeSchema, - [SCHEMA_IDS.costEstimate]: CostEstimateSchema, - [SCHEMA_IDS.capabilityCard]: CapabilityCardSchema, - [SCHEMA_IDS.providerLiveModeStandard]: ProviderLiveModeStandardSchema, - [SCHEMA_IDS.contextPack]: ContextPackSchema, - [SCHEMA_IDS.integrationRef]: IntegrationRefSchema, - [SCHEMA_IDS.projectManifest]: ProjectManifestSchema, - [SCHEMA_IDS.projectPanel]: ProjectPanelSchema, - [SCHEMA_IDS.projectSnapshot]: ProjectSnapshotSchema, - [SCHEMA_IDS.renderManifest]: RenderManifestSchema, - [SCHEMA_IDS.agentTrajectory]: AgentTrajectorySchema, - [SCHEMA_IDS.validationPlan]: ValidationPlanSchema, - [SCHEMA_IDS.proofBundle]: ProofBundleSchema, - [SCHEMA_IDS.scaffoldManifest]: ScaffoldManifestSchema, - [SCHEMA_IDS.scaffoldInstallRecord]: ScaffoldInstallRecordSchema, - [SCHEMA_IDS.appCloudManifest]: AppCloudManifestSchema, - [SCHEMA_IDS.noCloudEvidencePack]: NoCloudEvidencePackSchema, - [SCHEMA_IDS.serviceContract]: ServiceContractManifestSchema, - [SCHEMA_IDS.commsEventEnvelope]: CommsEventEnvelopeSchema, - [SCHEMA_IDS.commsChannelMetadata]: CommsChannelMetadataSchema, - [SCHEMA_IDS.commsMessageMetadata]: CommsMessageMetadataSchema, - [SCHEMA_IDS.app]: AppSchema, - [SCHEMA_IDS.release]: ReleaseSchema, - [SCHEMA_IDS.rolloutRecord]: RolloutRecordSchema, - [SCHEMA_IDS.announcement]: AnnouncementSchema, - [SCHEMA_IDS.audience]: AudienceSchema -}; -function normalizeStorageMode(value) { - const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); -} -function envToken(name) { - return name.toUpperCase().replace(/-/g, "_"); -} -function defaultCloudBaseUrl(name) { - return `https://${name}.hasna.xyz`; -} -function clientTransportEnvKeys(name) { - const envSegment = envToken(name); - return { - modeKeys: [ - `HASNA_${envSegment}_STORAGE_MODE`, - `HASNA_${envSegment}_MODE`, - `${envSegment}_STORAGE_MODE`, - `${envSegment}_MODE` - ], - apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], - apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] - }; -} -function firstEnv2(env, keys) { - for (const key of keys) { - const value = env[key]?.trim(); - if (value) - return { key, value }; - } - return null; -} -function toV1BaseUrl(apiUrl) { - const url = new URL(apiUrl); - if (url.protocol !== "http:" && url.protocol !== "https:") { - throw new Error("API URL must use http or https."); - } - let path = url.pathname.replace(/\/+$/, ""); - if (path.endsWith("/v1")) - path = path.slice(0, -"/v1".length); - url.pathname = `${path}/v1`; - url.search = ""; - url.hash = ""; - return url.toString().replace(/\/+$/, ""); -} -function resolveClientTransport(name, env = process.env) { - const keys = clientTransportEnvKeys(name); - const modeHit = firstEnv2(env, keys.modeKeys); - const urlHit = firstEnv2(env, keys.apiUrlKeys); - const keyHit = firstEnv2(env, keys.apiKeyKeys); - let mode = "local"; - let deprecatedAlias = null; - let modeSource = "default"; - const warnings = []; - if (modeHit) { - const normalized = normalizeStorageMode(modeHit.value); - mode = normalized.mode; - deprecatedAlias = normalized.deprecatedAlias; - modeSource = modeHit.key; - if (deprecatedAlias) { - warnings.push(`Deprecated mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Prefer ${keys.modeKeys[0]}=cloud.`); - } - } else if (urlHit && keyHit) { - mode = "cloud"; - modeSource = `${urlHit.key}+${keyHit.key}`; - } - if (mode === "local") { - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: Boolean(keyHit), - apiKeySource: keyHit ? keyHit.key : null, - misconfigured: false, - warning: warnings.length > 0 ? warnings.join(" ") : null - }; - } - if (!keyHit) { - warnings.push(`${modeSource}=cloud but no API key is set (${keys.apiKeyKeys[0]}). Refusing to route to cloud; using local store. Set ${keys.apiKeyKeys[0]} to enable the cloud client.`); - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: false, - apiKeySource: null, - misconfigured: true, - warning: warnings.join(" ") - }; - } - const rawUrl = urlHit?.value ?? defaultCloudBaseUrl(name); - const apiUrlSource = urlHit ? urlHit.key : "default"; - let baseUrl; - try { - baseUrl = toV1BaseUrl(rawUrl); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - warnings.push(`Invalid API URL from ${apiUrlSource}: ${message}. Using local store.`); - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: true, - apiKeySource: keyHit.key, - misconfigured: true, - warning: warnings.join(" ") - }; - } - return { - transport: "cloud-http", - mode, - deprecatedAlias, - modeSource, - baseUrl, - apiUrlSource, - apiKeyPresent: true, - apiKeySource: keyHit.key, - misconfigured: false, - warning: warnings.length > 0 ? warnings.join(" ") : null - }; -} - -class HasnaHttpError extends Error { - status; - method; - path; - body; - constructor(method, path, status, body) { - super(`Hasna cloud request failed: ${method} ${path} -> ${status}`); - this.name = "HasnaHttpError"; - this.status = status; - this.method = method; - this.path = path; - this.body = body; - } -} -var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504]; -var IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); -function appendQuery(path, query) { - if (!query) - return path; - const params = query instanceof URLSearchParams ? query : new URLSearchParams; - if (!(query instanceof URLSearchParams)) { - for (const [key, value] of Object.entries(query)) { - if (value === null || value === undefined) - continue; - if (Array.isArray(value)) { - for (const v of value) - params.append(key, String(v)); - } else { - params.append(key, String(value)); - } - } - } - const qs = params.toString(); - if (!qs) - return path; - return `${path}${path.includes("?") ? "&" : "?"}${qs}`; -} -var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); -function createHasnaHttpTransport(options) { - const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init)); - const base = options.baseUrl.replace(/\/+$/, ""); - const timeoutMs = options.timeoutMs ?? 30000; - const sleep = options.sleepImpl ?? defaultSleep; - const defaultRetry = options.retry; - function resolveRetry(callRetry) { - const chosen = callRetry !== undefined ? callRetry : defaultRetry; - if (chosen === false) - return null; - const r = chosen ?? {}; - return { - retries: r.retries ?? 2, - baseDelayMs: r.baseDelayMs ?? 200, - maxDelayMs: r.maxDelayMs ?? 2000, - retryStatuses: r.retryStatuses ?? [...DEFAULT_RETRY_STATUSES] - }; - } - async function once(method, rel, url, body, opts) { - const headers = { - "x-api-key": options.apiKey, - Authorization: `Bearer ${options.apiKey}`, - Accept: "application/json", - ...options.headers ?? {}, - ...opts.headers ?? {} - }; - if (opts.idempotencyKey) - headers["Idempotency-Key"] = opts.idempotencyKey; - const init = { method, headers }; - if (body !== undefined) { - headers["Content-Type"] = "application/json"; - init.body = JSON.stringify(body); - } - const controller = new AbortController; - const onAbort = () => controller.abort(); - if (opts.signal) { - if (opts.signal.aborted) - controller.abort(); - else - opts.signal.addEventListener("abort", onAbort, { once: true }); - } - const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? timeoutMs); - init.signal = controller.signal; - let response; - try { - response = await fetchImpl(url, init); - } catch (error) { - const err = error instanceof Error ? error : new Error(String(error)); - if (opts.signal?.aborted) - return { ok: false, retryable: false, error: err }; - return { ok: false, retryable: true, error: err }; - } finally { - clearTimeout(timer); - if (opts.signal) - opts.signal.removeEventListener("abort", onAbort); - } - const text = await response.text(); - let parsed = undefined; - if (text.length > 0) { - try { - parsed = JSON.parse(text); - } catch { - parsed = text; - } - } - if (!response.ok) { - const retry = resolveRetry(opts.retry); - const retryable = retry ? retry.retryStatuses.includes(response.status) : false; - return { ok: false, retryable, error: new HasnaHttpError(method, rel, response.status, parsed) }; - } - return { ok: true, value: parsed }; - } - async function request(method, path, body, opts = {}) { - const upper = method.toUpperCase(); - const rel = appendQuery(path.startsWith("/") ? path : `/${path}`, opts.query); - const url = `${base}${rel}`; - const retry = resolveRetry(opts.retry); - const methodRetryable = IDEMPOTENT_METHODS.has(upper) || Boolean(opts.idempotencyKey); - const maxAttempts = retry && methodRetryable ? retry.retries + 1 : 1; - let last = null; - for (let attempt = 1;attempt <= maxAttempts; attempt++) { - const result = await once(upper, rel, url, body, opts); - if (result.ok) - return result.value; - last = result; - const canRetry = retry !== null && methodRetryable && result.retryable && attempt < maxAttempts; - if (!canRetry) - break; - const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1)); - const jitter = Math.floor(Math.random() * (backoff / 2 + 1)); - await sleep(backoff + jitter); - } - throw last.error; - } - return { - baseUrl: base, - request, - get: (path, opts) => request("GET", path, undefined, opts), - post: (path, body, opts) => request("POST", path, body, opts), - put: (path, body, opts) => request("PUT", path, body, opts), - patch: (path, body, opts) => request("PATCH", path, body, opts), - del: (path, body, opts) => request("DELETE", path, body, opts) - }; -} -function createClientTransport(name, env = process.env, overrides) { - const resolution = resolveClientTransport(name, env); - if (resolution.misconfigured) { - throw new Error(resolution.warning ?? `Client for '${name}' is misconfigured for cloud mode.`); - } - if (resolution.transport === "local" || !resolution.baseUrl) { - return { transport: "local", client: null, resolution }; - } - const keys = clientTransportEnvKeys(name); - const apiKey = firstEnv2(env, keys.apiKeyKeys)?.value; - if (!apiKey) { - throw new Error(`Client for '${name}' resolved to cloud-http without an API key.`); - } - return { - transport: "cloud-http", - client: createHasnaHttpTransport({ - name, - baseUrl: resolution.baseUrl, - apiKey, - ...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {}, - ...overrides?.headers ? { headers: overrides.headers } : {}, - ...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {}, - ...overrides?.retry !== undefined ? { retry: overrides.retry } : {}, - ...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {} - }), - resolution - }; -} -function resourcePath(resource) { - const trimmed = resource.replace(/^\/+|\/+$/g, ""); - if (!trimmed) - throw new Error("resource must be a non-empty path segment"); - return `/${trimmed}`; -} -function entityPath(resource, id) { - if (id === undefined || id === null || `${id}`.length === 0) { - throw new Error("id must be a non-empty string"); - } - return `${resourcePath(resource)}/${encodeURIComponent(String(id))}`; -} -function newIdempotencyKey() { - const g = globalThis; - if (g.crypto?.randomUUID) - return g.crypto.randomUUID(); - return `idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`; -} -function extractItems(raw) { - if (Array.isArray(raw)) - return raw; - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["items", "data", "results", "rows", "records"]) { - if (Array.isArray(obj[key])) - return obj[key]; - } - } - return []; -} -function extractTotal(raw) { - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["total", "count", "totalCount", "total_count"]) { - if (typeof obj[key] === "number") - return obj[key]; - } - } - return null; -} -function extractCursor(raw) { - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["cursor", "nextCursor", "next_cursor", "next"]) { - if (typeof obj[key] === "string") - return obj[key]; - } - } - return null; -} -function createHasnaStorageClient(name, transport) { - return { - name, - baseUrl: transport.baseUrl, - transport, - async list(resource, options = {}) { - const raw = await transport.get(resourcePath(resource), options); - return { - items: extractItems(raw), - total: extractTotal(raw), - cursor: extractCursor(raw), - raw - }; - }, - async get(resource, id, options = {}) { - try { - return await transport.get(entityPath(resource, id), options); - } catch (error) { - if (error instanceof HasnaHttpError && error.status === 404) - return null; - throw error; - } - }, - async create(resource, body, options = {}) { - const { idempotencyKey, ...rest } = options; - return transport.post(resourcePath(resource), body, { - ...rest, - idempotencyKey: idempotencyKey ?? newIdempotencyKey() - }); - }, - async update(resource, id, patch, options = {}) { - const { method = "PATCH", idempotencyKey, ...rest } = options; - const call = method === "PUT" ? transport.put : transport.patch; - return call(entityPath(resource, id), patch, { ...rest, ...idempotencyKey ? { idempotencyKey } : {} }); - }, - async delete(resource, id, options = {}) { - try { - await transport.del(entityPath(resource, id), undefined, options); - } catch (error) { - if (error instanceof HasnaHttpError && error.status === 404) - return; - throw error; - } - } - }; -} -function resolveStorageClient(name, env = process.env, overrides) { - const wired = createClientTransport(name, env, overrides); - if (wired.transport === "cloud-http") { - return { transport: "cloud-http", client: createHasnaStorageClient(name, wired.client) }; - } - return { transport: "local", client: null }; -} - -// node_modules/@hasna/contracts/dist/client/transport.js -var __defProp3 = Object.defineProperty; -var __returnValue3 = (v) => v; -function __exportSetter3(name, newValue) { - this[name] = __returnValue3.bind(null, newValue); -} -var __export3 = (target, all) => { - for (var name in all) - __defProp3(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter3.bind(all, name) - }); -}; -var exports_external2 = {}; -__export3(exports_external2, { - void: () => voidType2, - util: () => util2, - unknown: () => unknownType2, - union: () => unionType2, - undefined: () => undefinedType2, - tuple: () => tupleType2, - transformer: () => effectsType2, - symbol: () => symbolType2, - string: () => stringType2, - strictObject: () => strictObjectType2, - setErrorMap: () => setErrorMap2, - set: () => setType2, - record: () => recordType2, - quotelessJson: () => quotelessJson2, - promise: () => promiseType2, - preprocess: () => preprocessType2, - pipeline: () => pipelineType2, - ostring: () => ostring2, - optional: () => optionalType2, - onumber: () => onumber2, - oboolean: () => oboolean2, - objectUtil: () => objectUtil2, - object: () => objectType2, - number: () => numberType2, - nullable: () => nullableType2, - null: () => nullType2, - never: () => neverType2, - nativeEnum: () => nativeEnumType2, - nan: () => nanType2, - map: () => mapType2, - makeIssue: () => makeIssue2, - literal: () => literalType2, - lazy: () => lazyType2, - late: () => late2, - isValid: () => isValid2, - isDirty: () => isDirty2, - isAsync: () => isAsync2, - isAborted: () => isAborted2, - intersection: () => intersectionType2, - instanceof: () => instanceOfType2, - getParsedType: () => getParsedType2, - getErrorMap: () => getErrorMap2, - function: () => functionType2, - enum: () => enumType2, - effect: () => effectsType2, - discriminatedUnion: () => discriminatedUnionType2, - defaultErrorMap: () => en_default2, - datetimeRegex: () => datetimeRegex2, - date: () => dateType2, - custom: () => custom2, - coerce: () => coerce2, - boolean: () => booleanType2, - bigint: () => bigIntType2, - array: () => arrayType2, - any: () => anyType2, - addIssueToContext: () => addIssueToContext2, - ZodVoid: () => ZodVoid2, - ZodUnknown: () => ZodUnknown2, - ZodUnion: () => ZodUnion2, - ZodUndefined: () => ZodUndefined2, - ZodType: () => ZodType2, - ZodTuple: () => ZodTuple2, - ZodTransformer: () => ZodEffects2, - ZodSymbol: () => ZodSymbol2, - ZodString: () => ZodString2, - ZodSet: () => ZodSet2, - ZodSchema: () => ZodType2, - ZodRecord: () => ZodRecord2, - ZodReadonly: () => ZodReadonly2, - ZodPromise: () => ZodPromise2, - ZodPipeline: () => ZodPipeline2, - ZodParsedType: () => ZodParsedType2, - ZodOptional: () => ZodOptional2, - ZodObject: () => ZodObject2, - ZodNumber: () => ZodNumber2, - ZodNullable: () => ZodNullable2, - ZodNull: () => ZodNull2, - ZodNever: () => ZodNever2, - ZodNativeEnum: () => ZodNativeEnum2, - ZodNaN: () => ZodNaN2, - ZodMap: () => ZodMap2, - ZodLiteral: () => ZodLiteral2, - ZodLazy: () => ZodLazy2, - ZodIssueCode: () => ZodIssueCode2, - ZodIntersection: () => ZodIntersection2, - ZodFunction: () => ZodFunction2, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, - ZodError: () => ZodError2, - ZodEnum: () => ZodEnum2, - ZodEffects: () => ZodEffects2, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, - ZodDefault: () => ZodDefault2, - ZodDate: () => ZodDate2, - ZodCatch: () => ZodCatch2, - ZodBranded: () => ZodBranded2, - ZodBoolean: () => ZodBoolean2, - ZodBigInt: () => ZodBigInt2, - ZodArray: () => ZodArray2, - ZodAny: () => ZodAny2, - Schema: () => ZodType2, - ParseStatus: () => ParseStatus2, - OK: () => OK2, - NEVER: () => NEVER2, - INVALID: () => INVALID2, - EMPTY_PATH: () => EMPTY_PATH2, - DIRTY: () => DIRTY2, - BRAND: () => BRAND2 -}); -var util2; -(function(util22) { - util22.assertEqual = (_) => {}; - function assertIs(_arg) {} - util22.assertIs = assertIs; - function assertNever(_x) { - throw new Error; - } - util22.assertNever = assertNever; - util22.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util22.getValidEnumValues = (obj) => { - const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util22.objectValues(filtered); - }; - util22.objectValues = (obj) => { - return util22.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util22.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util22.joinValues = joinValues; - util22.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util2 || (util2 = {})); -var objectUtil2; -(function(objectUtil22) { - objectUtil22.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; -})(objectUtil2 || (objectUtil2 = {})); -var ZodParsedType2 = util2.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType2.undefined; - case "string": - return ZodParsedType2.string; - case "number": - return Number.isNaN(data) ? ZodParsedType2.nan : ZodParsedType2.number; - case "boolean": - return ZodParsedType2.boolean; - case "function": - return ZodParsedType2.function; - case "bigint": - return ZodParsedType2.bigint; - case "symbol": - return ZodParsedType2.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType2.array; - } - if (data === null) { - return ZodParsedType2.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType2.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType2.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType2.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType2.date; - } - return ZodParsedType2.object; - default: - return ZodParsedType2.unknown; - } -}; -var ZodIssueCode2 = util2.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson2 = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; - -class ZodError2 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError2)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError2.create = (issues) => { - const error = new ZodError2(issues); - return error; -}; -var errorMap2 = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode2.invalid_type: - if (issue.received === ZodParsedType2.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode2.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`; - break; - case ZodIssueCode2.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode2.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`; - break; - case ZodIssueCode2.invalid_enum_value: - message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode2.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode2.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode2.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode2.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util2.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode2.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.custom: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode2.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode2.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util2.assertNever(issue); - } - return { message }; -}; -var en_default2 = errorMap2; -var overrideErrorMap2 = en_default2; -function setErrorMap2(map) { - overrideErrorMap2 = map; -} -function getErrorMap2() { - return overrideErrorMap2; -} -var makeIssue2 = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH2 = []; -function addIssueToContext2(ctx, issueData) { - const overrideMap = getErrorMap2(); - const issue = makeIssue2({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default2 ? undefined : en_default2 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); -} - -class ParseStatus2 { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID2; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus2.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID2; - if (value.status === "aborted") - return INVALID2; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -var INVALID2 = Object.freeze({ - status: "aborted" -}); -var DIRTY2 = (value) => ({ status: "dirty", value }); -var OK2 = (value) => ({ status: "valid", value }); -var isAborted2 = (x) => x.status === "aborted"; -var isDirty2 = (x) => x.status === "dirty"; -var isValid2 = (x) => x.status === "valid"; -var isAsync2 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil2; -(function(errorUtil22) { - errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil2 || (errorUtil2 = {})); - -class ParseInputLazyPath2 { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -var handleResult2 = (ctx, result) => { - if (isValid2(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError2(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams2(params) { - if (!params) - return {}; - const { errorMap: errorMap22, invalid_type_error, required_error, description } = params; - if (errorMap22 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap22) - return { errorMap: errorMap22, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -class ZodType2 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType2(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus2, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync2(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult2(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult2(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode2.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects2({ - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional2.create(this, this._def); - } - nullable() { - return ZodNullable2.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray2.create(this); - } - promise() { - return ZodPromise2.create(this, this._def); - } - or(option) { - return ZodUnion2.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection2.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects2({ - ...processCreateParams2(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault2({ - ...processCreateParams2(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodDefault - }); - } - brand() { - return new ZodBranded2({ - typeName: ZodFirstPartyTypeKind2.ZodBranded, - type: this, - ...processCreateParams2(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch2({ - ...processCreateParams2(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline2.create(this, target); - } - readonly() { - return ZodReadonly2.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex2 = /^c[^\s-]{8,}$/i; -var cuid2Regex2 = /^[0-9a-z]+$/; -var ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex2 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex2 = /^[a-z0-9_-]{21}$/i; -var jwtRegex2 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex2 = /^[-+]?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)?)??$/; -var emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex2 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex2; -var ipv4Regex2 = /^(?:(?: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])$/; -var ipv4CidrRegex2 = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex2 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex2 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex2 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource2 = `((\\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])))`; -var dateRegex2 = new RegExp(`^${dateRegexSource2}$`); -function timeRegexSource2(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex2(args) { - return new RegExp(`^${timeRegexSource2(args)}$`); -} -function datetimeRegex2(args) { - let regex = `${dateRegexSource2}T${timeRegexSource2(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP2(ip, version) { - if ((version === "v4" || !version) && ipv4Regex2.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex2.test(ip)) { - return true; - } - return false; -} -function isValidJWT2(jwt, alg) { - if (!jwtRegex2.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr2(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex2.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex2.test(ip)) { - return true; - } - return false; -} - -class ZodString2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.string, - received: ctx2.parsedType - }); - return INVALID2; - } - const status = new ParseStatus2; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "email", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex2) { - emojiRegex2 = new RegExp(_emojiRegex2, "u"); - } - if (!emojiRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "emoji", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "uuid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "nanoid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid2", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ulid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "url", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "regex", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex2(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex2; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex2(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "duration", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP2(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ip", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT2(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "jwt", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr2(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cidr", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64url", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode2.invalid_string, - ...errorUtil2.errToObj(message) - }); - } - _addCheck(check) { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil2.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil2.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil2.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil2.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil2.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil2.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil2.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil2.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil2.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil2.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil2.errToObj(message)); - } - trim() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString2.create = (params) => { - return new ZodString2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); -}; -function floatSafeRemainder2(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} - -class ZodNumber2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.number, - received: ctx2.parsedType - }); - return INVALID2; - } - let ctx = undefined; - const status = new ParseStatus2; - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util2.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder2(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodNumber2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil2.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil2.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil2.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil2.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber2.create = (params) => { - return new ZodNumber2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); -}; - -class ZodBigInt2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus2; - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.bigint, - received: ctx.parsedType - }); - return INVALID2; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodBigInt2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt2.create = (params) => { - return new ZodBigInt2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); -}; - -class ZodBoolean2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.boolean, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodBoolean2.create = (params) => { - return new ZodBoolean2({ - typeName: ZodFirstPartyTypeKind2.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); -}; - -class ZodDate2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.date, - received: ctx2.parsedType - }); - return INVALID2; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_date - }); - return INVALID2; - } - const status = new ParseStatus2; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new ZodDate2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil2.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil2.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate2.create = (params) => { - return new ZodDate2({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind2.ZodDate, - ...processCreateParams2(params) - }); -}; - -class ZodSymbol2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.symbol, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodSymbol2.create = (params) => { - return new ZodSymbol2({ - typeName: ZodFirstPartyTypeKind2.ZodSymbol, - ...processCreateParams2(params) - }); -}; - -class ZodUndefined2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.undefined, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodUndefined2.create = (params) => { - return new ZodUndefined2({ - typeName: ZodFirstPartyTypeKind2.ZodUndefined, - ...processCreateParams2(params) - }); -}; - -class ZodNull2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.null, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodNull2.create = (params) => { - return new ZodNull2({ - typeName: ZodFirstPartyTypeKind2.ZodNull, - ...processCreateParams2(params) - }); -}; - -class ZodAny2 extends ZodType2 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK2(input.data); - } -} -ZodAny2.create = (params) => { - return new ZodAny2({ - typeName: ZodFirstPartyTypeKind2.ZodAny, - ...processCreateParams2(params) - }); -}; - -class ZodUnknown2 extends ZodType2 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK2(input.data); - } -} -ZodUnknown2.create = (params) => { - return new ZodUnknown2({ - typeName: ZodFirstPartyTypeKind2.ZodUnknown, - ...processCreateParams2(params) - }); -}; - -class ZodNever2 extends ZodType2 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.never, - received: ctx.parsedType - }); - return INVALID2; - } -} -ZodNever2.create = (params) => { - return new ZodNever2({ - typeName: ZodFirstPartyTypeKind2.ZodNever, - ...processCreateParams2(params) - }); -}; - -class ZodVoid2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.void, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodVoid2.create = (params) => { - return new ZodVoid2({ - typeName: ZodFirstPartyTypeKind2.ZodVoid, - ...processCreateParams2(params) - }); -}; - -class ZodArray2 extends ZodType2 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext2(ctx, { - code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus2.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - }); - return ParseStatus2.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray2({ - ...this._def, - minLength: { value: minLength, message: errorUtil2.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray2({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil2.toString(message) } - }); - } - length(len, message) { - return new ZodArray2({ - ...this._def, - exactLength: { value: len, message: errorUtil2.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray2.create = (schema, params) => { - return new ZodArray2({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind2.ZodArray, - ...processCreateParams2(params) - }); -}; -function deepPartialify2(schema) { - if (schema instanceof ZodObject2) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional2.create(deepPartialify2(fieldSchema)); - } - return new ZodObject2({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray2) { - return new ZodArray2({ - ...schema._def, - type: deepPartialify2(schema.element) - }); - } else if (schema instanceof ZodOptional2) { - return ZodOptional2.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodNullable2) { - return ZodNullable2.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodTuple2) { - return ZodTuple2.create(schema.items.map((item) => deepPartialify2(item))); - } else { - return schema; - } -} - -class ZodObject2 extends ZodType2 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util2.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.object, - received: ctx2.parsedType - }); - return INVALID2; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever2) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus2.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus2.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil2.errToObj; - return new ZodObject2({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil2.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject2({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject2({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject2({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject2({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind2.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject2({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util2.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify2(this); - } - partial(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject2({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional2) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject2({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum2(util2.objectKeys(this.shape)); - } -} -ZodObject2.create = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams2(params) - }); -}; -ZodObject2.strictCreate = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams2(params) - }); -}; -ZodObject2.lazycreate = (shape, params) => { - return new ZodObject2({ - shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams2(params) - }); -}; - -class ZodUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors - }); - return INVALID2; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError2(issues2)); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors - }); - return INVALID2; - } - } - get options() { - return this._def.options; - } -} -ZodUnion2.create = (types, params) => { - return new ZodUnion2({ - options: types, - typeName: ZodFirstPartyTypeKind2.ZodUnion, - ...processCreateParams2(params) - }); -}; -var getDiscriminator2 = (type) => { - if (type instanceof ZodLazy2) { - return getDiscriminator2(type.schema); - } else if (type instanceof ZodEffects2) { - return getDiscriminator2(type.innerType()); - } else if (type instanceof ZodLiteral2) { - return [type.value]; - } else if (type instanceof ZodEnum2) { - return type.options; - } else if (type instanceof ZodNativeEnum2) { - return util2.objectValues(type.enum); - } else if (type instanceof ZodDefault2) { - return getDiscriminator2(type._def.innerType); - } else if (type instanceof ZodUndefined2) { - return [undefined]; - } else if (type instanceof ZodNull2) { - return [null]; - } else if (type instanceof ZodOptional2) { - return [undefined, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodNullable2) { - return [null, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodBranded2) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodReadonly2) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodCatch2) { - return getDiscriminator2(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID2; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator2(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion2({ - typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams2(params) - }); - } -} -function mergeValues2(a, b) { - const aType = getParsedType2(a); - const bType = getParsedType2(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) { - const bKeys = util2.objectKeys(b); - const sharedKeys = util2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues2(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues2(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted2(parsedLeft) || isAborted2(parsedRight)) { - return INVALID2; - } - const merged = mergeValues2(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_intersection_types - }); - return INVALID2; - } - if (isDirty2(parsedLeft) || isDirty2(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection2.create = (left, right, params) => { - return new ZodIntersection2({ - left, - right, - typeName: ZodFirstPartyTypeKind2.ZodIntersection, - ...processCreateParams2(params) - }); -}; - -class ZodTuple2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID2; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath2(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus2.mergeArray(status, results); - }); - } else { - return ParseStatus2.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple2({ - ...this._def, - rest - }); - } -} -ZodTuple2.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple2({ - items: schemas, - typeName: ZodFirstPartyTypeKind2.ZodTuple, - rest: null, - ...processCreateParams2(params) - }); -}; - -class ZodRecord2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus2.mergeObjectAsync(status, pairs); - } else { - return ParseStatus2.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType2) { - return new ZodRecord2({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams2(third) - }); - } - return new ZodRecord2({ - keyType: ZodString2.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams2(second) - }); - } -} - -class ZodMap2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.map) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.map, - received: ctx.parsedType - }); - return INVALID2; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap2.create = (keyType, valueType, params) => { - return new ZodMap2({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind2.ZodMap, - ...processCreateParams2(params) - }); -}; - -class ZodSet2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.set) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.set, - received: ctx.parsedType - }); - return INVALID2; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID2; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet2({ - ...this._def, - minSize: { value: minSize, message: errorUtil2.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet2({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil2.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet2.create = (valueType, params) => { - return new ZodSet2({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind2.ZodSet, - ...processCreateParams2(params) - }); -}; - -class ZodFunction2 extends ZodType2 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.function) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.function, - received: ctx.parsedType - }); - return INVALID2; - } - function makeArgsIssue(args, error) { - return makeIssue2({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue2({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise2) { - const me = this; - return OK2(async function(...args) { - const error = new ZodError2([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK2(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction2({ - ...this._def, - args: ZodTuple2.create(items).rest(ZodUnknown2.create()) - }); - } - returns(returnType) { - return new ZodFunction2({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction2({ - args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), - returns: returns || ZodUnknown2.create(), - typeName: ZodFirstPartyTypeKind2.ZodFunction, - ...processCreateParams2(params) - }); - } -} - -class ZodLazy2 extends ZodType2 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy2.create = (getter, params) => { - return new ZodLazy2({ - getter, - typeName: ZodFirstPartyTypeKind2.ZodLazy, - ...processCreateParams2(params) - }); -}; - -class ZodLiteral2 extends ZodType2 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_literal, - expected: this._def.value - }); - return INVALID2; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral2.create = (value, params) => { - return new ZodLiteral2({ - value, - typeName: ZodFirstPartyTypeKind2.ZodLiteral, - ...processCreateParams2(params) - }); -}; -function createZodEnum2(values, params) { - return new ZodEnum2({ - values, - typeName: ZodFirstPartyTypeKind2.ZodEnum, - ...processCreateParams2(params) - }); -} - -class ZodEnum2 extends ZodType2 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID2; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID2; - } - return OK2(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum2.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum2.create = createZodEnum2; - -class ZodNativeEnum2 extends ZodType2 { - _parse(input) { - const nativeEnumValues = util2.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID2; - } - if (!this._cache) { - this._cache = new Set(util2.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID2; - } - return OK2(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum2.create = (values, params) => { - return new ZodNativeEnum2({ - values, - typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, - ...processCreateParams2(params) - }); -}; - -class ZodPromise2 extends ZodType2 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.promise, - received: ctx.parsedType - }); - return INVALID2; - } - const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data); - return OK2(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise2.create = (schema, params) => { - return new ZodPromise2({ - type: schema, - typeName: ZodFirstPartyTypeKind2.ZodPromise, - ...processCreateParams2(params) - }); -}; - -class ZodEffects2 extends ZodType2 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext2(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID2; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID2; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid2(base)) - return INVALID2; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid2(base)) - return INVALID2; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util2.assertNever(effect); - } -} -ZodEffects2.create = (schema, effect, params) => { - return new ZodEffects2({ - schema, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect, - ...processCreateParams2(params) - }); -}; -ZodEffects2.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects2({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - ...processCreateParams2(params) - }); -}; - -class ZodOptional2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType2.undefined) { - return OK2(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional2.create = (type, params) => { - return new ZodOptional2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodOptional, - ...processCreateParams2(params) - }); -}; - -class ZodNullable2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType2.null) { - return OK2(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable2.create = (type, params) => { - return new ZodNullable2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodNullable, - ...processCreateParams2(params) - }); -}; - -class ZodDefault2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType2.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault2.create = (type, params) => { - return new ZodDefault2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams2(params) - }); -}; - -class ZodCatch2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync2(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch2.create = (type, params) => { - return new ZodCatch2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams2(params) - }); -}; - -class ZodNaN2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.nan, - received: ctx.parsedType - }); - return INVALID2; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN2.create = (params) => { - return new ZodNaN2({ - typeName: ZodFirstPartyTypeKind2.ZodNaN, - ...processCreateParams2(params) - }); -}; -var BRAND2 = Symbol("zod_brand"); - -class ZodBranded2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY2(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline2({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind2.ZodPipeline - }); - } -} - -class ZodReadonly2 extends ZodType2 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid2(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync2(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly2.create = (type, params) => { - return new ZodReadonly2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodReadonly, - ...processCreateParams2(params) - }); -}; -function cleanParams2(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom2(check, _params = {}, fatal) { - if (check) - return ZodAny2.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny2.create(); -} -var late2 = { - object: ZodObject2.lazycreate -}; -var ZodFirstPartyTypeKind2; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); -var instanceOfType2 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom2((data) => data instanceof cls, params); -var stringType2 = ZodString2.create; -var numberType2 = ZodNumber2.create; -var nanType2 = ZodNaN2.create; -var bigIntType2 = ZodBigInt2.create; -var booleanType2 = ZodBoolean2.create; -var dateType2 = ZodDate2.create; -var symbolType2 = ZodSymbol2.create; -var undefinedType2 = ZodUndefined2.create; -var nullType2 = ZodNull2.create; -var anyType2 = ZodAny2.create; -var unknownType2 = ZodUnknown2.create; -var neverType2 = ZodNever2.create; -var voidType2 = ZodVoid2.create; -var arrayType2 = ZodArray2.create; -var objectType2 = ZodObject2.create; -var strictObjectType2 = ZodObject2.strictCreate; -var unionType2 = ZodUnion2.create; -var discriminatedUnionType2 = ZodDiscriminatedUnion2.create; -var intersectionType2 = ZodIntersection2.create; -var tupleType2 = ZodTuple2.create; -var recordType2 = ZodRecord2.create; -var mapType2 = ZodMap2.create; -var setType2 = ZodSet2.create; -var functionType2 = ZodFunction2.create; -var lazyType2 = ZodLazy2.create; -var literalType2 = ZodLiteral2.create; -var enumType2 = ZodEnum2.create; -var nativeEnumType2 = ZodNativeEnum2.create; -var promiseType2 = ZodPromise2.create; -var effectsType2 = ZodEffects2.create; -var optionalType2 = ZodOptional2.create; -var nullableType2 = ZodNullable2.create; -var preprocessType2 = ZodEffects2.createWithPreprocess; -var pipelineType2 = ZodPipeline2.create; -var ostring2 = () => stringType2().optional(); -var onumber2 = () => numberType2().optional(); -var oboolean2 = () => booleanType2().optional(); -var coerce2 = { - string: (arg) => ZodString2.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber2.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean2.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt2.create({ ...arg, coerce: true }), - date: (arg) => ZodDate2.create({ ...arg, coerce: true }) -}; -var NEVER2 = INVALID2; -var SCHEMA_IDS2 = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema2 = exports_external2.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema2 = exports_external2.string().datetime(); -var NonEmptyStringSchema2 = exports_external2.string().trim().min(1); -var UriSchema2 = NonEmptyStringSchema2.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema2 = exports_external2.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema2 = exports_external2.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema2 = exports_external2.record(exports_external2.unknown()); -var TagsSchema2 = exports_external2.array(exports_external2.string().min(1)).default([]); -var OptionalTimestampSchema2 = TimestampSchema2.nullable().optional(); -var TerminalStatuses2 = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema2 = exports_external2.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema2(schema) { - return exports_external2.object({ - schema: exports_external2.literal(schema), - id: exports_external2.string().min(1), - createdAt: TimestampSchema2, - updatedAt: OptionalTimestampSchema2, - metadata: MetadataSchema2.optional() - }).strict(); -} -var ContractEnvelopeSchema2 = exports_external2.object({ - schema: SchemaIdSchema2, - id: exports_external2.string().min(1), - createdAt: TimestampSchema2, - updatedAt: OptionalTimestampSchema2, - metadata: MetadataSchema2.optional() -}).strict(); -var ActorKindSchema2 = exports_external2.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.actorRef).extend({ - kind: ActorKindSchema2, - name: exports_external2.string().min(1).optional(), - provider: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - machineId: exports_external2.string().min(1).optional(), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema2 = exports_external2.object({ - kind: ActorKindSchema2, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - provider: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - machineId: exports_external2.string().min(1).optional() -}).strict(); -var ResourceKindSchema2 = exports_external2.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.resourceRef).extend({ - kind: ResourceKindSchema2, - name: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema2 = exports_external2.object({ - kind: ResourceKindSchema2, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema2 = exports_external2.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema2 = exports_external2.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.evidenceRef).extend({ - kind: EvidenceKindSchema2, - uri: UriSchema2, - sha256: Sha256DigestSchema2.optional(), - summary: exports_external2.string().min(1).optional(), - contentType: exports_external2.string().min(1).optional(), - sizeBytes: exports_external2.number().int().nonnegative().optional(), - redaction: RedactionStateSchema2.default("unknown"), - producer: ActorPointerSchema2.optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - tags: TagsSchema2 -}).strict(); -var EvidencePointerSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: EvidenceKindSchema2.optional(), - uri: UriSchema2.optional(), - sha256: Sha256DigestSchema2.optional(), - summary: exports_external2.string().min(1).optional() -}).strict(); -var CostEstimateSchema2 = contractBaseSchema2(SCHEMA_IDS2.costEstimate).extend({ - currency: exports_external2.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external2.number().int().nonnegative(), - provider: exports_external2.string().min(1).optional(), - model: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - promptTokens: exports_external2.number().int().nonnegative().optional(), - completionTokens: exports_external2.number().int().nonnegative().optional(), - totalTokens: exports_external2.number().int().nonnegative().optional(), - basis: exports_external2.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema2 = exports_external2.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema2 = contractBaseSchema2(SCHEMA_IDS2.decisionEnvelope).extend({ - decisionType: exports_external2.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema2, - actor: ActorPointerSchema2.optional(), - traceId: exports_external2.string().min(1).optional(), - inputHash: HashStringSchema2.optional(), - policyBundleId: exports_external2.string().min(1).optional(), - selected: exports_external2.array(ResourcePointerSchema2).default([]), - skipped: exports_external2.array(ResourcePointerSchema2).default([]), - reason: exports_external2.string().min(1), - obligations: exports_external2.array(exports_external2.string().min(1)).default([]), - redactions: exports_external2.array(exports_external2.string().min(1)).default([]), - costEstimate: CostEstimateSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema2 = contractBaseSchema2(SCHEMA_IDS2.capabilityCard).extend({ - kind: exports_external2.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external2.string().min(1), - version: exports_external2.string().min(1).optional(), - status: exports_external2.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), - limitations: exports_external2.array(exports_external2.string().min(1)).default([]), - riskLevel: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict(); -var ProviderModeSchema2 = exports_external2.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema2 = exports_external2.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema2 = exports_external2.object({ - refName: NonEmptyStringSchema2, - requiredForModes: exports_external2.array(ProviderModeSchema2).min(1), - allowedSecretInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema2, - revocationCheck: exports_external2.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema2 = exports_external2.object({ - operation: NonEmptyStringSchema2, - supportedModes: exports_external2.array(ProviderModeSchema2).min(1), - sideEffectClass: ProviderSideEffectClassSchema2, - requiresApproval: exports_external2.boolean().default(false), - requiresIdempotencyKey: exports_external2.boolean().default(false), - requiresSandboxEvidence: exports_external2.boolean().default(false), - requiresRollbackOrRevocation: exports_external2.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema2.optional(), - noSideEffectSmoke: NonEmptyStringSchema2.optional(), - reconciliation: NonEmptyStringSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema2 = exports_external2.object({ - providerId: NonEmptyStringSchema2, - appId: NonEmptyStringSchema2, - adapterId: NonEmptyStringSchema2, - ownerPackage: NonEmptyStringSchema2, - modes: exports_external2.array(ProviderModeSchema2).min(1), - defaultMode: ProviderModeSchema2, - credentialRequirements: exports_external2.array(CredentialRequirementSchema2).default([]), - operations: exports_external2.array(ProviderOperationCardSchema2).min(1), - rateLimitPosture: NonEmptyStringSchema2, - costPosture: NonEmptyStringSchema2.optional(), - auditEvents: exports_external2.array(NonEmptyStringSchema2).default([]), - redactionRules: exports_external2.array(NonEmptyStringSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema2 = exports_external2.object({ - appId: NonEmptyStringSchema2, - repo: NonEmptyStringSchema2, - priority: exports_external2.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external2.array(NonEmptyStringSchema2).min(1), - firstOperations: exports_external2.array(NonEmptyStringSchema2).min(1), - blockedUntil: exports_external2.array(NonEmptyStringSchema2).default([]) -}).strict(); -var ProviderLiveModeStandardSchema2 = contractBaseSchema2(SCHEMA_IDS2.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema2, - version: NonEmptyStringSchema2, - modes: exports_external2.array(ProviderModeSchema2).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external2.array(NonEmptyStringSchema2).min(1), - liveMutationGate: exports_external2.object({ - requiredMode: exports_external2.literal("live_mutating"), - requiredChecks: exports_external2.array(NonEmptyStringSchema2).min(1), - forbiddenBypassSignals: exports_external2.array(NonEmptyStringSchema2).min(1), - disabledLiveSmoke: NonEmptyStringSchema2 - }).strict(), - noSideEffectSmoke: exports_external2.object({ - requiredForModes: exports_external2.array(ProviderModeSchema2).min(1), - commandEvidence: exports_external2.array(NonEmptyStringSchema2).min(1), - secretOutputScan: exports_external2.boolean().default(true) - }).strict(), - credentialPolicy: exports_external2.object({ - acceptedInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external2.literal(false), - missingCredentialBehavior: exports_external2.literal("fail_closed"), - revocationCheckRequired: exports_external2.boolean().default(true) - }).strict(), - operationCards: exports_external2.array(ProviderCapabilityCardSchema2).min(1), - firstAdoptionTargets: exports_external2.array(ProviderLiveModeTargetSchema2).min(1), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1).optional(), - summary: exports_external2.string().min(1), - text: exports_external2.string().optional(), - tokens: exports_external2.number().int().nonnegative().optional(), - source: EvidencePointerSchema2, - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict(); -var ContextPackSchema2 = contractBaseSchema2(SCHEMA_IDS2.contextPack).extend({ - objective: exports_external2.string().min(1), - budget: exports_external2.object({ - maxTokens: exports_external2.number().int().positive().optional(), - maxBytes: exports_external2.number().int().positive().optional() - }).strict().optional(), - items: exports_external2.array(ContextPackItemSchema2).default([]), - citations: exports_external2.array(EvidencePointerSchema2).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external2.array(exports_external2.string().min(1)).default([]), - redactions: exports_external2.array(exports_external2.string().min(1)).default([]), - conflicts: exports_external2.array(exports_external2.string().min(1)).default([]), - uncertainty: exports_external2.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema2 = NonEmptyStringSchema2.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema2 = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema2 = exports_external2.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema2 = exports_external2.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema2 = exports_external2.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.integrationRef).extend({ - kind: ProjectIntegrationKindSchema2, - name: exports_external2.string().min(1), - projectId: ProjectSlugSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - uri: UriSchema2.optional(), - enabled: exports_external2.boolean().default(true), - readOnly: exports_external2.boolean().default(true), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - config: MetadataSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema2 = exports_external2.object({ - schemaRoot: RelativeProjectPathSchema2.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema2.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema2.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema2.default("documents"), - reportsDir: RelativeProjectPathSchema2.default("reports"), - evidenceDir: RelativeProjectPathSchema2.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema2.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectManifest).extend({ - projectId: ProjectSlugSchema2, - slug: ProjectSlugSchema2, - name: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - status: ProjectStatusSchema2.default("active"), - classification: ProjectClassificationSchema2.default("private"), - owner: ActorPointerSchema2.optional(), - layout: ProjectLayoutSchema2.default({}), - integrations: exports_external2.array(IntegrationRefSchema2).default([]), - renderManifests: exports_external2.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema2 = exports_external2.enum(["local", "package", "provider", "url"]); -var RenderImportSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: RenderImportKindSchema2, - specifier: exports_external2.string().min(1), - path: RelativeProjectPathSchema2.optional(), - packageName: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - provider: ProjectIntegrationKindSchema2.optional(), - schemaId: SchemaIdSchema2.optional(), - integrity: HashStringSchema2.optional(), - resourceRef: ResourcePointerSchema2.optional(), - optional: exports_external2.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema2 = exports_external2.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1), - kind: RenderViewKindSchema2, - default: exports_external2.boolean().default(false), - entry: RelativeProjectPathSchema2.optional(), - imports: exports_external2.array(RenderImportSchema2).default([]), - panelRefs: exports_external2.array(ResourcePointerSchema2).default([]), - dataRefs: exports_external2.array(ResourcePointerSchema2).default([]), - layout: MetadataSchema2.optional() -}).strict(); -var RenderManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.renderManifest).extend({ - projectId: ProjectSlugSchema2, - name: exports_external2.string().min(1), - version: exports_external2.string().min(1), - manifestPath: RelativeProjectPathSchema2.default(".hasna/project/dashboard.render.json"), - renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external2.array(RenderViewSchema2).min(1), - imports: exports_external2.array(RenderImportSchema2).default([]), - theme: MetadataSchema2.optional(), - compatibility: exports_external2.object({ - minProjectsVersion: exports_external2.string().min(1).optional(), - minContractsVersion: exports_external2.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema2 = exports_external2.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema2 = exports_external2.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - label: exports_external2.string().min(1), - value: exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]), - unit: exports_external2.string().min(1).optional(), - status: exports_external2.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict(); -var ProjectPanelItemSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - status: exports_external2.string().min(1).optional(), - priority: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema2.optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - metadata: MetadataSchema2.optional() -}).strict(); -var ProjectRenderFragmentSchema2 = exports_external2.object({ - renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external2.string().min(1).optional(), - entry: RelativeProjectPathSchema2.optional(), - imports: exports_external2.array(RenderImportSchema2).default([]), - spec: MetadataSchema2.default({}) -}).strict(); -var ProjectPanelSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectPanel).extend({ - projectId: ProjectSlugSchema2, - provider: exports_external2.object({ - kind: ProjectIntegrationKindSchema2, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - externalId: NonEmptyStringSchema2.optional() - }).strict(), - kind: ProjectPanelKindSchema2, - title: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - state: ProjectPanelStateSchema2.default("ready"), - stateReason: exports_external2.string().min(1).optional(), - generatedAt: TimestampSchema2, - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external2.array(ProjectPanelMetricSchema2).default([]), - items: exports_external2.array(ProjectPanelItemSchema2).default([]), - actions: exports_external2.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - renderFragment: ProjectRenderFragmentSchema2.optional(), - warnings: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectSnapshot).extend({ - projectId: ProjectSlugSchema2, - generatedAt: TimestampSchema2, - status: ContractStatusSchema2.default("unknown"), - manifestRef: ResourcePointerSchema2, - renderManifestRef: ResourcePointerSchema2.optional(), - panels: exports_external2.array(ProjectPanelSchema2).default([]), - contextPacks: exports_external2.array(ContextPackSchema2).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - warnings: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: exports_external2.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external2.boolean().default(true), - command: exports_external2.string().min(1).optional(), - expected: exports_external2.string().min(1).optional(), - timeoutMs: exports_external2.number().int().positive().optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema2 = contractBaseSchema2(SCHEMA_IDS2.validationPlan).extend({ - objective: exports_external2.string().min(1), - subject: ResourcePointerSchema2.optional(), - checks: exports_external2.array(ValidationCheckSchema2).min(1), - verifier: ActorPointerSchema2.optional(), - requiredEvidenceKinds: exports_external2.array(EvidenceKindSchema2).default([]) -}).strict(); -var ScaffoldTypeSchema2 = exports_external2.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema2 = exports_external2.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema2 = exports_external2.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema2 = exports_external2.object({ - key: exports_external2.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external2.string().min(1), - required: exports_external2.boolean().default(false), - ["secret"]: exports_external2.boolean().default(false), - group: exports_external2.string().min(1).optional(), - default: exports_external2.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema2 = exports_external2.object({ - name: exports_external2.string().min(1), - command: exports_external2.string().min(1), - description: exports_external2.string().min(1).optional(), - required: exports_external2.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema2 = exports_external2.object({ - packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external2.array(exports_external2.string().min(1)).default([]), - requiredFiles: exports_external2.array(exports_external2.string().min(1)).default([]), - requiredDirectories: exports_external2.array(exports_external2.string().min(1)).default([]), - optionalDirectories: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.scaffoldManifest).extend({ - name: exports_external2.string().min(1), - version: exports_external2.string().min(1), - summary: exports_external2.string().min(1), - type: ScaffoldTypeSchema2, - status: ScaffoldStatusSchema2.default("draft"), - capabilities: exports_external2.array(ScaffoldCapabilitySchema2).default([]), - techStack: exports_external2.array(exports_external2.string().min(1)).default([]), - tags: TagsSchema2, - source: ResourcePointerSchema2.optional(), - output: ScaffoldOutputShapeSchema2, - env: exports_external2.array(ScaffoldEnvVarSchema2).default([]), - scripts: exports_external2.array(ScaffoldScriptSchema2).default([]), - validationChecks: exports_external2.array(ValidationCheckSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema2 = exports_external2.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema2 = contractBaseSchema2(SCHEMA_IDS2.scaffoldInstallRecord).extend({ - scaffoldId: exports_external2.string().min(1), - scaffoldVersion: exports_external2.string().min(1).optional(), - manifestRef: ResourcePointerSchema2.optional(), - target: ResourcePointerSchema2, - status: ScaffoldInstallStatusSchema2, - installedAt: TimestampSchema2.optional(), - installer: ActorPointerSchema2.optional(), - packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema2.optional(), - generatedFiles: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema2 = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema2 = exports_external2.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema2 = exports_external2.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema2 = exports_external2.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema2 = NonEmptyStringSchema2.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema2 = exports_external2.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema2 = exports_external2.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema2 = exports_external2.object({ - transport: exports_external2.enum(["http", "stdio"]).default("http"), - bin: exports_external2.string().min(1).optional(), - url: UriSchema2.optional() -}).strict(); -var AppHttpSurfaceSchema2 = exports_external2.object({ - healthPath: exports_external2.string().min(1).default("/health"), - port: exports_external2.number().int().positive().optional(), - baseUrl: UriSchema2.optional() -}).strict(); -var AppSurfacesSchema2 = exports_external2.object({ - bins: exports_external2.array(exports_external2.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema2.optional(), - http: AppHttpSurfaceSchema2.optional() -}).strict(); -var AppSchema2 = contractBaseSchema2(SCHEMA_IDS2.app).extend({ - appId: AppIdSchema2, - npmName: NpmPackageNameSchema2, - repoFolder: AppIdSchema2, - githubUrl: GithubUrlSchema2, - projectSlug: ProjectSlugSchema2, - surfaces: AppSurfacesSchema2.default({}), - lifecycle: AppLifecycleSchema2, - releaseChannel: ReleaseChannelSchema2.default("stable"), - summary: exports_external2.string().min(1).optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema2 = exports_external2.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema2 = contractBaseSchema2(SCHEMA_IDS2.release).extend({ - appId: AppIdSchema2, - package: NpmPackageNameSchema2, - version: SemverSchema2, - gitSha: GitShaSchema2, - publishedAt: TimestampSchema2, - publishPath: PublishPathSchema2, - changelogRef: ResourcePointerSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema2 = exports_external2.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema2 = exports_external2.object({ - cliVersion: exports_external2.string().min(1).optional(), - mcpHealth: exports_external2.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema2 = contractBaseSchema2(SCHEMA_IDS2.rolloutRecord).extend({ - appId: AppIdSchema2, - package: NpmPackageNameSchema2, - version: SemverSchema2, - machine: NonEmptyStringSchema2, - action: RolloutActionSchema2, - result: ContractStatusSchema2, - verifiedBy: RolloutVerificationSchema2.optional(), - at: TimestampSchema2, - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema2 = exports_external2.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema2 = exports_external2.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema2 = exports_external2.object({ - channel: AnnouncementChannelKindSchema2, - status: AnnouncementDeliveryStatusSchema2, - deliveredAt: TimestampSchema2.optional(), - detail: exports_external2.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema2 = contractBaseSchema2(SCHEMA_IDS2.announcement).extend({ - campaignId: NonEmptyStringSchema2, - appId: AppIdSchema2.optional(), - releaseRef: ResourcePointerSchema2.optional(), - channels: exports_external2.array(AnnouncementChannelSchema2).min(1), - audienceRef: ResourcePointerSchema2, - sentAt: TimestampSchema2 -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema2 = exports_external2.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema2 = exports_external2.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema2 = exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]); -var AudiencePredicateSchema2 = exports_external2.object({ - kind: AudiencePredicateKindSchema2, - key: exports_external2.string().min(1).optional(), - op: AudiencePredicateOpSchema2.default("eq"), - value: AudiencePredicateValueSchema2.optional(), - values: exports_external2.array(AudiencePredicateValueSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema2 = exports_external2.object({ - match: exports_external2.enum(["all", "any"]).default("all"), - predicates: exports_external2.array(AudiencePredicateSchema2).min(1) -}).strict(); -var ConsentPolicySchema2 = exports_external2.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema2 = contractBaseSchema2(SCHEMA_IDS2.audience).extend({ - audienceId: AppIdSchema2, - name: NonEmptyStringSchema2, - definition: AudienceDefinitionSchema2, - consentPolicy: ConsentPolicySchema2, - suppressionSyncedAt: OptionalTimestampSchema2 -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES2 = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema2 = exports_external2.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - provider: AppCloudProviderSchema2, - kind: exports_external2.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external2.string().min(1), - region: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - machineScoped: exports_external2.boolean().default(false) -}).strict(); -var AppCloudManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.appCloudManifest).extend({ - packageName: exports_external2.string().min(1), - packageVersion: exports_external2.string().min(1).optional(), - appId: exports_external2.string().min(1), - repository: ResourcePointerSchema2.optional(), - storageMode: exports_external2.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external2.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external2.array(AppCloudResourceSchema2).default([]), - localCache: exports_external2.object({ - path: exports_external2.string().min(1).optional(), - pullMode: exports_external2.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external2.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external2.array(exports_external2.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES2]), - dependencies: exports_external2.array(exports_external2.string().min(1)).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES2, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES2) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema2 = exports_external2.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema2 = exports_external2.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: NoCloudCheckKindSchema2, - severity: NoCloudFindingSeveritySchema2, - path: exports_external2.string().min(1).optional(), - packageName: exports_external2.string().min(1).optional(), - pattern: exports_external2.string().min(1), - message: exports_external2.string().min(1), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict(); -var NoCloudCheckResultSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: NoCloudCheckKindSchema2, - status: ContractStatusSchema2, - target: exports_external2.string().min(1), - command: exports_external2.string().min(1).optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - findings: exports_external2.array(NoCloudFindingSchema2).default([]) -}).strict(); -var NoCloudEvidencePackSchema2 = contractBaseSchema2(SCHEMA_IDS2.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema2, - packageName: exports_external2.string().min(1).optional(), - packageVersion: exports_external2.string().min(1).optional(), - generatedBy: ActorPointerSchema2.optional(), - scanMode: exports_external2.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema2, - verdict: exports_external2.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema2.optional(), - checks: exports_external2.array(NoCloudCheckResultSchema2).min(1), - findings: exports_external2.array(NoCloudFindingSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check) => check.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check) => check.status !== "succeeded")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check) => check.status === "failed")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check, index) => { - const checkBlockingFindings = check.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema2 = exports_external2.object({ - checkId: exports_external2.string().min(1), - status: ContractStatusSchema2, - summary: exports_external2.string().min(1).optional(), - startedAt: OptionalTimestampSchema2, - finishedAt: OptionalTimestampSchema2, - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict(); -var ProofBundleSchema2 = contractBaseSchema2(SCHEMA_IDS2.proofBundle).extend({ - subject: ResourcePointerSchema2, - validationPlanRef: ResourcePointerSchema2.optional(), - status: ContractStatusSchema2, - verdict: exports_external2.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external2.array(ProofCheckResultSchema2).default([]), - verifier: ActorPointerSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - residualRisks: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check, index) => { - if (check.status !== "succeeded") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check) => check.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check) => check.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema2 = contractBaseSchema2(SCHEMA_IDS2.workRun).extend({ - objective: exports_external2.string().min(1), - status: ContractStatusSchema2, - actor: ActorPointerSchema2, - traceId: exports_external2.string().min(1).optional(), - startedAt: OptionalTimestampSchema2, - finishedAt: OptionalTimestampSchema2, - constraints: exports_external2.array(exports_external2.string().min(1)).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - decisions: exports_external2.array(DecisionEnvelopeSchema2).default([]), - costEstimates: exports_external2.array(CostEstimateSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - validationPlanRefs: exports_external2.array(ResourcePointerSchema2).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses2.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - at: TimestampSchema2, - kind: exports_external2.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external2.string().min(1), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - costEstimate: CostEstimateSchema2.optional() -}).strict(); -var AgentTrajectorySchema2 = contractBaseSchema2(SCHEMA_IDS2.agentTrajectory).extend({ - actor: ActorPointerSchema2, - workRunRef: ResourcePointerSchema2.optional(), - events: exports_external2.array(TrajectoryEventSchema2).default([]), - outcome: exports_external2.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema2.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION2 = "v1"; -var RepoClassSchema2 = exports_external2.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES2 = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema2 = exports_external2.enum(DEPLOYMENT_MODES2); -var ServiceSurfaceStatusSchema2 = exports_external2.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema2 = exports_external2.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema2 = exports_external2.object({ - method: exports_external2.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external2.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external2.boolean().default(false), - description: exports_external2.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: exports_external2.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external2.boolean().default(true), - command: exports_external2.string().min(1).optional(), - evidenceRef: EvidencePointerSchema2.optional(), - status: exports_external2.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external2.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema2 = exports_external2.object({ - name: exports_external2.string().min(1), - status: ServiceSurfaceStatusSchema2, - bin: exports_external2.string().min(1).optional(), - mcpBin: exports_external2.string().min(1).optional(), - authMode: ServiceAuthModeSchema2, - deploymentModes: exports_external2.array(DeploymentModeSchema2).min(1), - health: ServiceEndpointSchema2.optional(), - readiness: ServiceEndpointSchema2.optional(), - version: ServiceEndpointSchema2.optional(), - apiBasePath: exports_external2.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external2.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external2.string().min(1).optional(), - readinessGates: exports_external2.array(DeploymentReadinessGateSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES2 = ["local", "cloud"]; -var StorageModeSchema2 = exports_external2.enum(STORAGE_MODES2); -var AppNameSchema2 = exports_external2.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES2 = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName2(name) { - return ALLOWED_BIN_SUFFIXES2.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor2(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema2 = exports_external2.object({ - mode: StorageModeSchema2, - envPrefix: exports_external2.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external2.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external2.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external2.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema2 = exports_external2.object({ - $schema: exports_external2.string().min(1).optional(), - schema: exports_external2.literal(SCHEMA_IDS2.serviceContract), - name: AppNameSchema2, - class: RepoClassSchema2, - contractVersion: exports_external2.literal(SERVICE_CONTRACT_VERSION2), - kitVersion: exports_external2.string().min(1), - description: exports_external2.string().min(1).optional(), - bins: exports_external2.array(exports_external2.string().min(1)).default([]), - storage: StorageContractSchema2.optional(), - deploymentModes: exports_external2.array(DeploymentModeSchema2).default(["local"]), - serviceSurfaces: exports_external2.array(ServiceSurfaceSchema2).default([]), - metadata: MetadataSchema2.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName2(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor2(value.name)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor2(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } - } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); - } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } - } - } -}); -var HealthResponseSchema2 = exports_external2.object({ - status: exports_external2.enum(["ok", "degraded", "unavailable"]), - version: exports_external2.string().min(1), - mode: StorageModeSchema2 -}).strict(); -var ReadyResponseSchema2 = exports_external2.object({ - ready: exports_external2.boolean(), - reason: exports_external2.string().min(1).optional() -}).strict(); -var VersionResponseSchema2 = exports_external2.object({ - version: exports_external2.string().min(1) -}).strict(); -var CommsSeveritySchema2 = exports_external2.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema2 = exports_external2.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); -var COMMS_SEVERITY_TAGS2 = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema2 = exports_external2.enum(COMMS_SEVERITY_TAGS2); -var CommsScopeSchema2 = exports_external2.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsEventEnvelope).extend({ - type: CommsEventTypeSchema2, - severity: CommsSeveritySchema2, - scope: CommsScopeSchema2, - summary: exports_external2.string().min(1).optional(), - source: ActorPointerSchema2.optional(), - affected_packages: exports_external2.array(NonEmptyStringSchema2).default([]), - affected_machines: exports_external2.array(NonEmptyStringSchema2).default([]), - action_required: exports_external2.boolean().default(false), - ack_by: TimestampSchema2.optional(), - dedupe_key: NonEmptyStringSchema2, - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); - } - } -}); -var CommsChannelClassSchema2 = exports_external2.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema2 = exports_external2.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema2 = NonEmptyStringSchema2.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); -var CommsChannelMetadataSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsChannelMetadata).extend({ - class: CommsChannelClassSchema2, - noise: CommsChannelNoiseSchema2.optional(), - owner: NonEmptyStringSchema2.optional(), - until: CommsUntilHorizonSchema2.optional(), - successor: NonEmptyStringSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); - } - } -}); -var COMMS_SEVERITY_TAG_INFO2 = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema2, - envelope: CommsEventEnvelopeSchema2 -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO2[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO2)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] - }); - } - } -}); -var ContractSchemaRegistry2 = { - [SCHEMA_IDS2.actorRef]: ActorRefSchema2, - [SCHEMA_IDS2.resourceRef]: ResourceRefSchema2, - [SCHEMA_IDS2.evidenceRef]: EvidenceRefSchema2, - [SCHEMA_IDS2.workRun]: WorkRunSchema2, - [SCHEMA_IDS2.decisionEnvelope]: DecisionEnvelopeSchema2, - [SCHEMA_IDS2.costEstimate]: CostEstimateSchema2, - [SCHEMA_IDS2.capabilityCard]: CapabilityCardSchema2, - [SCHEMA_IDS2.providerLiveModeStandard]: ProviderLiveModeStandardSchema2, - [SCHEMA_IDS2.contextPack]: ContextPackSchema2, - [SCHEMA_IDS2.integrationRef]: IntegrationRefSchema2, - [SCHEMA_IDS2.projectManifest]: ProjectManifestSchema2, - [SCHEMA_IDS2.projectPanel]: ProjectPanelSchema2, - [SCHEMA_IDS2.projectSnapshot]: ProjectSnapshotSchema2, - [SCHEMA_IDS2.renderManifest]: RenderManifestSchema2, - [SCHEMA_IDS2.agentTrajectory]: AgentTrajectorySchema2, - [SCHEMA_IDS2.validationPlan]: ValidationPlanSchema2, - [SCHEMA_IDS2.proofBundle]: ProofBundleSchema2, - [SCHEMA_IDS2.scaffoldManifest]: ScaffoldManifestSchema2, - [SCHEMA_IDS2.scaffoldInstallRecord]: ScaffoldInstallRecordSchema2, - [SCHEMA_IDS2.appCloudManifest]: AppCloudManifestSchema2, - [SCHEMA_IDS2.noCloudEvidencePack]: NoCloudEvidencePackSchema2, - [SCHEMA_IDS2.serviceContract]: ServiceContractManifestSchema2, - [SCHEMA_IDS2.commsEventEnvelope]: CommsEventEnvelopeSchema2, - [SCHEMA_IDS2.commsChannelMetadata]: CommsChannelMetadataSchema2, - [SCHEMA_IDS2.commsMessageMetadata]: CommsMessageMetadataSchema2, - [SCHEMA_IDS2.app]: AppSchema2, - [SCHEMA_IDS2.release]: ReleaseSchema2, - [SCHEMA_IDS2.rolloutRecord]: RolloutRecordSchema2, - [SCHEMA_IDS2.announcement]: AnnouncementSchema2, - [SCHEMA_IDS2.audience]: AudienceSchema2 -}; -function envToken2(name) { - return name.toUpperCase().replace(/-/g, "_"); -} -function clientTransportEnvKeys2(name) { - const envSegment = envToken2(name); - return { - modeKeys: [ - `HASNA_${envSegment}_STORAGE_MODE`, - `HASNA_${envSegment}_MODE`, - `${envSegment}_STORAGE_MODE`, - `${envSegment}_MODE` - ], - apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], - apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] - }; -} -var IDEMPOTENT_METHODS2 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); - -// node_modules/@hasna/contracts/dist/mode.js -var __defProp4 = Object.defineProperty; -var __returnValue4 = (v) => v; -function __exportSetter4(name, newValue) { - this[name] = __returnValue4.bind(null, newValue); -} -var __export4 = (target, all) => { - for (var name in all) - __defProp4(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter4.bind(all, name) - }); -}; -var exports_external3 = {}; -__export4(exports_external3, { - void: () => voidType3, - util: () => util3, - unknown: () => unknownType3, - union: () => unionType3, - undefined: () => undefinedType3, - tuple: () => tupleType3, - transformer: () => effectsType3, - symbol: () => symbolType3, - string: () => stringType3, - strictObject: () => strictObjectType3, - setErrorMap: () => setErrorMap3, - set: () => setType3, - record: () => recordType3, - quotelessJson: () => quotelessJson3, - promise: () => promiseType3, - preprocess: () => preprocessType3, - pipeline: () => pipelineType3, - ostring: () => ostring3, - optional: () => optionalType3, - onumber: () => onumber3, - oboolean: () => oboolean3, - objectUtil: () => objectUtil3, - object: () => objectType3, - number: () => numberType3, - nullable: () => nullableType3, - null: () => nullType3, - never: () => neverType3, - nativeEnum: () => nativeEnumType3, - nan: () => nanType3, - map: () => mapType3, - makeIssue: () => makeIssue3, - literal: () => literalType3, - lazy: () => lazyType3, - late: () => late3, - isValid: () => isValid3, - isDirty: () => isDirty3, - isAsync: () => isAsync3, - isAborted: () => isAborted3, - intersection: () => intersectionType3, - instanceof: () => instanceOfType3, - getParsedType: () => getParsedType3, - getErrorMap: () => getErrorMap3, - function: () => functionType3, - enum: () => enumType3, - effect: () => effectsType3, - discriminatedUnion: () => discriminatedUnionType3, - defaultErrorMap: () => en_default3, - datetimeRegex: () => datetimeRegex3, - date: () => dateType3, - custom: () => custom3, - coerce: () => coerce3, - boolean: () => booleanType3, - bigint: () => bigIntType3, - array: () => arrayType3, - any: () => anyType3, - addIssueToContext: () => addIssueToContext3, - ZodVoid: () => ZodVoid3, - ZodUnknown: () => ZodUnknown3, - ZodUnion: () => ZodUnion3, - ZodUndefined: () => ZodUndefined3, - ZodType: () => ZodType3, - ZodTuple: () => ZodTuple3, - ZodTransformer: () => ZodEffects3, - ZodSymbol: () => ZodSymbol3, - ZodString: () => ZodString3, - ZodSet: () => ZodSet3, - ZodSchema: () => ZodType3, - ZodRecord: () => ZodRecord3, - ZodReadonly: () => ZodReadonly3, - ZodPromise: () => ZodPromise3, - ZodPipeline: () => ZodPipeline3, - ZodParsedType: () => ZodParsedType3, - ZodOptional: () => ZodOptional3, - ZodObject: () => ZodObject3, - ZodNumber: () => ZodNumber3, - ZodNullable: () => ZodNullable3, - ZodNull: () => ZodNull3, - ZodNever: () => ZodNever3, - ZodNativeEnum: () => ZodNativeEnum3, - ZodNaN: () => ZodNaN3, - ZodMap: () => ZodMap3, - ZodLiteral: () => ZodLiteral3, - ZodLazy: () => ZodLazy3, - ZodIssueCode: () => ZodIssueCode3, - ZodIntersection: () => ZodIntersection3, - ZodFunction: () => ZodFunction3, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind3, - ZodError: () => ZodError3, - ZodEnum: () => ZodEnum3, - ZodEffects: () => ZodEffects3, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion3, - ZodDefault: () => ZodDefault3, - ZodDate: () => ZodDate3, - ZodCatch: () => ZodCatch3, - ZodBranded: () => ZodBranded3, - ZodBoolean: () => ZodBoolean3, - ZodBigInt: () => ZodBigInt3, - ZodArray: () => ZodArray3, - ZodAny: () => ZodAny3, - Schema: () => ZodType3, - ParseStatus: () => ParseStatus3, - OK: () => OK3, - NEVER: () => NEVER3, - INVALID: () => INVALID3, - EMPTY_PATH: () => EMPTY_PATH3, - DIRTY: () => DIRTY3, - BRAND: () => BRAND3 -}); -var util3; -(function(util22) { - util22.assertEqual = (_) => {}; - function assertIs(_arg) {} - util22.assertIs = assertIs; - function assertNever(_x) { - throw new Error; - } - util22.assertNever = assertNever; - util22.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util22.getValidEnumValues = (obj) => { - const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util22.objectValues(filtered); - }; - util22.objectValues = (obj) => { - return util22.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util22.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util22.joinValues = joinValues; - util22.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util3 || (util3 = {})); -var objectUtil3; -(function(objectUtil22) { - objectUtil22.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; -})(objectUtil3 || (objectUtil3 = {})); -var ZodParsedType3 = util3.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType3 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType3.undefined; - case "string": - return ZodParsedType3.string; - case "number": - return Number.isNaN(data) ? ZodParsedType3.nan : ZodParsedType3.number; - case "boolean": - return ZodParsedType3.boolean; - case "function": - return ZodParsedType3.function; - case "bigint": - return ZodParsedType3.bigint; - case "symbol": - return ZodParsedType3.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType3.array; - } - if (data === null) { - return ZodParsedType3.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType3.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType3.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType3.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType3.date; - } - return ZodParsedType3.object; - default: - return ZodParsedType3.unknown; - } -}; -var ZodIssueCode3 = util3.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson3 = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; - -class ZodError3 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError3)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util3.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError3.create = (issues) => { - const error = new ZodError3(issues); - return error; -}; -var errorMap3 = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode3.invalid_type: - if (issue.received === ZodParsedType3.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode3.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util3.jsonStringifyReplacer)}`; - break; - case ZodIssueCode3.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util3.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode3.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode3.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util3.joinValues(issue.options)}`; - break; - case ZodIssueCode3.invalid_enum_value: - message = `Invalid enum value. Expected ${util3.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode3.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode3.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode3.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode3.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util3.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode3.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode3.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode3.custom: - message = `Invalid input`; - break; - case ZodIssueCode3.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode3.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode3.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util3.assertNever(issue); - } - return { message }; -}; -var en_default3 = errorMap3; -var overrideErrorMap3 = en_default3; -function setErrorMap3(map) { - overrideErrorMap3 = map; -} -function getErrorMap3() { - return overrideErrorMap3; -} -var makeIssue3 = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH3 = []; -function addIssueToContext3(ctx, issueData) { - const overrideMap = getErrorMap3(); - const issue = makeIssue3({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default3 ? undefined : en_default3 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); -} - -class ParseStatus3 { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID3; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus3.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID3; - if (value.status === "aborted") - return INVALID3; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -var INVALID3 = Object.freeze({ - status: "aborted" -}); -var DIRTY3 = (value) => ({ status: "dirty", value }); -var OK3 = (value) => ({ status: "valid", value }); -var isAborted3 = (x) => x.status === "aborted"; -var isDirty3 = (x) => x.status === "dirty"; -var isValid3 = (x) => x.status === "valid"; -var isAsync3 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil3; -(function(errorUtil22) { - errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil3 || (errorUtil3 = {})); - -class ParseInputLazyPath3 { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -var handleResult3 = (ctx, result) => { - if (isValid3(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError3(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams3(params) { - if (!params) - return {}; - const { errorMap: errorMap22, invalid_type_error, required_error, description } = params; - if (errorMap22 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap22) - return { errorMap: errorMap22, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -class ZodType3 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType3(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType3(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus3, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType3(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync3(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult3(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid3(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid3(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync3(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult3(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode3.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects3({ - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional3.create(this, this._def); - } - nullable() { - return ZodNullable3.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray3.create(this); - } - promise() { - return ZodPromise3.create(this, this._def); - } - or(option) { - return ZodUnion3.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection3.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects3({ - ...processCreateParams3(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault3({ - ...processCreateParams3(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodDefault - }); - } - brand() { - return new ZodBranded3({ - typeName: ZodFirstPartyTypeKind3.ZodBranded, - type: this, - ...processCreateParams3(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch3({ - ...processCreateParams3(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline3.create(this, target); - } - readonly() { - return ZodReadonly3.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex3 = /^c[^\s-]{8,}$/i; -var cuid2Regex3 = /^[0-9a-z]+$/; -var ulidRegex3 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex3 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex3 = /^[a-z0-9_-]{21}$/i; -var jwtRegex3 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex3 = /^[-+]?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)?)??$/; -var emailRegex3 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex3; -var ipv4Regex3 = /^(?:(?: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])$/; -var ipv4CidrRegex3 = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex3 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex3 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex3 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex3 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource3 = `((\\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])))`; -var dateRegex3 = new RegExp(`^${dateRegexSource3}$`); -function timeRegexSource3(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex3(args) { - return new RegExp(`^${timeRegexSource3(args)}$`); -} -function datetimeRegex3(args) { - let regex = `${dateRegexSource3}T${timeRegexSource3(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP3(ip, version) { - if ((version === "v4" || !version) && ipv4Regex3.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex3.test(ip)) { - return true; - } - return false; -} -function isValidJWT3(jwt, alg) { - if (!jwtRegex3.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr3(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex3.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex3.test(ip)) { - return true; - } - return false; -} - -class ZodString3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.string, - received: ctx2.parsedType - }); - return INVALID3; - } - const status = new ParseStatus3; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "email", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex3) { - emojiRegex3 = new RegExp(_emojiRegex3, "u"); - } - if (!emojiRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "emoji", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "uuid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "nanoid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cuid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cuid2", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "ulid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "url", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "regex", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex3(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex3; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex3(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "duration", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP3(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "ip", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT3(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "jwt", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr3(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cidr", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "base64", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "base64url", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode3.invalid_string, - ...errorUtil3.errToObj(message) - }); - } - _addCheck(check) { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil3.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil3.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil3.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil3.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil3.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil3.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil3.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil3.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil3.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil3.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil3.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil3.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil3.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil3.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil3.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil3.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil3.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil3.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil3.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil3.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil3.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil3.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil3.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil3.errToObj(message)); - } - trim() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString3.create = (params) => { - return new ZodString3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams3(params) - }); -}; -function floatSafeRemainder3(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} - -class ZodNumber3 extends ZodType3 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.number, - received: ctx2.parsedType - }); - return INVALID3; - } - let ctx = undefined; - const status = new ParseStatus3; - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util3.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder3(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil3.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil3.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil3.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil3.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber3({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil3.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodNumber3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil3.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil3.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil3.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil3.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil3.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil3.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil3.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil3.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil3.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util3.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber3.create = (params) => { - return new ZodNumber3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams3(params) - }); -}; - -class ZodBigInt3 extends ZodType3 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus3; - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.bigint, - received: ctx.parsedType - }); - return INVALID3; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil3.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil3.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil3.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil3.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt3({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil3.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodBigInt3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil3.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil3.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil3.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil3.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil3.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt3.create = (params) => { - return new ZodBigInt3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams3(params) - }); -}; - -class ZodBoolean3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.boolean, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodBoolean3.create = (params) => { - return new ZodBoolean3({ - typeName: ZodFirstPartyTypeKind3.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams3(params) - }); -}; - -class ZodDate3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.date, - received: ctx2.parsedType - }); - return INVALID3; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_date - }); - return INVALID3; - } - const status = new ParseStatus3; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new ZodDate3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil3.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil3.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate3.create = (params) => { - return new ZodDate3({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind3.ZodDate, - ...processCreateParams3(params) - }); -}; - -class ZodSymbol3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.symbol, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodSymbol3.create = (params) => { - return new ZodSymbol3({ - typeName: ZodFirstPartyTypeKind3.ZodSymbol, - ...processCreateParams3(params) - }); -}; - -class ZodUndefined3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.undefined, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodUndefined3.create = (params) => { - return new ZodUndefined3({ - typeName: ZodFirstPartyTypeKind3.ZodUndefined, - ...processCreateParams3(params) - }); -}; - -class ZodNull3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.null, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodNull3.create = (params) => { - return new ZodNull3({ - typeName: ZodFirstPartyTypeKind3.ZodNull, - ...processCreateParams3(params) - }); -}; - -class ZodAny3 extends ZodType3 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK3(input.data); - } -} -ZodAny3.create = (params) => { - return new ZodAny3({ - typeName: ZodFirstPartyTypeKind3.ZodAny, - ...processCreateParams3(params) - }); -}; - -class ZodUnknown3 extends ZodType3 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK3(input.data); - } -} -ZodUnknown3.create = (params) => { - return new ZodUnknown3({ - typeName: ZodFirstPartyTypeKind3.ZodUnknown, - ...processCreateParams3(params) - }); -}; - -class ZodNever3 extends ZodType3 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.never, - received: ctx.parsedType - }); - return INVALID3; - } -} -ZodNever3.create = (params) => { - return new ZodNever3({ - typeName: ZodFirstPartyTypeKind3.ZodNever, - ...processCreateParams3(params) - }); -}; - -class ZodVoid3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.void, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodVoid3.create = (params) => { - return new ZodVoid3({ - typeName: ZodFirstPartyTypeKind3.ZodVoid, - ...processCreateParams3(params) - }); -}; - -class ZodArray3 extends ZodType3 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType3.array) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.array, - received: ctx.parsedType - }); - return INVALID3; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext3(ctx, { - code: tooBig ? ZodIssueCode3.too_big : ZodIssueCode3.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath3(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus3.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath3(ctx, item, ctx.path, i)); - }); - return ParseStatus3.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray3({ - ...this._def, - minLength: { value: minLength, message: errorUtil3.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray3({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil3.toString(message) } - }); - } - length(len, message) { - return new ZodArray3({ - ...this._def, - exactLength: { value: len, message: errorUtil3.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray3.create = (schema, params) => { - return new ZodArray3({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind3.ZodArray, - ...processCreateParams3(params) - }); -}; -function deepPartialify3(schema) { - if (schema instanceof ZodObject3) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional3.create(deepPartialify3(fieldSchema)); - } - return new ZodObject3({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray3) { - return new ZodArray3({ - ...schema._def, - type: deepPartialify3(schema.element) - }); - } else if (schema instanceof ZodOptional3) { - return ZodOptional3.create(deepPartialify3(schema.unwrap())); - } else if (schema instanceof ZodNullable3) { - return ZodNullable3.create(deepPartialify3(schema.unwrap())); - } else if (schema instanceof ZodTuple3) { - return ZodTuple3.create(schema.items.map((item) => deepPartialify3(item))); - } else { - return schema; - } -} - -class ZodObject3 extends ZodType3 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util3.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.object, - received: ctx2.parsedType - }); - return INVALID3; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever3 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever3) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus3.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus3.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil3.errToObj; - return new ZodObject3({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil3.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject3({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject3({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject3({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject3({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind3.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject3({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util3.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject3({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject3({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify3(this); - } - partial(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject3({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional3) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject3({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum3(util3.objectKeys(this.shape)); - } -} -ZodObject3.create = (shape, params) => { - return new ZodObject3({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams3(params) - }); -}; -ZodObject3.strictCreate = (shape, params) => { - return new ZodObject3({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams3(params) - }); -}; -ZodObject3.lazycreate = (shape, params) => { - return new ZodObject3({ - shape, - unknownKeys: "strip", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams3(params) - }); -}; - -class ZodUnion3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError3(result.ctx.common.issues)); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_union, - unionErrors - }); - return INVALID3; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError3(issues2)); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_union, - unionErrors - }); - return INVALID3; - } - } - get options() { - return this._def.options; - } -} -ZodUnion3.create = (types, params) => { - return new ZodUnion3({ - options: types, - typeName: ZodFirstPartyTypeKind3.ZodUnion, - ...processCreateParams3(params) - }); -}; -var getDiscriminator3 = (type) => { - if (type instanceof ZodLazy3) { - return getDiscriminator3(type.schema); - } else if (type instanceof ZodEffects3) { - return getDiscriminator3(type.innerType()); - } else if (type instanceof ZodLiteral3) { - return [type.value]; - } else if (type instanceof ZodEnum3) { - return type.options; - } else if (type instanceof ZodNativeEnum3) { - return util3.objectValues(type.enum); - } else if (type instanceof ZodDefault3) { - return getDiscriminator3(type._def.innerType); - } else if (type instanceof ZodUndefined3) { - return [undefined]; - } else if (type instanceof ZodNull3) { - return [null]; - } else if (type instanceof ZodOptional3) { - return [undefined, ...getDiscriminator3(type.unwrap())]; - } else if (type instanceof ZodNullable3) { - return [null, ...getDiscriminator3(type.unwrap())]; - } else if (type instanceof ZodBranded3) { - return getDiscriminator3(type.unwrap()); - } else if (type instanceof ZodReadonly3) { - return getDiscriminator3(type.unwrap()); - } else if (type instanceof ZodCatch3) { - return getDiscriminator3(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.object) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.object, - received: ctx.parsedType - }); - return INVALID3; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID3; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator3(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion3({ - typeName: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams3(params) - }); - } -} -function mergeValues3(a, b) { - const aType = getParsedType3(a); - const bType = getParsedType3(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType3.object && bType === ZodParsedType3.object) { - const bKeys = util3.objectKeys(b); - const sharedKeys = util3.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues3(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType3.array && bType === ZodParsedType3.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues3(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType3.date && bType === ZodParsedType3.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted3(parsedLeft) || isAborted3(parsedRight)) { - return INVALID3; - } - const merged = mergeValues3(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_intersection_types - }); - return INVALID3; - } - if (isDirty3(parsedLeft) || isDirty3(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection3.create = (left, right, params) => { - return new ZodIntersection3({ - left, - right, - typeName: ZodFirstPartyTypeKind3.ZodIntersection, - ...processCreateParams3(params) - }); -}; - -class ZodTuple3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.array) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.array, - received: ctx.parsedType - }); - return INVALID3; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID3; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath3(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus3.mergeArray(status, results); - }); - } else { - return ParseStatus3.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple3({ - ...this._def, - rest - }); - } -} -ZodTuple3.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple3({ - items: schemas, - typeName: ZodFirstPartyTypeKind3.ZodTuple, - rest: null, - ...processCreateParams3(params) - }); -}; - -class ZodRecord3 extends ZodType3 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.object) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.object, - received: ctx.parsedType - }); - return INVALID3; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath3(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus3.mergeObjectAsync(status, pairs); - } else { - return ParseStatus3.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType3) { - return new ZodRecord3({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams3(third) - }); - } - return new ZodRecord3({ - keyType: ZodString3.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams3(second) - }); - } -} - -class ZodMap3 extends ZodType3 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.map) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.map, - received: ctx.parsedType - }); - return INVALID3; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath3(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID3; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID3; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap3.create = (keyType, valueType, params) => { - return new ZodMap3({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind3.ZodMap, - ...processCreateParams3(params) - }); -}; - -class ZodSet3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.set) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.set, - received: ctx.parsedType - }); - return INVALID3; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID3; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath3(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet3({ - ...this._def, - minSize: { value: minSize, message: errorUtil3.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet3({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil3.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet3.create = (valueType, params) => { - return new ZodSet3({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind3.ZodSet, - ...processCreateParams3(params) - }); -}; - -class ZodFunction3 extends ZodType3 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.function) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.function, - received: ctx.parsedType - }); - return INVALID3; - } - function makeArgsIssue(args, error) { - return makeIssue3({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap3(), en_default3].filter((x) => !!x), - issueData: { - code: ZodIssueCode3.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue3({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap3(), en_default3].filter((x) => !!x), - issueData: { - code: ZodIssueCode3.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise3) { - const me = this; - return OK3(async function(...args) { - const error = new ZodError3([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK3(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError3([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError3([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction3({ - ...this._def, - args: ZodTuple3.create(items).rest(ZodUnknown3.create()) - }); - } - returns(returnType) { - return new ZodFunction3({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction3({ - args: args ? args : ZodTuple3.create([]).rest(ZodUnknown3.create()), - returns: returns || ZodUnknown3.create(), - typeName: ZodFirstPartyTypeKind3.ZodFunction, - ...processCreateParams3(params) - }); - } -} - -class ZodLazy3 extends ZodType3 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy3.create = (getter, params) => { - return new ZodLazy3({ - getter, - typeName: ZodFirstPartyTypeKind3.ZodLazy, - ...processCreateParams3(params) - }); -}; - -class ZodLiteral3 extends ZodType3 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_literal, - expected: this._def.value - }); - return INVALID3; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral3.create = (value, params) => { - return new ZodLiteral3({ - value, - typeName: ZodFirstPartyTypeKind3.ZodLiteral, - ...processCreateParams3(params) - }); -}; -function createZodEnum3(values, params) { - return new ZodEnum3({ - values, - typeName: ZodFirstPartyTypeKind3.ZodEnum, - ...processCreateParams3(params) - }); -} - -class ZodEnum3 extends ZodType3 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext3(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode3.invalid_type - }); - return INVALID3; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_enum_value, - options: expectedValues - }); - return INVALID3; - } - return OK3(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum3.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum3.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum3.create = createZodEnum3; - -class ZodNativeEnum3 extends ZodType3 { - _parse(input) { - const nativeEnumValues = util3.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType3.string && ctx.parsedType !== ZodParsedType3.number) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext3(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode3.invalid_type - }); - return INVALID3; - } - if (!this._cache) { - this._cache = new Set(util3.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_enum_value, - options: expectedValues - }); - return INVALID3; - } - return OK3(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum3.create = (values, params) => { - return new ZodNativeEnum3({ - values, - typeName: ZodFirstPartyTypeKind3.ZodNativeEnum, - ...processCreateParams3(params) - }); -}; - -class ZodPromise3 extends ZodType3 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.promise && ctx.common.async === false) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.promise, - received: ctx.parsedType - }); - return INVALID3; - } - const promisified = ctx.parsedType === ZodParsedType3.promise ? ctx.data : Promise.resolve(ctx.data); - return OK3(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise3.create = (schema, params) => { - return new ZodPromise3({ - type: schema, - typeName: ZodFirstPartyTypeKind3.ZodPromise, - ...processCreateParams3(params) - }); -}; - -class ZodEffects3 extends ZodType3 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext3(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID3; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID3; - if (result.status === "dirty") - return DIRTY3(result.value); - if (status.value === "dirty") - return DIRTY3(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID3; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID3; - if (result.status === "dirty") - return DIRTY3(result.value); - if (status.value === "dirty") - return DIRTY3(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID3; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID3; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid3(base)) - return INVALID3; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid3(base)) - return INVALID3; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util3.assertNever(effect); - } -} -ZodEffects3.create = (schema, effect, params) => { - return new ZodEffects3({ - schema, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect, - ...processCreateParams3(params) - }); -}; -ZodEffects3.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects3({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - ...processCreateParams3(params) - }); -}; - -class ZodOptional3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType3.undefined) { - return OK3(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional3.create = (type, params) => { - return new ZodOptional3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodOptional, - ...processCreateParams3(params) - }); -}; - -class ZodNullable3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType3.null) { - return OK3(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable3.create = (type, params) => { - return new ZodNullable3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodNullable, - ...processCreateParams3(params) - }); -}; - -class ZodDefault3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType3.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault3.create = (type, params) => { - return new ZodDefault3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams3(params) - }); -}; - -class ZodCatch3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync3(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError3(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError3(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch3.create = (type, params) => { - return new ZodCatch3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams3(params) - }); -}; - -class ZodNaN3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.nan, - received: ctx.parsedType - }); - return INVALID3; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN3.create = (params) => { - return new ZodNaN3({ - typeName: ZodFirstPartyTypeKind3.ZodNaN, - ...processCreateParams3(params) - }); -}; -var BRAND3 = Symbol("zod_brand"); - -class ZodBranded3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID3; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY3(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID3; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline3({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind3.ZodPipeline - }); - } -} - -class ZodReadonly3 extends ZodType3 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid3(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync3(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly3.create = (type, params) => { - return new ZodReadonly3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodReadonly, - ...processCreateParams3(params) - }); -}; -function cleanParams3(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom3(check, _params = {}, fatal) { - if (check) - return ZodAny3.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams3(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams3(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny3.create(); -} -var late3 = { - object: ZodObject3.lazycreate -}; -var ZodFirstPartyTypeKind3; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind3 || (ZodFirstPartyTypeKind3 = {})); -var instanceOfType3 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom3((data) => data instanceof cls, params); -var stringType3 = ZodString3.create; -var numberType3 = ZodNumber3.create; -var nanType3 = ZodNaN3.create; -var bigIntType3 = ZodBigInt3.create; -var booleanType3 = ZodBoolean3.create; -var dateType3 = ZodDate3.create; -var symbolType3 = ZodSymbol3.create; -var undefinedType3 = ZodUndefined3.create; -var nullType3 = ZodNull3.create; -var anyType3 = ZodAny3.create; -var unknownType3 = ZodUnknown3.create; -var neverType3 = ZodNever3.create; -var voidType3 = ZodVoid3.create; -var arrayType3 = ZodArray3.create; -var objectType3 = ZodObject3.create; -var strictObjectType3 = ZodObject3.strictCreate; -var unionType3 = ZodUnion3.create; -var discriminatedUnionType3 = ZodDiscriminatedUnion3.create; -var intersectionType3 = ZodIntersection3.create; -var tupleType3 = ZodTuple3.create; -var recordType3 = ZodRecord3.create; -var mapType3 = ZodMap3.create; -var setType3 = ZodSet3.create; -var functionType3 = ZodFunction3.create; -var lazyType3 = ZodLazy3.create; -var literalType3 = ZodLiteral3.create; -var enumType3 = ZodEnum3.create; -var nativeEnumType3 = ZodNativeEnum3.create; -var promiseType3 = ZodPromise3.create; -var effectsType3 = ZodEffects3.create; -var optionalType3 = ZodOptional3.create; -var nullableType3 = ZodNullable3.create; -var preprocessType3 = ZodEffects3.createWithPreprocess; -var pipelineType3 = ZodPipeline3.create; -var ostring3 = () => stringType3().optional(); -var onumber3 = () => numberType3().optional(); -var oboolean3 = () => booleanType3().optional(); -var coerce3 = { - string: (arg) => ZodString3.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber3.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean3.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt3.create({ ...arg, coerce: true }), - date: (arg) => ZodDate3.create({ ...arg, coerce: true }) -}; -var NEVER3 = INVALID3; -var SCHEMA_IDS3 = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema3 = exports_external3.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema3 = exports_external3.string().datetime(); -var NonEmptyStringSchema3 = exports_external3.string().trim().min(1); -var UriSchema3 = NonEmptyStringSchema3.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema3 = exports_external3.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema3 = exports_external3.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema3 = exports_external3.record(exports_external3.unknown()); -var TagsSchema3 = exports_external3.array(exports_external3.string().min(1)).default([]); -var OptionalTimestampSchema3 = TimestampSchema3.nullable().optional(); -var TerminalStatuses3 = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema3 = exports_external3.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema3(schema) { - return exports_external3.object({ - schema: exports_external3.literal(schema), - id: exports_external3.string().min(1), - createdAt: TimestampSchema3, - updatedAt: OptionalTimestampSchema3, - metadata: MetadataSchema3.optional() - }).strict(); -} -var ContractEnvelopeSchema3 = exports_external3.object({ - schema: SchemaIdSchema3, - id: exports_external3.string().min(1), - createdAt: TimestampSchema3, - updatedAt: OptionalTimestampSchema3, - metadata: MetadataSchema3.optional() -}).strict(); -var ActorKindSchema3 = exports_external3.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.actorRef).extend({ - kind: ActorKindSchema3, - name: exports_external3.string().min(1).optional(), - provider: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - machineId: exports_external3.string().min(1).optional(), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema3 = exports_external3.object({ - kind: ActorKindSchema3, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - provider: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - machineId: exports_external3.string().min(1).optional() -}).strict(); -var ResourceKindSchema3 = exports_external3.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.resourceRef).extend({ - kind: ResourceKindSchema3, - name: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema3 = exports_external3.object({ - kind: ResourceKindSchema3, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema3 = exports_external3.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema3 = exports_external3.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.evidenceRef).extend({ - kind: EvidenceKindSchema3, - uri: UriSchema3, - sha256: Sha256DigestSchema3.optional(), - summary: exports_external3.string().min(1).optional(), - contentType: exports_external3.string().min(1).optional(), - sizeBytes: exports_external3.number().int().nonnegative().optional(), - redaction: RedactionStateSchema3.default("unknown"), - producer: ActorPointerSchema3.optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - tags: TagsSchema3 -}).strict(); -var EvidencePointerSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: EvidenceKindSchema3.optional(), - uri: UriSchema3.optional(), - sha256: Sha256DigestSchema3.optional(), - summary: exports_external3.string().min(1).optional() -}).strict(); -var CostEstimateSchema3 = contractBaseSchema3(SCHEMA_IDS3.costEstimate).extend({ - currency: exports_external3.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external3.number().int().nonnegative(), - provider: exports_external3.string().min(1).optional(), - model: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - promptTokens: exports_external3.number().int().nonnegative().optional(), - completionTokens: exports_external3.number().int().nonnegative().optional(), - totalTokens: exports_external3.number().int().nonnegative().optional(), - basis: exports_external3.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema3 = exports_external3.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema3 = contractBaseSchema3(SCHEMA_IDS3.decisionEnvelope).extend({ - decisionType: exports_external3.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema3, - actor: ActorPointerSchema3.optional(), - traceId: exports_external3.string().min(1).optional(), - inputHash: HashStringSchema3.optional(), - policyBundleId: exports_external3.string().min(1).optional(), - selected: exports_external3.array(ResourcePointerSchema3).default([]), - skipped: exports_external3.array(ResourcePointerSchema3).default([]), - reason: exports_external3.string().min(1), - obligations: exports_external3.array(exports_external3.string().min(1)).default([]), - redactions: exports_external3.array(exports_external3.string().min(1)).default([]), - costEstimate: CostEstimateSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema3 = contractBaseSchema3(SCHEMA_IDS3.capabilityCard).extend({ - kind: exports_external3.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external3.string().min(1), - version: exports_external3.string().min(1).optional(), - status: exports_external3.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]), - limitations: exports_external3.array(exports_external3.string().min(1)).default([]), - riskLevel: exports_external3.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict(); -var ProviderModeSchema3 = exports_external3.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema3 = exports_external3.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema3 = exports_external3.object({ - refName: NonEmptyStringSchema3, - requiredForModes: exports_external3.array(ProviderModeSchema3).min(1), - allowedSecretInputs: exports_external3.array(exports_external3.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema3, - revocationCheck: exports_external3.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema3 = exports_external3.object({ - operation: NonEmptyStringSchema3, - supportedModes: exports_external3.array(ProviderModeSchema3).min(1), - sideEffectClass: ProviderSideEffectClassSchema3, - requiresApproval: exports_external3.boolean().default(false), - requiresIdempotencyKey: exports_external3.boolean().default(false), - requiresSandboxEvidence: exports_external3.boolean().default(false), - requiresRollbackOrRevocation: exports_external3.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema3.optional(), - noSideEffectSmoke: NonEmptyStringSchema3.optional(), - reconciliation: NonEmptyStringSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema3 = exports_external3.object({ - providerId: NonEmptyStringSchema3, - appId: NonEmptyStringSchema3, - adapterId: NonEmptyStringSchema3, - ownerPackage: NonEmptyStringSchema3, - modes: exports_external3.array(ProviderModeSchema3).min(1), - defaultMode: ProviderModeSchema3, - credentialRequirements: exports_external3.array(CredentialRequirementSchema3).default([]), - operations: exports_external3.array(ProviderOperationCardSchema3).min(1), - rateLimitPosture: NonEmptyStringSchema3, - costPosture: NonEmptyStringSchema3.optional(), - auditEvents: exports_external3.array(NonEmptyStringSchema3).default([]), - redactionRules: exports_external3.array(NonEmptyStringSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema3 = exports_external3.object({ - appId: NonEmptyStringSchema3, - repo: NonEmptyStringSchema3, - priority: exports_external3.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external3.array(NonEmptyStringSchema3).min(1), - firstOperations: exports_external3.array(NonEmptyStringSchema3).min(1), - blockedUntil: exports_external3.array(NonEmptyStringSchema3).default([]) -}).strict(); -var ProviderLiveModeStandardSchema3 = contractBaseSchema3(SCHEMA_IDS3.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema3, - version: NonEmptyStringSchema3, - modes: exports_external3.array(ProviderModeSchema3).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external3.array(NonEmptyStringSchema3).min(1), - liveMutationGate: exports_external3.object({ - requiredMode: exports_external3.literal("live_mutating"), - requiredChecks: exports_external3.array(NonEmptyStringSchema3).min(1), - forbiddenBypassSignals: exports_external3.array(NonEmptyStringSchema3).min(1), - disabledLiveSmoke: NonEmptyStringSchema3 - }).strict(), - noSideEffectSmoke: exports_external3.object({ - requiredForModes: exports_external3.array(ProviderModeSchema3).min(1), - commandEvidence: exports_external3.array(NonEmptyStringSchema3).min(1), - secretOutputScan: exports_external3.boolean().default(true) - }).strict(), - credentialPolicy: exports_external3.object({ - acceptedInputs: exports_external3.array(exports_external3.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external3.literal(false), - missingCredentialBehavior: exports_external3.literal("fail_closed"), - revocationCheckRequired: exports_external3.boolean().default(true) - }).strict(), - operationCards: exports_external3.array(ProviderCapabilityCardSchema3).min(1), - firstAdoptionTargets: exports_external3.array(ProviderLiveModeTargetSchema3).min(1), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1).optional(), - summary: exports_external3.string().min(1), - text: exports_external3.string().optional(), - tokens: exports_external3.number().int().nonnegative().optional(), - source: EvidencePointerSchema3, - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict(); -var ContextPackSchema3 = contractBaseSchema3(SCHEMA_IDS3.contextPack).extend({ - objective: exports_external3.string().min(1), - budget: exports_external3.object({ - maxTokens: exports_external3.number().int().positive().optional(), - maxBytes: exports_external3.number().int().positive().optional() - }).strict().optional(), - items: exports_external3.array(ContextPackItemSchema3).default([]), - citations: exports_external3.array(EvidencePointerSchema3).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external3.array(exports_external3.string().min(1)).default([]), - redactions: exports_external3.array(exports_external3.string().min(1)).default([]), - conflicts: exports_external3.array(exports_external3.string().min(1)).default([]), - uncertainty: exports_external3.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema3 = NonEmptyStringSchema3.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema3 = exports_external3.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema3 = exports_external3.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema3 = exports_external3.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema3 = exports_external3.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.integrationRef).extend({ - kind: ProjectIntegrationKindSchema3, - name: exports_external3.string().min(1), - projectId: ProjectSlugSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - uri: UriSchema3.optional(), - enabled: exports_external3.boolean().default(true), - readOnly: exports_external3.boolean().default(true), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - config: MetadataSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema3 = exports_external3.object({ - schemaRoot: RelativeProjectPathSchema3.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema3.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema3.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema3.default("documents"), - reportsDir: RelativeProjectPathSchema3.default("reports"), - evidenceDir: RelativeProjectPathSchema3.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema3.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectManifest).extend({ - projectId: ProjectSlugSchema3, - slug: ProjectSlugSchema3, - name: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - status: ProjectStatusSchema3.default("active"), - classification: ProjectClassificationSchema3.default("private"), - owner: ActorPointerSchema3.optional(), - layout: ProjectLayoutSchema3.default({}), - integrations: exports_external3.array(IntegrationRefSchema3).default([]), - renderManifests: exports_external3.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema3 = exports_external3.enum(["local", "package", "provider", "url"]); -var RenderImportSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: RenderImportKindSchema3, - specifier: exports_external3.string().min(1), - path: RelativeProjectPathSchema3.optional(), - packageName: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - provider: ProjectIntegrationKindSchema3.optional(), - schemaId: SchemaIdSchema3.optional(), - integrity: HashStringSchema3.optional(), - resourceRef: ResourcePointerSchema3.optional(), - optional: exports_external3.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema3 = exports_external3.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1), - kind: RenderViewKindSchema3, - default: exports_external3.boolean().default(false), - entry: RelativeProjectPathSchema3.optional(), - imports: exports_external3.array(RenderImportSchema3).default([]), - panelRefs: exports_external3.array(ResourcePointerSchema3).default([]), - dataRefs: exports_external3.array(ResourcePointerSchema3).default([]), - layout: MetadataSchema3.optional() -}).strict(); -var RenderManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.renderManifest).extend({ - projectId: ProjectSlugSchema3, - name: exports_external3.string().min(1), - version: exports_external3.string().min(1), - manifestPath: RelativeProjectPathSchema3.default(".hasna/project/dashboard.render.json"), - renderer: exports_external3.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external3.array(RenderViewSchema3).min(1), - imports: exports_external3.array(RenderImportSchema3).default([]), - theme: MetadataSchema3.optional(), - compatibility: exports_external3.object({ - minProjectsVersion: exports_external3.string().min(1).optional(), - minContractsVersion: exports_external3.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema3 = exports_external3.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema3 = exports_external3.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - label: exports_external3.string().min(1), - value: exports_external3.union([exports_external3.string(), exports_external3.number(), exports_external3.boolean()]), - unit: exports_external3.string().min(1).optional(), - status: exports_external3.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict(); -var ProjectPanelItemSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - status: exports_external3.string().min(1).optional(), - priority: exports_external3.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema3.optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - metadata: MetadataSchema3.optional() -}).strict(); -var ProjectRenderFragmentSchema3 = exports_external3.object({ - renderer: exports_external3.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external3.string().min(1).optional(), - entry: RelativeProjectPathSchema3.optional(), - imports: exports_external3.array(RenderImportSchema3).default([]), - spec: MetadataSchema3.default({}) -}).strict(); -var ProjectPanelSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectPanel).extend({ - projectId: ProjectSlugSchema3, - provider: exports_external3.object({ - kind: ProjectIntegrationKindSchema3, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - externalId: NonEmptyStringSchema3.optional() - }).strict(), - kind: ProjectPanelKindSchema3, - title: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - state: ProjectPanelStateSchema3.default("ready"), - stateReason: exports_external3.string().min(1).optional(), - generatedAt: TimestampSchema3, - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external3.array(ProjectPanelMetricSchema3).default([]), - items: exports_external3.array(ProjectPanelItemSchema3).default([]), - actions: exports_external3.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - renderFragment: ProjectRenderFragmentSchema3.optional(), - warnings: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectSnapshot).extend({ - projectId: ProjectSlugSchema3, - generatedAt: TimestampSchema3, - status: ContractStatusSchema3.default("unknown"), - manifestRef: ResourcePointerSchema3, - renderManifestRef: ResourcePointerSchema3.optional(), - panels: exports_external3.array(ProjectPanelSchema3).default([]), - contextPacks: exports_external3.array(ContextPackSchema3).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - warnings: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: exports_external3.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external3.boolean().default(true), - command: exports_external3.string().min(1).optional(), - expected: exports_external3.string().min(1).optional(), - timeoutMs: exports_external3.number().int().positive().optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema3 = contractBaseSchema3(SCHEMA_IDS3.validationPlan).extend({ - objective: exports_external3.string().min(1), - subject: ResourcePointerSchema3.optional(), - checks: exports_external3.array(ValidationCheckSchema3).min(1), - verifier: ActorPointerSchema3.optional(), - requiredEvidenceKinds: exports_external3.array(EvidenceKindSchema3).default([]) -}).strict(); -var ScaffoldTypeSchema3 = exports_external3.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema3 = exports_external3.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema3 = exports_external3.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema3 = exports_external3.object({ - key: exports_external3.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external3.string().min(1), - required: exports_external3.boolean().default(false), - ["secret"]: exports_external3.boolean().default(false), - group: exports_external3.string().min(1).optional(), - default: exports_external3.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema3 = exports_external3.object({ - name: exports_external3.string().min(1), - command: exports_external3.string().min(1), - description: exports_external3.string().min(1).optional(), - required: exports_external3.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema3 = exports_external3.object({ - packageManager: exports_external3.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external3.array(exports_external3.string().min(1)).default([]), - requiredFiles: exports_external3.array(exports_external3.string().min(1)).default([]), - requiredDirectories: exports_external3.array(exports_external3.string().min(1)).default([]), - optionalDirectories: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.scaffoldManifest).extend({ - name: exports_external3.string().min(1), - version: exports_external3.string().min(1), - summary: exports_external3.string().min(1), - type: ScaffoldTypeSchema3, - status: ScaffoldStatusSchema3.default("draft"), - capabilities: exports_external3.array(ScaffoldCapabilitySchema3).default([]), - techStack: exports_external3.array(exports_external3.string().min(1)).default([]), - tags: TagsSchema3, - source: ResourcePointerSchema3.optional(), - output: ScaffoldOutputShapeSchema3, - env: exports_external3.array(ScaffoldEnvVarSchema3).default([]), - scripts: exports_external3.array(ScaffoldScriptSchema3).default([]), - validationChecks: exports_external3.array(ValidationCheckSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema3 = exports_external3.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema3 = contractBaseSchema3(SCHEMA_IDS3.scaffoldInstallRecord).extend({ - scaffoldId: exports_external3.string().min(1), - scaffoldVersion: exports_external3.string().min(1).optional(), - manifestRef: ResourcePointerSchema3.optional(), - target: ResourcePointerSchema3, - status: ScaffoldInstallStatusSchema3, - installedAt: TimestampSchema3.optional(), - installer: ActorPointerSchema3.optional(), - packageManager: exports_external3.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema3.optional(), - generatedFiles: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema3 = exports_external3.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema3 = exports_external3.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema3 = exports_external3.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema3 = exports_external3.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema3 = NonEmptyStringSchema3.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema3 = exports_external3.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema3 = exports_external3.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema3 = exports_external3.object({ - transport: exports_external3.enum(["http", "stdio"]).default("http"), - bin: exports_external3.string().min(1).optional(), - url: UriSchema3.optional() -}).strict(); -var AppHttpSurfaceSchema3 = exports_external3.object({ - healthPath: exports_external3.string().min(1).default("/health"), - port: exports_external3.number().int().positive().optional(), - baseUrl: UriSchema3.optional() -}).strict(); -var AppSurfacesSchema3 = exports_external3.object({ - bins: exports_external3.array(exports_external3.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema3.optional(), - http: AppHttpSurfaceSchema3.optional() -}).strict(); -var AppSchema3 = contractBaseSchema3(SCHEMA_IDS3.app).extend({ - appId: AppIdSchema3, - npmName: NpmPackageNameSchema3, - repoFolder: AppIdSchema3, - githubUrl: GithubUrlSchema3, - projectSlug: ProjectSlugSchema3, - surfaces: AppSurfacesSchema3.default({}), - lifecycle: AppLifecycleSchema3, - releaseChannel: ReleaseChannelSchema3.default("stable"), - summary: exports_external3.string().min(1).optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema3 = exports_external3.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema3 = contractBaseSchema3(SCHEMA_IDS3.release).extend({ - appId: AppIdSchema3, - package: NpmPackageNameSchema3, - version: SemverSchema3, - gitSha: GitShaSchema3, - publishedAt: TimestampSchema3, - publishPath: PublishPathSchema3, - changelogRef: ResourcePointerSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema3 = exports_external3.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema3 = exports_external3.object({ - cliVersion: exports_external3.string().min(1).optional(), - mcpHealth: exports_external3.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema3 = contractBaseSchema3(SCHEMA_IDS3.rolloutRecord).extend({ - appId: AppIdSchema3, - package: NpmPackageNameSchema3, - version: SemverSchema3, - machine: NonEmptyStringSchema3, - action: RolloutActionSchema3, - result: ContractStatusSchema3, - verifiedBy: RolloutVerificationSchema3.optional(), - at: TimestampSchema3, - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema3 = exports_external3.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema3 = exports_external3.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema3 = exports_external3.object({ - channel: AnnouncementChannelKindSchema3, - status: AnnouncementDeliveryStatusSchema3, - deliveredAt: TimestampSchema3.optional(), - detail: exports_external3.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema3 = contractBaseSchema3(SCHEMA_IDS3.announcement).extend({ - campaignId: NonEmptyStringSchema3, - appId: AppIdSchema3.optional(), - releaseRef: ResourcePointerSchema3.optional(), - channels: exports_external3.array(AnnouncementChannelSchema3).min(1), - audienceRef: ResourcePointerSchema3, - sentAt: TimestampSchema3 -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema3 = exports_external3.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema3 = exports_external3.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema3 = exports_external3.union([exports_external3.string(), exports_external3.number(), exports_external3.boolean()]); -var AudiencePredicateSchema3 = exports_external3.object({ - kind: AudiencePredicateKindSchema3, - key: exports_external3.string().min(1).optional(), - op: AudiencePredicateOpSchema3.default("eq"), - value: AudiencePredicateValueSchema3.optional(), - values: exports_external3.array(AudiencePredicateValueSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema3 = exports_external3.object({ - match: exports_external3.enum(["all", "any"]).default("all"), - predicates: exports_external3.array(AudiencePredicateSchema3).min(1) -}).strict(); -var ConsentPolicySchema3 = exports_external3.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema3 = contractBaseSchema3(SCHEMA_IDS3.audience).extend({ - audienceId: AppIdSchema3, - name: NonEmptyStringSchema3, - definition: AudienceDefinitionSchema3, - consentPolicy: ConsentPolicySchema3, - suppressionSyncedAt: OptionalTimestampSchema3 -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES3 = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema3 = exports_external3.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - provider: AppCloudProviderSchema3, - kind: exports_external3.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external3.string().min(1), - region: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - machineScoped: exports_external3.boolean().default(false) -}).strict(); -var AppCloudManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.appCloudManifest).extend({ - packageName: exports_external3.string().min(1), - packageVersion: exports_external3.string().min(1).optional(), - appId: exports_external3.string().min(1), - repository: ResourcePointerSchema3.optional(), - storageMode: exports_external3.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external3.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external3.array(AppCloudResourceSchema3).default([]), - localCache: exports_external3.object({ - path: exports_external3.string().min(1).optional(), - pullMode: exports_external3.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external3.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external3.array(exports_external3.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES3]), - dependencies: exports_external3.array(exports_external3.string().min(1)).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES3, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES3) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema3 = exports_external3.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema3 = exports_external3.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: NoCloudCheckKindSchema3, - severity: NoCloudFindingSeveritySchema3, - path: exports_external3.string().min(1).optional(), - packageName: exports_external3.string().min(1).optional(), - pattern: exports_external3.string().min(1), - message: exports_external3.string().min(1), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict(); -var NoCloudCheckResultSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: NoCloudCheckKindSchema3, - status: ContractStatusSchema3, - target: exports_external3.string().min(1), - command: exports_external3.string().min(1).optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - findings: exports_external3.array(NoCloudFindingSchema3).default([]) -}).strict(); -var NoCloudEvidencePackSchema3 = contractBaseSchema3(SCHEMA_IDS3.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema3, - packageName: exports_external3.string().min(1).optional(), - packageVersion: exports_external3.string().min(1).optional(), - generatedBy: ActorPointerSchema3.optional(), - scanMode: exports_external3.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema3, - verdict: exports_external3.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema3.optional(), - checks: exports_external3.array(NoCloudCheckResultSchema3).min(1), - findings: exports_external3.array(NoCloudFindingSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check) => check.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check) => check.status !== "succeeded")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check) => check.status === "failed")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check, index) => { - const checkBlockingFindings = check.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema3 = exports_external3.object({ - checkId: exports_external3.string().min(1), - status: ContractStatusSchema3, - summary: exports_external3.string().min(1).optional(), - startedAt: OptionalTimestampSchema3, - finishedAt: OptionalTimestampSchema3, - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict(); -var ProofBundleSchema3 = contractBaseSchema3(SCHEMA_IDS3.proofBundle).extend({ - subject: ResourcePointerSchema3, - validationPlanRef: ResourcePointerSchema3.optional(), - status: ContractStatusSchema3, - verdict: exports_external3.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external3.array(ProofCheckResultSchema3).default([]), - verifier: ActorPointerSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - residualRisks: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check, index) => { - if (check.status !== "succeeded") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check) => check.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check) => check.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema3 = contractBaseSchema3(SCHEMA_IDS3.workRun).extend({ - objective: exports_external3.string().min(1), - status: ContractStatusSchema3, - actor: ActorPointerSchema3, - traceId: exports_external3.string().min(1).optional(), - startedAt: OptionalTimestampSchema3, - finishedAt: OptionalTimestampSchema3, - constraints: exports_external3.array(exports_external3.string().min(1)).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - decisions: exports_external3.array(DecisionEnvelopeSchema3).default([]), - costEstimates: exports_external3.array(CostEstimateSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - validationPlanRefs: exports_external3.array(ResourcePointerSchema3).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses3.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - at: TimestampSchema3, - kind: exports_external3.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external3.string().min(1), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - costEstimate: CostEstimateSchema3.optional() -}).strict(); -var AgentTrajectorySchema3 = contractBaseSchema3(SCHEMA_IDS3.agentTrajectory).extend({ - actor: ActorPointerSchema3, - workRunRef: ResourcePointerSchema3.optional(), - events: exports_external3.array(TrajectoryEventSchema3).default([]), - outcome: exports_external3.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema3.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION3 = "v1"; -var RepoClassSchema3 = exports_external3.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES3 = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema3 = exports_external3.enum(DEPLOYMENT_MODES3); -var ServiceSurfaceStatusSchema3 = exports_external3.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema3 = exports_external3.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema3 = exports_external3.object({ - method: exports_external3.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external3.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external3.boolean().default(false), - description: exports_external3.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: exports_external3.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external3.boolean().default(true), - command: exports_external3.string().min(1).optional(), - evidenceRef: EvidencePointerSchema3.optional(), - status: exports_external3.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external3.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema3 = exports_external3.object({ - name: exports_external3.string().min(1), - status: ServiceSurfaceStatusSchema3, - bin: exports_external3.string().min(1).optional(), - mcpBin: exports_external3.string().min(1).optional(), - authMode: ServiceAuthModeSchema3, - deploymentModes: exports_external3.array(DeploymentModeSchema3).min(1), - health: ServiceEndpointSchema3.optional(), - readiness: ServiceEndpointSchema3.optional(), - version: ServiceEndpointSchema3.optional(), - apiBasePath: exports_external3.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external3.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external3.string().min(1).optional(), - readinessGates: exports_external3.array(DeploymentReadinessGateSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES3 = ["local", "cloud"]; -var StorageModeSchema3 = exports_external3.enum(STORAGE_MODES3); -var DEPRECATED_STORAGE_MODE_ALIASES2 = ["remote", "hybrid", "self_hosted"]; -var AppNameSchema3 = exports_external3.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES3 = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName3(name) { - return ALLOWED_BIN_SUFFIXES3.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor3(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema3 = exports_external3.object({ - mode: StorageModeSchema3, - envPrefix: exports_external3.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external3.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external3.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external3.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema3 = exports_external3.object({ - $schema: exports_external3.string().min(1).optional(), - schema: exports_external3.literal(SCHEMA_IDS3.serviceContract), - name: AppNameSchema3, - class: RepoClassSchema3, - contractVersion: exports_external3.literal(SERVICE_CONTRACT_VERSION3), - kitVersion: exports_external3.string().min(1), - description: exports_external3.string().min(1).optional(), - bins: exports_external3.array(exports_external3.string().min(1)).default([]), - storage: StorageContractSchema3.optional(), - deploymentModes: exports_external3.array(DeploymentModeSchema3).default(["local"]), - serviceSurfaces: exports_external3.array(ServiceSurfaceSchema3).default([]), - metadata: MetadataSchema3.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName3(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor3(value.name)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor3(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } - } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); - } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } - } - } -}); -var HealthResponseSchema3 = exports_external3.object({ - status: exports_external3.enum(["ok", "degraded", "unavailable"]), - version: exports_external3.string().min(1), - mode: StorageModeSchema3 -}).strict(); -var ReadyResponseSchema3 = exports_external3.object({ - ready: exports_external3.boolean(), - reason: exports_external3.string().min(1).optional() -}).strict(); -var VersionResponseSchema3 = exports_external3.object({ - version: exports_external3.string().min(1) -}).strict(); -var CommsSeveritySchema3 = exports_external3.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema3 = exports_external3.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); -var COMMS_SEVERITY_TAGS3 = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema3 = exports_external3.enum(COMMS_SEVERITY_TAGS3); -var CommsScopeSchema3 = exports_external3.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsEventEnvelope).extend({ - type: CommsEventTypeSchema3, - severity: CommsSeveritySchema3, - scope: CommsScopeSchema3, - summary: exports_external3.string().min(1).optional(), - source: ActorPointerSchema3.optional(), - affected_packages: exports_external3.array(NonEmptyStringSchema3).default([]), - affected_machines: exports_external3.array(NonEmptyStringSchema3).default([]), - action_required: exports_external3.boolean().default(false), - ack_by: TimestampSchema3.optional(), - dedupe_key: NonEmptyStringSchema3, - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); - } - } -}); -var CommsChannelClassSchema3 = exports_external3.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema3 = exports_external3.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema3 = NonEmptyStringSchema3.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); -var CommsChannelMetadataSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsChannelMetadata).extend({ - class: CommsChannelClassSchema3, - noise: CommsChannelNoiseSchema3.optional(), - owner: NonEmptyStringSchema3.optional(), - until: CommsUntilHorizonSchema3.optional(), - successor: NonEmptyStringSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); - } - } -}); -var COMMS_SEVERITY_TAG_INFO3 = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema3, - envelope: CommsEventEnvelopeSchema3 -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO3[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO3)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] - }); - } - } -}); -var ContractSchemaRegistry3 = { - [SCHEMA_IDS3.actorRef]: ActorRefSchema3, - [SCHEMA_IDS3.resourceRef]: ResourceRefSchema3, - [SCHEMA_IDS3.evidenceRef]: EvidenceRefSchema3, - [SCHEMA_IDS3.workRun]: WorkRunSchema3, - [SCHEMA_IDS3.decisionEnvelope]: DecisionEnvelopeSchema3, - [SCHEMA_IDS3.costEstimate]: CostEstimateSchema3, - [SCHEMA_IDS3.capabilityCard]: CapabilityCardSchema3, - [SCHEMA_IDS3.providerLiveModeStandard]: ProviderLiveModeStandardSchema3, - [SCHEMA_IDS3.contextPack]: ContextPackSchema3, - [SCHEMA_IDS3.integrationRef]: IntegrationRefSchema3, - [SCHEMA_IDS3.projectManifest]: ProjectManifestSchema3, - [SCHEMA_IDS3.projectPanel]: ProjectPanelSchema3, - [SCHEMA_IDS3.projectSnapshot]: ProjectSnapshotSchema3, - [SCHEMA_IDS3.renderManifest]: RenderManifestSchema3, - [SCHEMA_IDS3.agentTrajectory]: AgentTrajectorySchema3, - [SCHEMA_IDS3.validationPlan]: ValidationPlanSchema3, - [SCHEMA_IDS3.proofBundle]: ProofBundleSchema3, - [SCHEMA_IDS3.scaffoldManifest]: ScaffoldManifestSchema3, - [SCHEMA_IDS3.scaffoldInstallRecord]: ScaffoldInstallRecordSchema3, - [SCHEMA_IDS3.appCloudManifest]: AppCloudManifestSchema3, - [SCHEMA_IDS3.noCloudEvidencePack]: NoCloudEvidencePackSchema3, - [SCHEMA_IDS3.serviceContract]: ServiceContractManifestSchema3, - [SCHEMA_IDS3.commsEventEnvelope]: CommsEventEnvelopeSchema3, - [SCHEMA_IDS3.commsChannelMetadata]: CommsChannelMetadataSchema3, - [SCHEMA_IDS3.commsMessageMetadata]: CommsMessageMetadataSchema3, - [SCHEMA_IDS3.app]: AppSchema3, - [SCHEMA_IDS3.release]: ReleaseSchema3, - [SCHEMA_IDS3.rolloutRecord]: RolloutRecordSchema3, - [SCHEMA_IDS3.announcement]: AnnouncementSchema3, - [SCHEMA_IDS3.audience]: AudienceSchema3 -}; -function normalizeStorageMode2(value) { - const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES2.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); } -// src/generated/storage-kit/mode.ts -var DEPRECATED_STORAGE_MODE_ALIASES3 = [ - "remote", - "hybrid", - "self_hosted" -]; -function normalizeStorageMode3(value) { - const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES3.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); -} -function envToken3(name) { - return name.toUpperCase().replace(/-/g, "_"); -} -function storageEnvKeys(name) { - const token = envToken3(name); - return { - modeKeys: [`HASNA_${token}_STORAGE_MODE`, `${token}_STORAGE_MODE`], - databaseUrlKeys: [`HASNA_${token}_DATABASE_URL`, `${token}_DATABASE_URL`] - }; -} -function firstEnv(env, keys) { - for (const key of keys) { - const value = env[key]?.trim(); - if (value) - return { key, value }; - } - return null; -} -function resolveStorageMode(name, env = process.env) { - const { modeKeys, databaseUrlKeys } = storageEnvKeys(name); - const dbHit = firstEnv(env, databaseUrlKeys); - const databaseUrlPresent = Boolean(dbHit); - const databaseUrlSource = dbHit ? dbHit.key : null; - const modeHit = firstEnv(env, modeKeys); - if (!modeHit) { - return { - mode: "local", - source: "default", - deprecatedAlias: null, - databaseUrlPresent, - databaseUrlSource, - warning: null - }; - } - const { mode, deprecatedAlias } = normalizeStorageMode3(modeHit.value); - const warnings = []; - if (deprecatedAlias) { - warnings.push(`Deprecated storage mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Set ${modeKeys[0]}=cloud instead.`); - } - if (mode === "cloud" && !databaseUrlPresent) { - warnings.push(`cloud mode needs ${databaseUrlKeys[0]} (PURE REMOTE: reads and writes go to cloud Postgres).`); - } - if (modeHit.key !== modeKeys[0]) { - warnings.push(`Using alias env ${modeHit.key}; the canonical key is ${modeKeys[0]}.`); - } - return { - mode, - source: modeHit.key, - deprecatedAlias, - databaseUrlPresent, - databaseUrlSource, - warning: warnings.length > 0 ? warnings.join(" ") : null - }; -} -function resolveDatabaseUrl(name, env = process.env) { - const { databaseUrlKeys } = storageEnvKeys(name); - const hit = firstEnv(env, databaseUrlKeys); - return hit ? hit.value : null; -} -// src/generated/storage-kit/tls.ts -import { readFileSync as readFileSync2 } from "fs"; -function sslModeFromConnectionString(connectionString) { - const queryStart = connectionString.indexOf("?"); - const params = new URLSearchParams(queryStart === -1 ? "" : connectionString.slice(queryStart + 1)); - const sslmode = params.get("sslmode")?.trim().toLowerCase(); - if (sslmode) { - switch (sslmode) { - case "disable": - case "prefer": - case "require": - case "verify-ca": - case "verify-full": - return sslmode; - case "allow": - return "prefer"; - default: - throw new Error(`Unknown sslmode '${sslmode}' in connection string.`); - } - } - const ssl = params.get("ssl")?.trim().toLowerCase(); - if (ssl && ["1", "true", "yes", "on", "require"].includes(ssl)) - return "require"; - return "disable"; -} -function loadCaBundle(options) { - const env = options.env ?? process.env; - if (options.ca && options.ca.trim()) - return options.ca; - const path = options.caCertPath ?? env.PGSSLROOTCERT ?? env.NODE_EXTRA_CA_CERTS; - if (path && path.trim()) - return readFileSync2(path.trim(), "utf8"); - return null; -} -function resolveTlsConfig(connectionString, options = {}) { - const mode = sslModeFromConnectionString(connectionString); - if (mode === "disable") { - return; - } - const ca = loadCaBundle(options); - if (mode === "prefer" || mode === "require") { - return ca ? { rejectUnauthorized: false, ca } : { rejectUnauthorized: false }; - } - if (!ca) { - throw new Error(`sslmode=${mode} requires a CA bundle. Set PGSSLROOTCERT (or pass caCertPath/ca) to the ` + `Amazon RDS global bundle: https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem`); - } - return { rejectUnauthorized: true, ca }; -} -// src/generated/storage-kit/query.ts -function wrapExecutor(executor) { - return { - async query(sql, params) { - const result = await executor.query(sql, params); - return { rows: result.rows, rowCount: result.rowCount ?? result.rows.length }; - }, - async many(sql, params) { - const result = await executor.query(sql, params); - return result.rows; - }, - async get(sql, params) { - const result = await executor.query(sql, params); - return result.rows[0] ?? null; - }, - async one(sql, params) { - const result = await executor.query(sql, params); - if (result.rows.length !== 1) { - throw new Error(`Expected exactly one row, got ${result.rows.length}.`); - } - return result.rows[0]; - }, - async execute(sql, params) { - await executor.query(sql, params); - } - }; -} -function createQueryClient(pool) { - const base = wrapExecutor(pool); - return { - ...base, - pool, - async transaction(fn) { - const client = await pool.connect(); - try { - await client.query("BEGIN"); - const result = await fn(wrapExecutor(client)); - await client.query("COMMIT"); - return result; - } catch (error) { - try { - await client.query("ROLLBACK"); - } catch {} - throw error; - } finally { - client.release(); - } - }, - async close() { - await pool.end(); - } - }; +// src/db/storage-sync.ts +var STORAGE_TABLES = [ + "sources", + "wiki_pages", + "source_revisions", + "chunks", + "chunk_embeddings", + "wiki_backlinks", + "citations", + "knowledge_indexes", + "runs", + "run_events", + "provider_usage", + "redaction_findings", + "storage_objects", + "audit_events", + "approval_gates", + "vector_index_entries", + "reindex_queue", + "knowledge_machines", + "knowledge_sync_snapshots", + "knowledge_sync_changes", + "knowledge_sync_conflicts", + "knowledge_sync_table_clocks", + "knowledge_sync_imports" +]; +var KNOWLEDGE_STORAGE_TABLES = STORAGE_TABLES; +var KNOWLEDGE_STORAGE_MODE_ENV = "HASNA_KNOWLEDGE_STORAGE_MODE"; +var KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV = "KNOWLEDGE_STORAGE_MODE"; +var STORAGE_MODE_ENV = [KNOWLEDGE_STORAGE_MODE_ENV, KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV]; +function readEnv(name) { + const value = process.env[name]?.trim(); + return value || undefined; } -// src/generated/storage-kit/pool.ts -import pg from "pg"; -function createPgPool(options) { - const ssl = resolveTlsConfig(options.connectionString, { - ...options.ca !== undefined ? { ca: options.ca } : {}, - ...options.caCertPath !== undefined ? { caCertPath: options.caCertPath } : {}, - ...options.env !== undefined ? { env: options.env } : {} - }); - const config = { connectionString: options.connectionString }; - if (ssl !== undefined) - config.ssl = ssl; - if (options.max !== undefined) - config.max = options.max; - if (options.idleTimeoutMillis !== undefined) - config.idleTimeoutMillis = options.idleTimeoutMillis; - if (options.connectionTimeoutMillis !== undefined) - config.connectionTimeoutMillis = options.connectionTimeoutMillis; - if (options.applicationName !== undefined) - config.application_name = options.applicationName; - return new pg.Pool(config); +function normalizeStorageMode4(value) { + const normalized = value?.trim().toLowerCase().replace(/-/g, "_"); + if (normalized === "sqlite") + return "sqlite"; + if (normalized === "postgres" || normalized === "postgresql") + return "postgres"; + return; } -function createCloudPoolFromEnv(appName, options = {}) { - const env = options.env ?? process.env; - const resolution = resolveStorageMode(appName, env); - if (resolution.mode !== "cloud") { - throw new Error(`createCloudPoolFromEnv requires ${appName} storage mode 'cloud', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=cloud.`); - } - const connectionString = resolveDatabaseUrl(appName, env); - if (!connectionString) { - throw new Error(`cloud mode for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); - } - const pool = createPgPool({ - connectionString, - ...options.ca !== undefined ? { ca: options.ca } : {}, - ...options.caCertPath !== undefined ? { caCertPath: options.caCertPath } : {}, - env, - ...options.max !== undefined ? { max: options.max } : {}, - ...options.idleTimeoutMillis !== undefined ? { idleTimeoutMillis: options.idleTimeoutMillis } : {}, - ...options.connectionTimeoutMillis !== undefined ? { connectionTimeoutMillis: options.connectionTimeoutMillis } : {}, - ...options.applicationName !== undefined ? { applicationName: options.applicationName } : {} - }); +function openScopedDb(options = {}) { + const workspace = ensureKnowledgeWorkspace(resolveScopedWorkspace(options.scope, options.cwd).home); + migrateKnowledgeDb(workspace.knowledgeDbPath); return { - client: createQueryClient(pool), - connectionSource: resolution.databaseUrlSource ?? "unknown" + db: openKnowledgeDb(workspace.knowledgeDbPath), + path: workspace.knowledgeDbPath, + scope: options.scope ?? "global" }; } -// src/generated/storage-kit/migrations.ts -import { createHash } from "crypto"; -var DEFAULT_MIGRATION_LEDGER_TABLE = "schema_migrations"; -function checksumSql(sql) { - const normalized = sql.trim().replace(/\r\n/g, ` -`); - return `sha256:${createHash("sha256").update(normalized).digest("hex")}`; -} -function defineMigration(id, sql) { - return Object.freeze({ id, sql: sql.trim(), checksum: checksumSql(sql) }); -} -function hasTransaction(client) { - return typeof client.transaction === "function"; -} - -class MigrationLedger { - client; - migrations; - ledgerTable; - constructor(client, migrations, options = {}) { - this.client = client; - this.migrations = migrations; - this.ledgerTable = options.ledgerTable ?? DEFAULT_MIGRATION_LEDGER_TABLE; - const seen = new Set; - for (const migration of migrations) { - if (seen.has(migration.id)) - throw new Error(`Duplicate migration id: ${migration.id}`); - seen.add(migration.id); - } - } - async ensureLedger() { - await this.client.execute(`CREATE TABLE IF NOT EXISTS ${this.ledgerTable} ( - id TEXT PRIMARY KEY, - checksum TEXT NOT NULL, - applied_at TIMESTAMPTZ NOT NULL DEFAULT now() - )`); - } - async listApplied() { - await this.ensureLedger(); - return this.readApplied(); - } - async readApplied() { - const rows = await this.client.many(`SELECT id, checksum, applied_at FROM ${this.ledgerTable} ORDER BY id ASC`); - return rows.map((row) => ({ - id: row.id, - checksum: row.checksum, - appliedAt: row.applied_at instanceof Date ? row.applied_at.toISOString() : String(row.applied_at) - })); - } - buildPlan(applied) { - const known = new Set(this.migrations.map((m) => m.id)); - for (const row of applied) { - if (!known.has(row.id)) { - throw new Error(`Applied migration '${row.id}' is not recognized by this build (downgrade?).`); - } - } - const appliedById = new Map(applied.map((row) => [row.id, row])); - for (const migration of this.migrations) { - const existing = appliedById.get(migration.id); - if (existing && existing.checksum !== migration.checksum) { - throw new Error(`Migration checksum mismatch for '${migration.id}': the SQL changed after it was applied.`); - } - } - return this.migrations.map((migration) => ({ - migration, - state: appliedById.has(migration.id) ? "already_applied" : "pending" - })); - } - async migrate(opts = {}) { - const dryRun = opts.dryRun === true; - await this.ensureLedger(); - const applied = await this.readApplied(); - const plan = this.buildPlan(applied); - if (dryRun) - return { dryRun, applied, plan }; - for (const item of plan) { - if (item.state === "already_applied") - continue; - await this.applyPendingMigration(item.migration); - } - return { dryRun, applied: await this.readApplied(), plan }; - } - async applyPendingMigration(migration) { - const apply = async (client) => { - await client.execute(migration.sql); - await client.execute(`INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, [migration.id, migration.checksum]); - }; - if (hasTransaction(this.client)) { - await this.client.transaction(apply); - return; - } - await this.client.execute("BEGIN"); - try { - await apply(this.client); - await this.client.execute("COMMIT"); - } catch (error) { - try { - await this.client.execute("ROLLBACK"); - } catch {} - throw error; - } - } -} -function createMigrationLedger(client, migrations, options = {}) { - return new MigrationLedger(client, migrations, options); -} -// src/generated/storage-kit/health.ts -async function checkHealth(client) { - const start = Date.now(); - try { - await client.get("SELECT 1 AS ok"); - return { ok: true, latencyMs: Date.now() - start }; - } catch (error) { - return { - ok: false, - latencyMs: Date.now() - start, - error: error instanceof Error ? error.message : String(error) - }; - } +function getStorageMode() { + const mode2 = normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_ENV)) ?? normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV)); + if (mode2) + return mode2; + return "sqlite"; } -async function checkReady(client, migrations, options = {}) { - const start = Date.now(); +function getSyncMetaAll(options = {}) { + const local = openScopedDb(options); try { - const ledger = new MigrationLedger(client, migrations, options); - const result = await ledger.migrate({ dryRun: true }); - const pending = result.plan.filter((item) => item.state === "pending").map((item) => item.migration.id); - return { ok: pending.length === 0, latencyMs: Date.now() - start, pendingMigrations: pending }; - } catch (error) { - return { - ok: false, - latencyMs: Date.now() - start, - pendingMigrations: [], - error: error instanceof Error ? error.message : String(error) - }; - } -} - -// src/generated/storage-kit/index.ts -var KIT_VERSION = "0.4.0"; - -// src/net-guard.ts -var NETWORK_GUARD_ENV = "NODE_ENV"; - -class KnowledgeNetworkGuardError extends Error { - scheme; - port; - constructor(message, details) { - super(message); - this.name = "KnowledgeNetworkGuardError"; - this.scheme = details.scheme; - this.port = details.port; + ensureSyncMetaTable(local.db); + return local.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all(); + } finally { + local.db.close(); } } -function isNetworkGuardActive(env = process.env) { - return (env[NETWORK_GUARD_ENV] ?? "").trim().toLowerCase() === "test"; -} -function isIpv4Loopback(hostname) { - const parts = hostname.split("."); - if (parts.length !== 4) - return false; - if (!parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)) - return false; - return parts[0] === "127"; -} -function isLoopbackHostname(hostname) { - const host = hostname.trim().toLowerCase(); - if (host.length === 0) - return false; - if (host === "localhost" || host.endsWith(".localhost")) - return true; - if (isIpv4Loopback(host)) - return true; - if (!host.startsWith("[") || !host.endsWith("]")) - return false; - const v6 = host.slice(1, -1); - if (v6 === "::1" || /^(0:){7}1$/.test(v6)) - return true; - const tail = v6.split(":").pop() ?? ""; - if (/^(::ffff:|::)/.test(v6) && isIpv4Loopback(tail)) - return true; - return /^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(v6); -} -function targetUrl(input) { - if (typeof input === "string") - return input; - if (input instanceof URL) - return input.href; - return input.url; -} -function assertOutboundRequestAllowed(input, env = process.env) { - if (!isNetworkGuardActive(env)) - return; - const raw = targetUrl(input); - let url; +function getStorageStatus(options = {}) { + const local = openScopedDb(options); try { - url = new URL(raw); - } catch { - throw new KnowledgeNetworkGuardError(`knowledge: refused an outbound request with an unparseable target while ${NETWORK_GUARD_ENV}=test. ` + "Under test, only loopback requests are permitted.", { scheme: "unknown", port: "" }); - } - if (isLoopbackHostname(url.hostname)) - return; - throw new KnowledgeNetworkGuardError(`knowledge: refused a non-loopback ${url.protocol.replace(":", "")} request while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). This process resolved to the cloud backend under test, which means a " + "read or write was about to leave the machine and reach the live store. Select the mode explicitly " + `(${"HASNA_KNOWLEDGE_STORAGE_MODE"}=local) or point the API URL at 127.0.0.1 for a hermetic test.`, { scheme: url.protocol.replace(":", ""), port: url.port }); -} -var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); -var MAX_GUARDED_REDIRECTS = 5; -function requestMethod(input, init) { - if (init?.method) - return init.method.toUpperCase(); - if (typeof input !== "string" && !(input instanceof URL)) - return input.method.toUpperCase(); - return "GET"; -} -async function guardedFetch(input, init) { - assertOutboundRequestAllowed(input); - if (!isNetworkGuardActive() || init?.redirect !== undefined) { - return fetch(input, init); - } - let from = targetUrl(input); - let method = requestMethod(input, init); - let body = init?.body; - let response = await fetch(input, { ...init ?? {}, redirect: "manual" }); - for (let hop = 0;REDIRECT_STATUSES.has(response.status); hop++) { - const location = response.headers.get("location"); - if (!location) - return response; - const next = new URL(location, from).href; - assertOutboundRequestAllowed(next); - if (hop >= MAX_GUARDED_REDIRECTS) { - const url = new URL(next); - throw new KnowledgeNetworkGuardError(`knowledge: refused to follow more than ${MAX_GUARDED_REDIRECTS} redirects while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). Under test the guard follows redirects itself so every hop is " + "checked, and a chain this long is a loop, not a route.", { scheme: url.protocol.replace(":", ""), port: url.port }); - } - if (response.status === 303 || (response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD") { - method = "GET"; - body = undefined; - } - const hopInit = { ...init ?? {}, method, redirect: "manual" }; - if (body === undefined) - delete hopInit.body; - else - hopInit.body = body; - response = await fetch(next, hopInit); - from = next; - } - return response; -} - -// src/knowledge-mode.ts -var KNOWLEDGE_APP_SLUG = "knowledge"; -var ENV_KEYS = clientTransportEnvKeys2(KNOWLEDGE_APP_SLUG); -var KNOWLEDGE_MODE_ENV_KEYS = ENV_KEYS.modeKeys; -var KNOWLEDGE_API_URL_ENV_KEYS = ENV_KEYS.apiUrlKeys; -var KNOWLEDGE_API_KEY_ENV_KEYS = ENV_KEYS.apiKeyKeys; -function presentEnvNames(env, keys) { - return keys.filter((key) => (env[key] ?? "").trim().length > 0); -} -function resolveKnowledgeModeSelection(env = process.env) { - const pointers = [ - ...presentEnvNames(env, KNOWLEDGE_API_URL_ENV_KEYS), - ...presentEnvNames(env, KNOWLEDGE_API_KEY_ENV_KEYS) - ]; - const canonicalModeKey = KNOWLEDGE_MODE_ENV_KEYS[0]; - for (const name of KNOWLEDGE_MODE_ENV_KEYS) { - const value = env[name]?.trim(); - if (!value) - continue; - let normalized; - try { - normalized = normalizeStorageMode3(value); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - throw new Error(`knowledge: ${name}=${value} is not a valid mode. ${message}`); - } - const warnings = []; - if (normalized.deprecatedAlias) { - warnings.push(`Deprecated mode '${normalized.deprecatedAlias}' from ${name} is treated as 'cloud'. Prefer ${canonicalModeKey}=cloud.`); - } - if (name !== canonicalModeKey) { - warnings.push(`Using alias env ${name}; the canonical key is ${canonicalModeKey}.`); - } - if (normalized.mode === "local" && pointers.length > 0) { - warnings.push(`${name}=local pins the on-box store; ${pointers.join(", ")} are set but ignored.`); - } + ensureSyncMetaTable(local.db); + const sync = local.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all(); return { - mode: normalized.mode, - source: { kind: "env", name, value }, - pointer_env_present: pointers, - pointer_ignored: normalized.mode === "local" && pointers.length > 0, - warning: warnings.length > 0 ? warnings.join(" ") : null + mode: getStorageMode(), + service: "knowledge", + scope: local.scope, + databasePath: local.path, + tables: STORAGE_TABLES, + sync }; + } finally { + local.db.close(); } - return { - mode: "local", - source: { kind: "default", name: null, value: null }, - pointer_env_present: pointers, - pointer_ignored: pointers.length > 0, - warning: pointers.length > 0 ? `${pointers.join(", ")} are set but do NOT select a backend: mode is local by default. ` + `Set ${canonicalModeKey}=cloud to route reads and writes to the API, or unset those vars to silence this note.` : null - }; -} -var SERVER_MODE_CANDIDATES = ["postgres", "cloud", "self_hosted"]; -var LOCAL_MODE_CANDIDATES = ["sqlite", "local"]; -var derivedTokenCache = new Map; -function deriveToken(candidates, normalize, constantName) { - const useCache = normalize === normalizeStorageMode2; - if (useCache) { - const hit = derivedTokenCache.get(candidates); - if (hit !== undefined) - return hit; - } - for (const candidate of candidates) { - try { - normalize(candidate); - if (useCache) - derivedTokenCache.set(candidates, candidate); - return candidate; - } catch {} - } - throw new Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts ` + `(tried ${candidates.join(", ")}). The storage-mode enum has changed; add the new ` + `token to ${constantName} in src/knowledge-mode.ts.`); -} -function serverStorageMode(normalize = normalizeStorageMode2) { - return deriveToken(SERVER_MODE_CANDIDATES, normalize, "SERVER_MODE_CANDIDATES"); -} -function localStorageMode(normalize = normalizeStorageMode2) { - return deriveToken(LOCAL_MODE_CANDIDATES, normalize, "LOCAL_MODE_CANDIDATES"); -} -function contractsStorageModeFor(mode2, normalize = normalizeStorageMode2) { - return mode2 === "cloud" ? serverStorageMode(normalize) : localStorageMode(normalize); -} -function pinnedTransportEnv(env, mode2) { - return { ...env, [KNOWLEDGE_MODE_ENV_KEYS[0]]: contractsStorageModeFor(mode2) }; -} -function knowledgeModeReport(env = process.env) { - const resolution = resolveKnowledgeModeSelection(env); - return { - ...resolution, - store_transport: resolution.mode === "cloud" ? "api" : "local", - api_key_present: presentEnvNames(env, KNOWLEDGE_API_KEY_ENV_KEYS).length > 0, - network_guard_active: isNetworkGuardActive(env) - }; -} - -// src/cloud-store.ts -function transportOverrides(env) { - return { - fetchImpl: guardedFetch, - ...isNetworkGuardActive(env) ? { retry: false } : {} - }; -} -var KNOWLEDGE_RESOURCE = "notes"; - -class KnowledgeVersionConflictError extends Error { - expected; - current; - code = "version_conflict"; - constructor(expected, current) { - super(`version_conflict: this edit was written against version ${expected} but the stored entry is now at version ${current}. ` + "Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions."); - this.expected = expected; - this.current = current; - this.name = "KnowledgeVersionConflictError"; - } -} -function toQuery(options) { - const q = {}; - if (options.search) - q.search = options.search; - if (options.limit !== undefined) - q.limit = options.limit; - if (options.offset !== undefined) - q.offset = options.offset; - if (options.includeArchived || options.archivedOnly) - q.includeArchived = true; - return q; -} -function wrap(client) { - return { - baseUrl: client.baseUrl, - async list(options = {}) { - const wantLimit = options.limit ?? 200; - const query2 = toQuery({ ...options, limit: Math.min(Math.max(wantLimit, 1), 200) }); - const res = await client.list(KNOWLEDGE_RESOURCE, { query: query2 }); - let items = res.items; - if (options.archivedOnly) - items = items.filter((x) => x.archived === true); - if (options.tag) { - const t = options.tag.toLowerCase(); - items = items.filter((x) => (x.tags ?? []).some((tag) => tag.toLowerCase() === t)); - } - return { items, total: res.total }; - }, - async get(idOrShort) { - return client.get(KNOWLEDGE_RESOURCE, idOrShort); - }, - async create(input) { - return client.create(KNOWLEDGE_RESOURCE, { - ...input.id ? { id: input.id } : {}, - title: input.title, - content: input.content, - url: input.url ?? null, - tags: input.tags ?? [], - ...input.metadata ? { metadata: input.metadata } : {} - }); - }, - async update(idOrShort, patch, options = {}) { - try { - return await client.update(KNOWLEDGE_RESOURCE, idOrShort, patch, { - ...options.expectedVersion !== undefined ? { headers: { "if-match": String(options.expectedVersion) } } : {} - }); - } catch (error) { - if (isNotFound(error)) - return null; - const conflict = asVersionConflict(error); - if (conflict) - throw conflict; - throw error; - } - }, - async delete(idOrShort) { - const existing = await client.get(KNOWLEDGE_RESOURCE, idOrShort); - if (!existing) - return false; - await client.delete(KNOWLEDGE_RESOURCE, existing.id); - return true; - }, - async listVersions(idOrShort, options = {}) { - try { - return await client.transport.get(`/${KNOWLEDGE_RESOURCE}/${encodeURIComponent(idOrShort)}/versions`, { query: { limit: options.limit, offset: options.offset } }); - } catch (error) { - if (isNotFound(error)) - return null; - throw error; - } - }, - async getVersion(idOrShort, version) { - try { - return await client.transport.get(`/${KNOWLEDGE_RESOURCE}/${encodeURIComponent(idOrShort)}/versions/${version}`); - } catch (error) { - if (isNotFound(error)) - return null; - throw error; - } - } - }; -} -function asVersionConflict(error) { - if (!error || typeof error !== "object") - return null; - if (error.status !== 409) - return null; - const body = error.body; - const parsed = typeof body === "string" ? safeJson(body) : body; - const shape = parsed ?? {}; - if (shape.error !== "version_conflict") - return null; - return new KnowledgeVersionConflictError(Number(shape.expected ?? 0), Number(shape.current ?? 0)); -} -function safeJson(value) { - try { - return JSON.parse(value); - } catch { - return null; - } -} -function isNotFound(error) { - return Boolean(error && typeof error === "object" && error.status === 404); } -function resolveKnowledgeCloudStore(env = process.env) { - if (resolveKnowledgeModeSelection(env).mode !== "cloud") - return null; - const resolved = resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "cloud"), transportOverrides(env)); - if (resolved.transport !== "cloud-http") - return null; - return wrap(resolved.client); +function resolveTables(tables) { + if (!tables || tables.length === 0) + return [...STORAGE_TABLES]; + const allowed = new Set(STORAGE_TABLES); + const requested = tables.map((table) => table.trim()).filter(Boolean); + const invalid = requested.filter((table) => !allowed.has(table)); + if (invalid.length > 0) + throw new Error(`Unknown knowledge sync table(s): ${invalid.join(", ")}`); + return requested; } -function isKnowledgeApiMode(env = process.env) { - if (resolveKnowledgeModeSelection(env).mode !== "cloud") - return false; - return resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "cloud"), transportOverrides(env)).transport === "cloud-http"; +function parseStorageTables(value) { + if (!value) + return; + return resolveTables(Array.isArray(value) ? value : value.split(",")); } -async function fetchAllCloudItems(store) { - const pageSize = 200; - const all = []; - for (let offset = 0;; offset += pageSize) { - const { items } = await store.list({ includeArchived: true, limit: pageSize, offset }); - all.push(...items); - if (items.length < pageSize) - break; - if (offset > 1e5) - break; - } - return all; +function ensureSyncMetaTable(db) { + db.exec(` + CREATE TABLE IF NOT EXISTS _knowledge_sync_meta ( + table_name TEXT NOT NULL, + last_synced_at TEXT, + direction TEXT NOT NULL CHECK(direction IN ('push', 'pull')), + PRIMARY KEY (table_name, direction) + ) + `); } - -// src/knowledge-db.ts -function assertLocalCatalogMode(operation = "catalog") { - if (isKnowledgeApiMode()) { - const modeKey = KNOWLEDGE_MODE_ENV_KEYS[0]; - throw new Error(`knowledge: ${operation} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, ` + `wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in ` + `cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item ` + `commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${modeKey}=local ` + `(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see ` + `which variable selected the current backend.`); - } +// src/db/remote-storage.ts +var KNOWLEDGE_APP_NAME = "knowledge"; +function createKnowledgeCloudClient() { + return createServerPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; } -var CURRENT_SCHEMA_VERSION = 10; -var CHUNKS_FTS_TOKENIZE = "porter unicode61 remove_diacritics 2"; -var MIGRATION_1 = ` -PRAGMA journal_mode = WAL; -PRAGMA foreign_keys = ON; - -CREATE TABLE IF NOT EXISTS schema_versions ( - version INTEGER PRIMARY KEY, - applied_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS sources ( - id TEXT PRIMARY KEY, - uri TEXT NOT NULL UNIQUE, - kind TEXT NOT NULL, - title TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - acl_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS source_revisions ( - id TEXT PRIMARY KEY, - source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE, - revision TEXT NOT NULL, - hash TEXT, - extracted_text_uri TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - UNIQUE(source_id, revision) -); - -CREATE TABLE IF NOT EXISTS chunks ( - id TEXT PRIMARY KEY, - source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, - wiki_page_id TEXT, - kind TEXT NOT NULL, - ordinal INTEGER NOT NULL, - text TEXT NOT NULL, - token_count INTEGER, - start_offset INTEGER, - end_offset INTEGER, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS chunk_embeddings ( - id TEXT PRIMARY KEY, - chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, - provider TEXT NOT NULL, - model TEXT NOT NULL, - dimensions INTEGER NOT NULL, - vector_json TEXT NOT NULL, - created_at TEXT NOT NULL, - UNIQUE(chunk_id, provider, model) -); - -CREATE TABLE IF NOT EXISTS wiki_pages ( - id TEXT PRIMARY KEY, - path TEXT NOT NULL UNIQUE, - title TEXT NOT NULL, - artifact_uri TEXT, - content_hash TEXT, - status TEXT NOT NULL DEFAULT 'active', - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS wiki_backlinks ( - from_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, - to_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, - label TEXT, - created_at TEXT NOT NULL, - PRIMARY KEY(from_page_id, to_page_id) -); - -CREATE TABLE IF NOT EXISTS citations ( - id TEXT PRIMARY KEY, - wiki_page_id TEXT REFERENCES wiki_pages(id) ON DELETE CASCADE, - chunk_id TEXT REFERENCES chunks(id) ON DELETE SET NULL, - source_uri TEXT NOT NULL, - quote TEXT, - start_offset INTEGER, - end_offset INTEGER, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS knowledge_indexes ( - id TEXT PRIMARY KEY, - kind TEXT NOT NULL, - name TEXT NOT NULL, - artifact_uri TEXT, - shard_key TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - UNIQUE(kind, name, shard_key) -); - -CREATE TABLE IF NOT EXISTS runs ( - id TEXT PRIMARY KEY, - type TEXT NOT NULL, - prompt TEXT, - status TEXT NOT NULL, - provider TEXT, - model TEXT, - cost_tokens INTEGER NOT NULL DEFAULT 0, - cost_usd REAL NOT NULL DEFAULT 0, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS run_events ( - id TEXT PRIMARY KEY, - run_id TEXT NOT NULL REFERENCES runs(id) ON DELETE CASCADE, - level TEXT NOT NULL, - event TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS provider_usage ( - id TEXT PRIMARY KEY, - run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, - provider TEXT NOT NULL, - model TEXT NOT NULL, - input_tokens INTEGER NOT NULL DEFAULT 0, - output_tokens INTEGER NOT NULL DEFAULT 0, - cost_usd REAL NOT NULL DEFAULT 0, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS redaction_findings ( - id TEXT PRIMARY KEY, - source_uri TEXT, - run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, - severity TEXT NOT NULL, - finding_type TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS storage_objects ( - id TEXT PRIMARY KEY, - artifact_uri TEXT NOT NULL UNIQUE, - kind TEXT NOT NULL, - content_type TEXT, - hash TEXT, - size_bytes INTEGER, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( - text, - title, - source_uri, - content='', - tokenize='porter unicode61' -); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (1, datetime('now')); -`; -var MIGRATION_2 = ` -DROP TABLE IF EXISTS chunks_fts; - -CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( - chunk_id UNINDEXED, - text, - title, - source_uri, - tokenize='porter unicode61' -); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (2, datetime('now')); -`; -var MIGRATION_3 = ` -CREATE TABLE IF NOT EXISTS audit_events ( - id TEXT PRIMARY KEY, - event_type TEXT NOT NULL, - action TEXT NOT NULL, - target_uri TEXT, - decision TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS approval_gates ( - id TEXT PRIMARY KEY, - action TEXT NOT NULL, - target_uri TEXT, - status TEXT NOT NULL, - reason TEXT, - approved_by TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_audit_events_action ON audit_events(action); -CREATE INDEX IF NOT EXISTS idx_audit_events_target ON audit_events(target_uri); -CREATE INDEX IF NOT EXISTS idx_audit_events_created ON audit_events(created_at); -CREATE INDEX IF NOT EXISTS idx_approval_gates_action ON approval_gates(action); -CREATE INDEX IF NOT EXISTS idx_approval_gates_status ON approval_gates(status); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (3, datetime('now')); -`; -var MIGRATION_4 = ` -CREATE TABLE IF NOT EXISTS vector_index_entries ( - id TEXT PRIMARY KEY, - chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, - source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, - provider TEXT NOT NULL, - model TEXT NOT NULL, - dimensions INTEGER NOT NULL, - vector_json TEXT NOT NULL, - vector_norm REAL NOT NULL, - source_uri TEXT, - source_ref TEXT, - revision TEXT, - hash TEXT, - start_offset INTEGER, - end_offset INTEGER, - token_count INTEGER, - status TEXT NOT NULL DEFAULT 'active', - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - UNIQUE(chunk_id, provider, model) -); - -CREATE INDEX IF NOT EXISTS idx_vector_index_provider_model ON vector_index_entries(provider, model); -CREATE INDEX IF NOT EXISTS idx_vector_index_source_revision ON vector_index_entries(source_revision_id); -CREATE INDEX IF NOT EXISTS idx_vector_index_source_uri ON vector_index_entries(source_uri); -CREATE INDEX IF NOT EXISTS idx_vector_index_status ON vector_index_entries(status); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (4, datetime('now')); -`; -var MIGRATION_5 = ` -CREATE TABLE IF NOT EXISTS reindex_queue ( - id TEXT PRIMARY KEY, - kind TEXT NOT NULL, - target_id TEXT NOT NULL, - source_uri TEXT, - reason TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - UNIQUE(kind, target_id, reason) -); - -CREATE INDEX IF NOT EXISTS idx_reindex_queue_status ON reindex_queue(status); -CREATE INDEX IF NOT EXISTS idx_reindex_queue_kind_target ON reindex_queue(kind, target_id); -CREATE INDEX IF NOT EXISTS idx_reindex_queue_source_uri ON reindex_queue(source_uri); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (5, datetime('now')); -`; -var MIGRATION_6 = ` -CREATE TABLE IF NOT EXISTS knowledge_machines ( - machine_id TEXT PRIMARY KEY, - hostname TEXT, - platform TEXT, - user_label TEXT, - workspace_home TEXT, - tailscale_dns TEXT, - tailscale_ips_json TEXT NOT NULL DEFAULT '[]', - ssh_target TEXT, - last_seen_at TEXT, - capabilities_json TEXT NOT NULL DEFAULT '{}', - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS knowledge_sync_snapshots ( - id TEXT PRIMARY KEY, - machine_id TEXT NOT NULL, - scope TEXT NOT NULL, - workspace_home TEXT NOT NULL, - sqlite_schema_version INTEGER NOT NULL, - artifact_root_uri TEXT NOT NULL, - content_hash TEXT NOT NULL, - tables_json TEXT NOT NULL, - artifact_hashes_json TEXT NOT NULL, - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS knowledge_sync_changes ( - id TEXT PRIMARY KEY, - origin_machine_id TEXT NOT NULL, - updated_by_machine_id TEXT NOT NULL, - entity_kind TEXT NOT NULL, - entity_id TEXT NOT NULL, - operation TEXT NOT NULL, - base_hash TEXT, - next_hash TEXT, - source_ref TEXT, - source_revision_id TEXT, - artifact_uri TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS knowledge_sync_conflicts ( - id TEXT PRIMARY KEY, - entity_kind TEXT NOT NULL, - entity_id TEXT NOT NULL, - local_machine_id TEXT NOT NULL, - remote_machine_id TEXT NOT NULL, - local_hash TEXT, - remote_hash TEXT, - base_hash TEXT, - status TEXT NOT NULL, - resolution_strategy TEXT, - proposed_patch_uri TEXT, - approved_by TEXT, - resolved_at TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_knowledge_machines_last_seen ON knowledge_machines(last_seen_at); -CREATE INDEX IF NOT EXISTS idx_sync_snapshots_machine_created ON knowledge_sync_snapshots(machine_id, created_at); -CREATE INDEX IF NOT EXISTS idx_sync_snapshots_hash ON knowledge_sync_snapshots(content_hash); -CREATE INDEX IF NOT EXISTS idx_sync_changes_entity ON knowledge_sync_changes(entity_kind, entity_id); -CREATE INDEX IF NOT EXISTS idx_sync_changes_origin ON knowledge_sync_changes(origin_machine_id); -CREATE INDEX IF NOT EXISTS idx_sync_changes_created ON knowledge_sync_changes(created_at); -CREATE INDEX IF NOT EXISTS idx_sync_conflicts_status ON knowledge_sync_conflicts(status); -CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON knowledge_sync_conflicts(entity_kind, entity_id); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (6, datetime('now')); -`; -var MIGRATION_7_TABLES_AND_INDEXES = ` -CREATE TABLE IF NOT EXISTS knowledge_sync_table_clocks ( - table_name TEXT NOT NULL, - machine_id TEXT NOT NULL, - logical_clock INTEGER NOT NULL DEFAULT 0, - high_water_hash TEXT, - high_water_bundle_id TEXT, - origin_machine_id TEXT, - updated_by_machine_id TEXT, - last_applied_at TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - PRIMARY KEY(table_name, machine_id) -); - -CREATE TABLE IF NOT EXISTS knowledge_sync_imports ( - bundle_id TEXT PRIMARY KEY, - source_machine_id TEXT NOT NULL, - target_machine_id TEXT NOT NULL, - direction TEXT NOT NULL, - status TEXT NOT NULL, - content_hash TEXT NOT NULL, - table_clocks_json TEXT NOT NULL, - tables_json TEXT NOT NULL, - generated_at TEXT NOT NULL, - applied_at TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}' -); - -CREATE INDEX IF NOT EXISTS idx_sync_changes_bundle ON knowledge_sync_changes(bundle_id); -CREATE INDEX IF NOT EXISTS idx_sync_changes_clock ON knowledge_sync_changes(entity_kind, logical_clock); -CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_machine ON knowledge_sync_table_clocks(machine_id); -CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_updated ON knowledge_sync_table_clocks(updated_at); -CREATE INDEX IF NOT EXISTS idx_sync_imports_source ON knowledge_sync_imports(source_machine_id, applied_at); -CREATE INDEX IF NOT EXISTS idx_sync_imports_target ON knowledge_sync_imports(target_machine_id, applied_at); -CREATE INDEX IF NOT EXISTS idx_sync_imports_status ON knowledge_sync_imports(status); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (7, datetime('now')); -`; -var MIGRATION_8_TABLES_AND_INDEXES = ` -CREATE INDEX IF NOT EXISTS idx_wiki_pages_lifecycle_status ON wiki_pages(status, valid_to); -CREATE INDEX IF NOT EXISTS idx_wiki_pages_last_verified ON wiki_pages(last_verified_at); -CREATE INDEX IF NOT EXISTS idx_wiki_pages_supersedes ON wiki_pages(supersedes); -CREATE INDEX IF NOT EXISTS idx_wiki_pages_superseded_by ON wiki_pages(superseded_by); - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (8, datetime('now')); -`; -var MIGRATION_9_REBUILD_FTS = ` -BEGIN; - -CREATE TEMP TABLE _chunks_fts_backup AS - SELECT chunk_id, text, title, source_uri FROM chunks_fts; - -DROP TABLE chunks_fts; - -CREATE VIRTUAL TABLE chunks_fts USING fts5( - chunk_id UNINDEXED, - text, - title, - source_uri, - tokenize='${CHUNKS_FTS_TOKENIZE}' -); - -INSERT INTO chunks_fts (chunk_id, text, title, source_uri) - SELECT chunk_id, text, title, source_uri FROM _chunks_fts_backup; - -DROP TABLE _chunks_fts_backup; - -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (9, datetime('now')); +// src/db/pg-migrations.ts +var PG_MIGRATIONS = [ + `CREATE TABLE IF NOT EXISTS sources ( + id TEXT PRIMARY KEY, + uri TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL, + title TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + acl_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS wiki_pages ( + id TEXT PRIMARY KEY, + path TEXT NOT NULL UNIQUE, + title TEXT NOT NULL, + artifact_uri TEXT, + content_hash TEXT, + status TEXT NOT NULL DEFAULT 'active', + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS source_revisions ( + id TEXT PRIMARY KEY, + source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE, + revision TEXT NOT NULL, + hash TEXT, + extracted_text_uri TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + UNIQUE(source_id, revision) + )`, + `CREATE TABLE IF NOT EXISTS chunks ( + id TEXT PRIMARY KEY, + source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, + wiki_page_id TEXT REFERENCES wiki_pages(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + ordinal INTEGER NOT NULL, + text TEXT NOT NULL, + token_count INTEGER, + start_offset INTEGER, + end_offset INTEGER, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS chunk_embeddings ( + id TEXT PRIMARY KEY, + chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + model TEXT NOT NULL, + dimensions INTEGER NOT NULL, + vector_json TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT NOW()::text, + UNIQUE(chunk_id, provider, model) + )`, + `CREATE TABLE IF NOT EXISTS wiki_backlinks ( + from_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, + to_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, + label TEXT, + created_at TEXT NOT NULL DEFAULT NOW()::text, + PRIMARY KEY(from_page_id, to_page_id) + )`, + `CREATE TABLE IF NOT EXISTS citations ( + id TEXT PRIMARY KEY, + wiki_page_id TEXT REFERENCES wiki_pages(id) ON DELETE CASCADE, + chunk_id TEXT REFERENCES chunks(id) ON DELETE SET NULL, + source_uri TEXT NOT NULL, + quote TEXT, + start_offset INTEGER, + end_offset INTEGER, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS knowledge_indexes ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + name TEXT NOT NULL, + artifact_uri TEXT, + shard_key TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text, + UNIQUE(kind, name, shard_key) + )`, + `CREATE TABLE IF NOT EXISTS runs ( + id TEXT PRIMARY KEY, + type TEXT NOT NULL, + prompt TEXT, + status TEXT NOT NULL, + provider TEXT, + model TEXT, + cost_tokens INTEGER NOT NULL DEFAULT 0, + cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS run_events ( + id TEXT PRIMARY KEY, + run_id TEXT NOT NULL REFERENCES runs(id) ON DELETE CASCADE, + level TEXT NOT NULL, + event TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS provider_usage ( + id TEXT PRIMARY KEY, + run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, + provider TEXT NOT NULL, + model TEXT NOT NULL, + input_tokens INTEGER NOT NULL DEFAULT 0, + output_tokens INTEGER NOT NULL DEFAULT 0, + cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS redaction_findings ( + id TEXT PRIMARY KEY, + source_uri TEXT, + run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, + severity TEXT NOT NULL, + finding_type TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS storage_objects ( + id TEXT PRIMARY KEY, + artifact_uri TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL, + content_type TEXT, + hash TEXT, + size_bytes INTEGER, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS audit_events ( + id TEXT PRIMARY KEY, + event_type TEXT NOT NULL, + action TEXT NOT NULL, + target_uri TEXT, + decision TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS approval_gates ( + id TEXT PRIMARY KEY, + action TEXT NOT NULL, + target_uri TEXT, + status TEXT NOT NULL, + reason TEXT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS vector_index_entries ( + id TEXT PRIMARY KEY, + chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, + source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + model TEXT NOT NULL, + dimensions INTEGER NOT NULL, + vector_json TEXT NOT NULL, + vector_norm DOUBLE PRECISION NOT NULL, + source_uri TEXT, + source_ref TEXT, + revision TEXT, + hash TEXT, + start_offset INTEGER, + end_offset INTEGER, + token_count INTEGER, + status TEXT NOT NULL DEFAULT 'active', + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text, + UNIQUE(chunk_id, provider, model) + )`, + `CREATE TABLE IF NOT EXISTS reindex_queue ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + target_id TEXT NOT NULL, + source_uri TEXT, + reason TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + attempts INTEGER NOT NULL DEFAULT 0, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text, + UNIQUE(kind, target_id, reason) + )`, + `CREATE TABLE IF NOT EXISTS knowledge_machines ( + machine_id TEXT PRIMARY KEY, + hostname TEXT, + platform TEXT, + user_label TEXT, + workspace_home TEXT, + tailscale_dns TEXT, + tailscale_ips_json TEXT NOT NULL DEFAULT '[]', + ssh_target TEXT, + last_seen_at TEXT, + capabilities_json TEXT NOT NULL DEFAULT '{}', + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS knowledge_sync_snapshots ( + id TEXT PRIMARY KEY, + machine_id TEXT NOT NULL, + scope TEXT NOT NULL, + workspace_home TEXT NOT NULL, + sqlite_schema_version INTEGER NOT NULL, + artifact_root_uri TEXT NOT NULL, + content_hash TEXT NOT NULL, + tables_json TEXT NOT NULL, + artifact_hashes_json TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS knowledge_sync_changes ( + id TEXT PRIMARY KEY, + origin_machine_id TEXT NOT NULL, + updated_by_machine_id TEXT NOT NULL, + entity_kind TEXT NOT NULL, + entity_id TEXT NOT NULL, + operation TEXT NOT NULL, + base_hash TEXT, + next_hash TEXT, + source_ref TEXT, + source_revision_id TEXT, + artifact_uri TEXT, + logical_clock INTEGER NOT NULL DEFAULT 0, + bundle_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `ALTER TABLE knowledge_sync_changes ADD COLUMN IF NOT EXISTS logical_clock INTEGER NOT NULL DEFAULT 0`, + `ALTER TABLE knowledge_sync_changes ADD COLUMN IF NOT EXISTS bundle_id TEXT`, + `CREATE TABLE IF NOT EXISTS knowledge_sync_conflicts ( + id TEXT PRIMARY KEY, + entity_kind TEXT NOT NULL, + entity_id TEXT NOT NULL, + local_machine_id TEXT NOT NULL, + remote_machine_id TEXT NOT NULL, + local_hash TEXT, + remote_hash TEXT, + base_hash TEXT, + status TEXT NOT NULL, + resolution_strategy TEXT, + proposed_patch_uri TEXT, + approved_by TEXT, + resolved_at TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE TABLE IF NOT EXISTS knowledge_sync_table_clocks ( + table_name TEXT NOT NULL, + machine_id TEXT NOT NULL, + logical_clock INTEGER NOT NULL DEFAULT 0, + high_water_hash TEXT, + high_water_bundle_id TEXT, + origin_machine_id TEXT, + updated_by_machine_id TEXT, + last_applied_at TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text, + PRIMARY KEY(table_name, machine_id) + )`, + `CREATE TABLE IF NOT EXISTS knowledge_sync_imports ( + bundle_id TEXT PRIMARY KEY, + source_machine_id TEXT NOT NULL, + target_machine_id TEXT NOT NULL, + direction TEXT NOT NULL, + status TEXT NOT NULL, + content_hash TEXT NOT NULL, + table_clocks_json TEXT NOT NULL, + tables_json TEXT NOT NULL, + generated_at TEXT NOT NULL, + applied_at TEXT NOT NULL, + metadata_json TEXT NOT NULL DEFAULT '{}' + )`, + `CREATE INDEX IF NOT EXISTS idx_source_revisions_source ON source_revisions(source_id)`, + `CREATE INDEX IF NOT EXISTS idx_chunks_source_revision ON chunks(source_revision_id)`, + `CREATE INDEX IF NOT EXISTS idx_chunks_wiki_page ON chunks(wiki_page_id)`, + `CREATE INDEX IF NOT EXISTS idx_citations_wiki_page ON citations(wiki_page_id)`, + `CREATE INDEX IF NOT EXISTS idx_citations_chunk ON citations(chunk_id)`, + `CREATE INDEX IF NOT EXISTS idx_run_events_run ON run_events(run_id)`, + `CREATE INDEX IF NOT EXISTS idx_provider_usage_run ON provider_usage(run_id)`, + `CREATE INDEX IF NOT EXISTS idx_audit_events_action ON audit_events(action)`, + `CREATE INDEX IF NOT EXISTS idx_audit_events_target ON audit_events(target_uri)`, + `CREATE INDEX IF NOT EXISTS idx_audit_events_created ON audit_events(created_at)`, + `CREATE INDEX IF NOT EXISTS idx_approval_gates_action ON approval_gates(action)`, + `CREATE INDEX IF NOT EXISTS idx_approval_gates_status ON approval_gates(status)`, + `CREATE INDEX IF NOT EXISTS idx_vector_index_provider_model ON vector_index_entries(provider, model)`, + `CREATE INDEX IF NOT EXISTS idx_vector_index_source_revision ON vector_index_entries(source_revision_id)`, + `CREATE INDEX IF NOT EXISTS idx_vector_index_source_uri ON vector_index_entries(source_uri)`, + `CREATE INDEX IF NOT EXISTS idx_vector_index_status ON vector_index_entries(status)`, + `CREATE INDEX IF NOT EXISTS idx_reindex_queue_status ON reindex_queue(status)`, + `CREATE INDEX IF NOT EXISTS idx_reindex_queue_kind_target ON reindex_queue(kind, target_id)`, + `CREATE INDEX IF NOT EXISTS idx_reindex_queue_source_uri ON reindex_queue(source_uri)`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_machines_last_seen ON knowledge_machines(last_seen_at)`, + `CREATE INDEX IF NOT EXISTS idx_sync_snapshots_machine_created ON knowledge_sync_snapshots(machine_id, created_at)`, + `CREATE INDEX IF NOT EXISTS idx_sync_snapshots_hash ON knowledge_sync_snapshots(content_hash)`, + `CREATE INDEX IF NOT EXISTS idx_sync_changes_entity ON knowledge_sync_changes(entity_kind, entity_id)`, + `CREATE INDEX IF NOT EXISTS idx_sync_changes_origin ON knowledge_sync_changes(origin_machine_id)`, + `CREATE INDEX IF NOT EXISTS idx_sync_changes_created ON knowledge_sync_changes(created_at)`, + `CREATE INDEX IF NOT EXISTS idx_sync_changes_bundle ON knowledge_sync_changes(bundle_id)`, + `CREATE INDEX IF NOT EXISTS idx_sync_changes_clock ON knowledge_sync_changes(entity_kind, logical_clock)`, + `CREATE INDEX IF NOT EXISTS idx_sync_conflicts_status ON knowledge_sync_conflicts(status)`, + `CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON knowledge_sync_conflicts(entity_kind, entity_id)`, + `CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_machine ON knowledge_sync_table_clocks(machine_id)`, + `CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_updated ON knowledge_sync_table_clocks(updated_at)`, + `CREATE INDEX IF NOT EXISTS idx_sync_imports_source ON knowledge_sync_imports(source_machine_id, applied_at)`, + `CREATE INDEX IF NOT EXISTS idx_sync_imports_target ON knowledge_sync_imports(target_machine_id, applied_at)`, + `CREATE INDEX IF NOT EXISTS idx_sync_imports_status ON knowledge_sync_imports(status)`, + `CREATE TABLE IF NOT EXISTS knowledge_items ( + id TEXT PRIMARY KEY, + short_id TEXT, + title TEXT NOT NULL, + content TEXT NOT NULL DEFAULT '', + url TEXT, + tags JSONB NOT NULL DEFAULT '[]'::jsonb, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + archived BOOLEAN NOT NULL DEFAULT FALSE, + created_at TEXT NOT NULL DEFAULT NOW()::text, + updated_at TEXT NOT NULL DEFAULT NOW()::text + )`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_items_short_id ON knowledge_items(short_id)`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_items_archived ON knowledge_items(archived)`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_items_created ON knowledge_items(created_at)`, + `ALTER TABLE knowledge_items + ADD COLUMN IF NOT EXISTS search_vector tsvector + GENERATED ALWAYS AS ( + setweight(to_tsvector('english', coalesce(title, '')), 'A') || + setweight(to_tsvector('english', coalesce(content, '')), 'B') + ) STORED`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_items_search_vector + ON knowledge_items USING GIN (search_vector)`, + `ALTER TABLE knowledge_items ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 1`, + `CREATE TABLE IF NOT EXISTS knowledge_item_versions ( + id TEXT PRIMARY KEY, + item_id TEXT NOT NULL REFERENCES knowledge_items(id) ON DELETE CASCADE, + tenant_id TEXT, + version INTEGER NOT NULL, + title TEXT NOT NULL, + content TEXT, + body_uri TEXT, + content_hash TEXT NOT NULL, + content_bytes INTEGER NOT NULL, + url TEXT, + tags JSONB NOT NULL DEFAULT '[]'::jsonb, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + archived BOOLEAN NOT NULL DEFAULT FALSE, + actor TEXT, + reason TEXT, + valid_from TEXT, + valid_to TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + UNIQUE(item_id, version) + )`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_item_versions_item + ON knowledge_item_versions(item_id, version DESC)`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_item_versions_hash + ON knowledge_item_versions(content_hash)`, + `CREATE OR REPLACE FUNCTION knowledge_items_version_snapshot() + RETURNS TRIGGER AS $knowledge_item_version$ + BEGIN + IF (OLD.title, OLD.content, OLD.url, OLD.tags, OLD.metadata, OLD.archived) + IS NOT DISTINCT FROM + (NEW.title, NEW.content, NEW.url, NEW.tags, NEW.metadata, NEW.archived) THEN + -- No content-bearing change: no version, no snapshot. Pin the counter so + -- a caller cannot move it on a write the trigger otherwise ignores. + NEW.version := OLD.version; + RETURN NEW; + END IF; -COMMIT; -`; -var MIGRATION_10_PROMOTION_INBOX = ` -CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( - id TEXT PRIMARY KEY, - record_kind TEXT NOT NULL, - title TEXT NOT NULL, - content TEXT NOT NULL, - canonical_key TEXT NOT NULL, - content_hash TEXT NOT NULL, - source_kind TEXT NOT NULL, - source_refs_json TEXT NOT NULL DEFAULT '[]', - evidence_refs_json TEXT NOT NULL DEFAULT '[]', - status TEXT NOT NULL DEFAULT 'pending', - requires_approval INTEGER NOT NULL DEFAULT 0, - checks_json TEXT NOT NULL DEFAULT '{}', - idempotency_key TEXT NOT NULL UNIQUE, - duplicate_of TEXT, - approved_by TEXT, - promoted_record_id TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - reviewed_at TEXT, - promoted_at TEXT -); + INSERT INTO knowledge_item_versions + (id, item_id, tenant_id, version, title, content, content_hash, content_bytes, + url, tags, metadata, archived, actor, reason, valid_from, valid_to) + VALUES + (gen_random_uuid()::text, + OLD.id, + to_jsonb(OLD)->>'tenant_id', + OLD.version, + OLD.title, + OLD.content, + encode(sha256(convert_to(coalesce(OLD.content, ''), 'UTF8')), 'hex'), + octet_length(coalesce(OLD.content, '')), + OLD.url, + OLD.tags, + OLD.metadata, + OLD.archived, + NULLIF(current_setting('hasna.actor', true), ''), + NULLIF(current_setting('hasna.reason', true), ''), + OLD.updated_at, + to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')); -CREATE TABLE IF NOT EXISTS durable_knowledge_records ( - id TEXT PRIMARY KEY, - record_kind TEXT NOT NULL, - title TEXT NOT NULL, - content TEXT NOT NULL, - canonical_key TEXT NOT NULL, - content_hash TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'active', - source_refs_json TEXT NOT NULL DEFAULT '[]', - evidence_refs_json TEXT NOT NULL DEFAULT '[]', - confidence REAL, - valid_from TEXT NOT NULL, - valid_to TEXT, - promoted_from_candidate_id TEXT NOT NULL UNIQUE - REFERENCES knowledge_promotion_candidates(id) ON DELETE RESTRICT, - approved_by TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); + -- The bump and the snapshot are ONE write. The counter advances by exactly + -- one and only here, so a caller can neither skip it nor forge it. + NEW.version := OLD.version + 1; -CREATE INDEX IF NOT EXISTS idx_promotion_candidates_status - ON knowledge_promotion_candidates(status, updated_at); -CREATE INDEX IF NOT EXISTS idx_promotion_candidates_kind_key - ON knowledge_promotion_candidates(record_kind, canonical_key); -CREATE INDEX IF NOT EXISTS idx_promotion_candidates_hash - ON knowledge_promotion_candidates(record_kind, content_hash); -CREATE INDEX IF NOT EXISTS idx_durable_records_kind_key - ON durable_knowledge_records(record_kind, canonical_key, status); -CREATE INDEX IF NOT EXISTS idx_durable_records_hash - ON durable_knowledge_records(record_kind, content_hash, status); -CREATE INDEX IF NOT EXISTS idx_durable_records_validity - ON durable_knowledge_records(status, valid_to); + -- updated_at is TEXT and the application fills it with toISOString(), so + -- the trigger must write the SAME shape. NOW()::text renders as + -- '2026-07-28 21:29:56.01+00'; space (0x20) sorts below 'T' (0x54), so a + -- column carrying both formats orders every trigger-written row before + -- every application-written one regardless of actual time, and valid_from + -- (copied verbatim from the row below) would stop being comparable with + -- valid_to. One format, no casts needed at read time. + -- + -- Only stamped when the caller did NOT set it. Import, sync replay, and + -- backfill carry a SOURCE timestamp and kept it before this trigger + -- existed; silently replacing it would be a regression. A writer that says + -- nothing still gets a truthful advance. + IF NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at THEN + NEW.updated_at := to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'); + END IF; + RETURN NEW; + END + $knowledge_item_version$ LANGUAGE plpgsql`, + `DO $knowledge_item_version_trigger$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgname = 'trg_knowledge_items_version' + AND tgrelid = 'knowledge_items'::regclass + ) THEN + CREATE TRIGGER trg_knowledge_items_version + BEFORE UPDATE ON knowledge_items + FOR EACH ROW EXECUTE FUNCTION knowledge_items_version_snapshot(); + END IF; + END + $knowledge_item_version_trigger$`, + `ALTER TABLE knowledge_items ENABLE ALWAYS TRIGGER trg_knowledge_items_version`, + `CREATE OR REPLACE FUNCTION knowledge_item_versions_append_only() + RETURNS TRIGGER AS $knowledge_item_versions_append_only$ + BEGIN + RAISE EXCEPTION 'knowledge_item_versions is append-only: version % of item % cannot be rewritten', + OLD.version, OLD.item_id + USING ERRCODE = 'restrict_violation'; + END + $knowledge_item_versions_append_only$ LANGUAGE plpgsql`, + `DO $knowledge_item_versions_guard$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgname = 'trg_knowledge_item_versions_append_only' + AND tgrelid = 'knowledge_item_versions'::regclass + ) THEN + CREATE TRIGGER trg_knowledge_item_versions_append_only + BEFORE UPDATE ON knowledge_item_versions + FOR EACH ROW EXECUTE FUNCTION knowledge_item_versions_append_only(); + END IF; + END + $knowledge_item_versions_guard$`, + `ALTER TABLE knowledge_item_versions ENABLE ALWAYS TRIGGER trg_knowledge_item_versions_append_only` +]; +// src/serve.ts +import { readFileSync as readFileSync5 } from "fs"; -INSERT OR IGNORE INTO schema_versions(version, applied_at) -VALUES (10, datetime('now')); -`; -function openKnowledgeDb(path) { - assertLocalCatalogMode("opening the local knowledge.db catalog"); - ensureParentDir(path); - const db = new Database(path); - db.exec("PRAGMA foreign_keys = ON;"); - db.exec("PRAGMA busy_timeout = 5000;"); - return db; -} -function openKnowledgeDbReadonly(path) { - assertLocalCatalogMode("reading the local knowledge.db catalog"); - return new Database(path, { readonly: true }); -} -function migrateKnowledgeDb(path) { - const db = openKnowledgeDb(path); - try { - db.exec(MIGRATION_1); - if (getSchemaVersion(db) < 2) - db.exec(MIGRATION_2); - if (getSchemaVersion(db) < 3) - db.exec(MIGRATION_3); - if (getSchemaVersion(db) < 4) - db.exec(MIGRATION_4); - if (getSchemaVersion(db) < 5) - db.exec(MIGRATION_5); - if (getSchemaVersion(db) < 6) - db.exec(MIGRATION_6); - if (needsMigration7(db)) - applyMigration7(db); - if (needsMigration8(db)) - applyMigration8(db); - if (needsMigration9(db)) - applyMigration9(db); - if (needsMigration10(db)) - applyMigration10(db); - return { path, schema_version: getSchemaVersion(db) }; - } finally { - db.close(); +// node_modules/@hasna/contracts/dist/auth/index.js +import { createHash as createHash2, createHmac, randomBytes, timingSafeEqual } from "crypto"; +var MAX_TENANT_ID_LENGTH = 64; +var TENANT_ID_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_TENANT_ID_LENGTH - 1}}$`); +var UUID_HEX = "[0-9a-fA-F]"; +var UUID_PATTERN = new RegExp(`^\\{?(?:${UUID_HEX}{8}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{12}|${UUID_HEX}{32})\\}?$`); +function isValidTenantId(value) { + return typeof value === "string" && TENANT_ID_PATTERN.test(value); +} +function isUuidTenantId(value) { + return typeof value === "string" && UUID_PATTERN.test(value); +} +function canonicalizeTenantId(value) { + if (!isUuidTenantId(value)) + return value; + const hex = value.replace(/[{}-]/g, "").toLowerCase(); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +function normalizeTenantId(value) { + const trimmed = typeof value === "string" ? value.trim() : ""; + const canonical = canonicalizeTenantId(trimmed); + if (!isValidTenantId(canonical)) { + throw new Error(`Invalid tenant id '${value}'. Expected 1-${MAX_TENANT_ID_LENGTH} characters matching ${TENANT_ID_PATTERN} (a UUID, ULID, slug, or prefixed id).`); } + return canonical; } -function getSchemaVersion(db) { - const row = db.query("SELECT MAX(version) AS version FROM schema_versions").get(); - return row?.version ?? 0; +function tenantIdsEqual(left, right) { + const canonical = (value) => { + if (typeof value !== "string") + return null; + const folded = canonicalizeTenantId(value.trim()); + return isValidTenantId(folded) ? folded : null; + }; + const a = canonical(left); + const b = canonical(right); + return a !== null && b !== null && a === b; } -function count(db, table) { - const row = db.query(`SELECT COUNT(*) AS n FROM ${table}`).get(); - return row?.n ?? 0; +function ownTenantId(source) { + return Object.hasOwn(source, "tid") ? source.tid : undefined; } -function quoteIdentifier(identifier) { - return `"${identifier.replaceAll('"', '""')}"`; +var API_KEY_TOKEN_VERSION = 1; +var API_KEY_NAMESPACE = "hasna"; +var API_KEY_TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/; +var TOKEN_PATTERN = API_KEY_TOKEN_PATTERN; +var DEFAULT_API_KEY_TTL_SECONDS = 90 * 24 * 60 * 60; +function toBuffer(secret) { + return typeof secret === "string" ? Buffer.from(secret, "utf8") : secret; } -function tableExists(db, table) { - const row = db.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get(table); - return Boolean(row); +function hmac(signingSecret, message) { + return createHmac("sha256", toBuffer(signingSecret)).update(message, "utf8").digest(); } -function columnExists(db, table, column) { - if (!tableExists(db, table)) - return false; - const columns = db.query(`PRAGMA table_info(${quoteIdentifier(table)})`).all(); - return columns.some((row) => row.name === column); +function apiKeyPrefix(app) { + return `${API_KEY_NAMESPACE}_${app}_`; } -function ensureColumn(db, table, column, definition) { - if (!columnExists(db, table, column)) { - db.exec(`ALTER TABLE ${quoteIdentifier(table)} ADD COLUMN ${quoteIdentifier(column)} ${definition};`); +function parseApiKey(token) { + if (typeof token !== "string") + return null; + const match = TOKEN_PATTERN.exec(token); + if (!match) + return null; + const [, app, body, sig] = match; + if (!app || !body || !sig) + return null; + let claims; + try { + claims = JSON.parse(Buffer.from(body, "base64url").toString("utf8")); + } catch { + return null; + } + if (typeof claims !== "object" || claims === null || typeof claims.kid !== "string" || typeof claims.app !== "string" || !Array.isArray(claims.scopes)) { + return null; } + const claimedTid = ownTenantId(claims); + if (claimedTid !== undefined && !isValidTenantId(claimedTid)) { + return null; + } + return { app, body, sig, claims }; } -function needsMigration7(db) { - return getSchemaVersion(db) < 7 || !columnExists(db, "knowledge_sync_changes", "logical_clock") || !columnExists(db, "knowledge_sync_changes", "bundle_id") || !tableExists(db, "knowledge_sync_table_clocks") || !tableExists(db, "knowledge_sync_imports"); +function verifyApiKeyToken(token, options) { + const parsed = parseApiKey(token); + if (!parsed) { + return { ok: false, reason: "malformed", message: "Token is malformed." }; + } + const { app, body, sig, claims } = parsed; + if (claims.v !== API_KEY_TOKEN_VERSION) { + return { ok: false, reason: "unsupported_version", message: `Unsupported token version ${claims.v}.` }; + } + if (claims.app !== app) { + return { ok: false, reason: "app_mismatch", message: "Token prefix app does not match claims." }; + } + if (options.expectedApp !== undefined && app !== options.expectedApp) { + return { ok: false, reason: "app_mismatch", message: `Token is for app '${app}', expected '${options.expectedApp}'.` }; + } + const expected = hmac(options.signingSecret, `${apiKeyPrefix(app)}${body}`); + let provided; + try { + provided = Buffer.from(sig, "base64url"); + } catch { + return { ok: false, reason: "bad_signature", message: "Signature is not valid base64url." }; + } + if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) { + return { ok: false, reason: "bad_signature", message: "Signature verification failed." }; + } + const now = Math.floor((options.nowMs ?? Date.now()) / 1000); + const leeway = options.leewaySeconds ?? 0; + if (typeof claims.iat === "number" && now + leeway < claims.iat) { + return { ok: false, reason: "not_yet_valid", message: "Token is not yet valid." }; + } + if (claims.exp !== null && typeof claims.exp === "number" && now - leeway >= claims.exp) { + return { ok: false, reason: "expired", message: "Token has expired." }; + } + const verifiedTid = ownTenantId(claims); + const tid = verifiedTid === undefined ? null : canonicalizeTenantId(verifiedTid); + const tenantRequired = Boolean(options.requireTenant) || options.expectedTid !== undefined; + if (tenantRequired && tid === null) { + return { + ok: false, + reason: "tenant_required", + message: "Token carries no tenant id ('tid') and this service requires one.", + kid: claims.kid, + tid: null + }; + } + if (options.expectedTid !== undefined && !tenantIdsEqual(tid, options.expectedTid)) { + const expectationIsWellFormed = typeof options.expectedTid === "string" && isValidTenantId(options.expectedTid.trim()); + return { + ok: false, + reason: "tenant_mismatch", + message: expectationIsWellFormed ? "Token is for a different tenant than the one this service accepts." : "Token tenant cannot be checked: the expected tenant id is not a valid tenant id.", + kid: claims.kid, + tid + }; + } + if (options.requiredScopes && options.requiredScopes.length > 0) { + const granted = claims.scopes; + const satisfies = (required) => granted.some((g) => { + if (g === "*") + return true; + const gi = g.indexOf(":"); + const ri = required.indexOf(":"); + if (gi < 0 || ri < 0) + return false; + const gApp = g.slice(0, gi); + const gAction = g.slice(gi + 1); + const rApp = required.slice(0, ri); + const rAction = required.slice(ri + 1); + return (gApp === "*" || gApp === rApp) && (gAction === "*" || gAction === rAction); + }); + for (const required of options.requiredScopes) { + if (!satisfies(required)) { + return { ok: false, reason: "insufficient_scope", message: `Missing required scope '${required}'.` }; + } + } + } + return { ok: true, claims, kid: claims.kid, app, tid }; } -function applyMigration7(db) { - if (!tableExists(db, "knowledge_sync_changes")) - db.exec(MIGRATION_6); - ensureColumn(db, "knowledge_sync_changes", "logical_clock", "INTEGER NOT NULL DEFAULT 0"); - ensureColumn(db, "knowledge_sync_changes", "bundle_id", "TEXT"); - db.exec(MIGRATION_7_TABLES_AND_INDEXES); +var DEFAULT_API_KEYS_TABLE = "api_keys"; +function createTableSql(table) { + return `CREATE TABLE IF NOT EXISTS ${table} ( + kid TEXT PRIMARY KEY, + app TEXT NOT NULL, + agent TEXT, + scopes JSONB NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + issued_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ, + revoked_at TIMESTAMPTZ, + revoked_reason TEXT, + last_used_at TIMESTAMPTZ, + created_by TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + )`; } -function needsMigration8(db) { - return getSchemaVersion(db) < 8 || !columnExists(db, "wiki_pages", "valid_from") || !columnExists(db, "wiki_pages", "valid_to") || !columnExists(db, "wiki_pages", "supersedes") || !columnExists(db, "wiki_pages", "superseded_by") || !columnExists(db, "wiki_pages", "confidence") || !columnExists(db, "wiki_pages", "last_verified_at"); +function apiKeyMigrations(table = DEFAULT_API_KEYS_TABLE) { + return [ + { id: `hasna_auth_0001_${table}`, sql: createTableSql(table) }, + { + id: `hasna_auth_0002_${table}_indexes`, + sql: `CREATE INDEX IF NOT EXISTS ${table}_app_idx ON ${table} (app); + CREATE INDEX IF NOT EXISTS ${table}_token_hash_idx ON ${table} (token_hash);` + }, + { + id: `hasna_auth_0003_${table}_tenant`, + sql: `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS tid TEXT; + CREATE INDEX IF NOT EXISTS ${table}_tid_idx ON ${table} (tid);` + } + ]; } -function applyMigration8(db) { - if (!tableExists(db, "wiki_pages")) - db.exec(MIGRATION_1); - ensureColumn(db, "wiki_pages", "valid_from", "TEXT"); - ensureColumn(db, "wiki_pages", "valid_to", "TEXT"); - ensureColumn(db, "wiki_pages", "supersedes", "TEXT"); - ensureColumn(db, "wiki_pages", "superseded_by", "TEXT"); - ensureColumn(db, "wiki_pages", "confidence", "REAL"); - ensureColumn(db, "wiki_pages", "last_verified_at", "TEXT"); - db.exec(` - UPDATE wiki_pages - SET valid_from = COALESCE(valid_from, created_at), - last_verified_at = COALESCE(last_verified_at, updated_at), - confidence = COALESCE(confidence, 0.8) - WHERE valid_from IS NULL OR last_verified_at IS NULL OR confidence IS NULL; - `); - db.exec(MIGRATION_8_TABLES_AND_INDEXES); +function toIso(value) { + if (value === null || value === undefined) + return null; + if (value instanceof Date) + return value.toISOString(); + return new Date(String(value)).toISOString(); } -function ftsUsesDiacriticFolding(db) { - const row = db.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts"); - return Boolean(row?.sql && row.sql.includes("remove_diacritics")); +function parseScopes(value) { + if (Array.isArray(value)) + return value.map((v) => String(v)); + if (typeof value === "string") { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed.map((v) => String(v)) : []; + } catch { + return []; + } + } + return []; } -function needsMigration9(db) { - if (!tableExists(db, "chunks_fts")) - return false; - return getSchemaVersion(db) < 9 || !ftsUsesDiacriticFolding(db); +function rowToRecord(row) { + const tid = ownTenantId(row); + return { + kid: String(row.kid), + app: String(row.app), + agent: row.agent === null || row.agent === undefined ? null : String(row.agent), + tid: tid === null || tid === undefined ? null : String(tid), + scopes: parseScopes(row.scopes), + tokenHash: String(row.token_hash), + issuedAt: toIso(row.issued_at) ?? new Date(0).toISOString(), + expiresAt: toIso(row.expires_at), + revokedAt: toIso(row.revoked_at), + revokedReason: row.revoked_reason === null || row.revoked_reason === undefined ? null : String(row.revoked_reason), + lastUsedAt: toIso(row.last_used_at), + createdBy: row.created_by === null || row.created_by === undefined ? null : String(row.created_by) + }; } -function applyMigration9(db) { - if (!tableExists(db, "chunks_fts")) - return; - if (ftsUsesDiacriticFolding(db)) { - db.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));"); - return; + +class ApiKeyStore { + client; + table; + constructor(client, options = {}) { + this.client = client; + this.table = options.table ?? DEFAULT_API_KEYS_TABLE; + if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.table)) { + throw new Error(`Invalid api-keys table name '${this.table}'.`); + } + } + migrations() { + return apiKeyMigrations(this.table); + } + async ensureSchema() { + for (const migration of this.migrations()) { + await this.client.execute(migration.sql); + } + } + async insert(input) { + const tid = ownTenantId(input); + await this.client.execute(`INSERT INTO ${this.table} + (kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, created_by) + VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9)`, [ + input.kid, + input.app, + input.agent ?? null, + tid === undefined || tid === null ? null : normalizeTenantId(tid), + JSON.stringify(input.scopes), + input.tokenHash, + input.issuedAt.toISOString(), + input.expiresAt ? input.expiresAt.toISOString() : null, + input.createdBy ?? null + ]); + } + async insertMinted(minted, createdBy) { + const claims = minted.claims; + await this.insert({ + kid: minted.kid, + app: claims.app, + agent: claims.agent ?? null, + tid: ownTenantId(claims) ?? null, + scopes: claims.scopes, + tokenHash: minted.tokenHash, + issuedAt: new Date(claims.iat * 1000), + expiresAt: claims.exp === null ? null : new Date(claims.exp * 1000), + createdBy: createdBy ?? null + }); + } + async findByKid(kid) { + const row = await this.client.get(`SELECT * FROM ${this.table} WHERE kid = $1`, [kid]); + return row ? rowToRecord(row) : null; + } + async findByTokenHash(tokenHash) { + const row = await this.client.get(`SELECT * FROM ${this.table} WHERE token_hash = $1`, [tokenHash]); + return row ? rowToRecord(row) : null; + } + isRevoked = async (kid) => { + const row = await this.client.get(`SELECT revoked_at FROM ${this.table} WHERE kid = $1`, [kid]); + if (!row) + return false; + return row.revoked_at !== null && row.revoked_at !== undefined; + }; + async status(kid, nowMs = Date.now()) { + const record = await this.findByKid(kid); + if (!record) + return "unknown"; + if (record.revokedAt) + return "revoked"; + if (record.expiresAt && new Date(record.expiresAt).getTime() <= nowMs) + return "expired"; + return "active"; + } + statusChecker() { + return async (kid) => { + const status = await this.status(kid); + return status !== "active"; + }; + } + async revoke(kid, reason, atMs = Date.now()) { + const row = await this.client.get(`UPDATE ${this.table} + SET revoked_at = COALESCE(revoked_at, $2), revoked_reason = COALESCE(revoked_reason, $3) + WHERE kid = $1 + RETURNING kid`, [kid, new Date(atMs).toISOString(), reason ?? null]); + return row !== null; + } + async touchLastUsed(kid, atMs = Date.now()) { + await this.client.execute(`UPDATE ${this.table} SET last_used_at = $2 WHERE kid = $1`, [ + kid, + new Date(atMs).toISOString() + ]); + } + async list(options = {}) { + const clauses = []; + const params = []; + if (options.app) { + params.push(options.app); + clauses.push(`app = $${params.length}`); + } + const tid = ownTenantId(options); + if (tid !== undefined) { + params.push(normalizeTenantId(tid)); + clauses.push(`tid = $${params.length}`); + } + if (!options.includeRevoked) { + clauses.push("revoked_at IS NULL"); + } + const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""; + const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`, params); + return rows.map(rowToRecord); + } + async revokedKids() { + const rows = await this.client.many(`SELECT kid FROM ${this.table} WHERE revoked_at IS NOT NULL`); + return rows.map((row) => String(row.kid)); } - db.exec(MIGRATION_9_REBUILD_FTS); } -function needsMigration10(db) { - return getSchemaVersion(db) < 10 || !tableExists(db, "knowledge_promotion_candidates") || !tableExists(db, "durable_knowledge_records"); +function readHeader(source, name) { + const lower = name.toLowerCase(); + if (typeof source === "function") { + return source(name) ?? source(lower) ?? null; + } + if (typeof Headers !== "undefined" && source instanceof Headers) { + return source.get(name); + } + const record = source; + const value = record[name] ?? record[lower] ?? record[name.toUpperCase()]; + if (Array.isArray(value)) + return value[0] ?? null; + return value ?? null; } -function applyMigration10(db) { - db.exec(MIGRATION_10_PROMOTION_INBOX); +function extractToken(source, headerName = "x-api-key", scheme = "Bearer") { + const direct = readHeader(source, headerName); + if (direct && direct.trim().length > 0) + return direct.trim(); + const authz = readHeader(source, "authorization"); + if (authz) { + const prefix = `${scheme} `; + if (authz.toLowerCase().startsWith(prefix.toLowerCase())) { + const token = authz.slice(prefix.length).trim(); + if (token.length > 0) + return token; + } + } + return null; } -function getKnowledgeDbStats(path) { - const db = openKnowledgeDb(path); - try { - return { - schema_version: getSchemaVersion(db), - sources: count(db, "sources"), - source_revisions: count(db, "source_revisions"), - chunks: count(db, "chunks"), - wiki_pages: count(db, "wiki_pages"), - citations: count(db, "citations"), - indexes: count(db, "knowledge_indexes"), - runs: count(db, "runs"), - run_events: count(db, "run_events"), - redaction_findings: count(db, "redaction_findings"), - audit_events: count(db, "audit_events"), - approval_gates: count(db, "approval_gates"), - storage_objects: count(db, "storage_objects"), - embeddings: count(db, "chunk_embeddings"), - vector_entries: count(db, "vector_index_entries"), - reindex_queue: count(db, "reindex_queue"), - knowledge_machines: count(db, "knowledge_machines"), - sync_snapshots: count(db, "knowledge_sync_snapshots"), - sync_changes: count(db, "knowledge_sync_changes"), - sync_conflicts: count(db, "knowledge_sync_conflicts"), - sync_table_clocks: count(db, "knowledge_sync_table_clocks"), - sync_imports: count(db, "knowledge_sync_imports"), - promotion_candidates: count(db, "knowledge_promotion_candidates"), - durable_records: count(db, "durable_knowledge_records") +function verifyApiKey(options) { + if (!options.app) + throw new Error("verifyApiKey requires an 'app' slug."); + if (!options.signingSecret) { + throw new Error("verifyApiKey requires a 'signingSecret'. Set it from HASNA_<APP>_API_SIGNING_KEY."); + } + if (options.expectedTid !== undefined && !isValidTenantId(options.expectedTid)) { + throw new Error(`verifyApiKey received an invalid 'expectedTid': '${options.expectedTid}'.`); + } + const headerName = options.headerName ?? "x-api-key"; + const scheme = options.scheme ?? "Bearer"; + const clock = options.nowMs ?? (() => Date.now()); + async function emit(event) { + if (!options.audit) + return; + try { + await options.audit(event); + } catch {} + } + async function authenticate(headers, context = {}) { + const method = context.method ?? null; + const path = context.path ?? null; + const requiredScopes = [...options.requiredScopes ?? [], ...context.requiredScopes ?? []]; + const at = new Date(clock()).toISOString(); + const perCallTid = Object.hasOwn(context, "expectedTid") ? context.expectedTid : undefined; + const expectedTid = perCallTid !== undefined ? perCallTid : options.expectedTid; + if (perCallTid !== undefined && options.expectedTid !== undefined && !tenantIdsEqual(perCallTid, options.expectedTid)) { + await emit({ outcome: "deny", app: options.app, kid: null, tid: null, reason: "tenant_mismatch", scopesRequired: requiredScopes, method, path, status: 403, at }); + return { + ok: false, + status: 403, + reason: "tenant_mismatch", + message: "This route addresses a tenant other than the one this service is pinned to." + }; + } + const token = extractToken(headers, headerName, scheme); + if (!token) { + const decision = { + ok: false, + status: 401, + reason: "missing_token", + message: `Missing API key. Send it as '${headerName}: <key>' or 'Authorization: ${scheme} <key>'.` + }; + await emit({ outcome: "deny", app: options.app, kid: null, tid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at }); + return decision; + } + const verified = verifyApiKeyToken(token, { + signingSecret: options.signingSecret, + expectedApp: options.app, + nowMs: clock(), + ...options.leewaySeconds !== undefined ? { leewaySeconds: options.leewaySeconds } : {}, + ...options.requireTenant !== undefined ? { requireTenant: options.requireTenant } : {}, + ...expectedTid !== undefined ? { expectedTid } : {}, + requiredScopes + }); + if (!verified.ok) { + const status = verified.reason === "insufficient_scope" || verified.reason === "tenant_mismatch" || verified.reason === "tenant_required" ? 403 : 401; + await emit({ outcome: "deny", app: options.app, kid: verified.kid ?? null, tid: ownTenantId(verified) ?? null, reason: verified.reason, scopesRequired: requiredScopes, method, path, status, at }); + return { ok: false, status, reason: verified.reason, message: verified.message }; + } + if (options.isRevoked) { + const revoked = await options.isRevoked(verified.kid); + if (revoked) { + await emit({ outcome: "deny", app: options.app, kid: verified.kid, tid: verified.tid, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at }); + return { ok: false, status: 401, reason: "revoked", message: "API key has been revoked." }; + } + } + const principal = { + kid: verified.kid, + app: verified.app, + scopes: verified.claims.scopes, + agent: verified.claims.agent ?? null, + tid: verified.tid, + claims: verified.claims }; - } finally { - db.close(); + await emit({ outcome: "allow", app: options.app, kid: verified.kid, tid: verified.tid, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at }); + return { ok: true, status: 200, principal }; } + return { authenticate, app: options.app }; } +var MAX_FLEET_TOKEN_TTL_SECONDS = 24 * 60 * 60; -// src/db/storage-sync.ts -var STORAGE_TABLES = [ - "sources", - "wiki_pages", - "source_revisions", - "chunks", - "chunk_embeddings", - "wiki_backlinks", - "citations", - "knowledge_indexes", - "runs", - "run_events", - "provider_usage", - "redaction_findings", - "storage_objects", - "audit_events", - "approval_gates", - "vector_index_entries", - "reindex_queue", - "knowledge_machines", - "knowledge_sync_snapshots", - "knowledge_sync_changes", - "knowledge_sync_conflicts", - "knowledge_sync_table_clocks", - "knowledge_sync_imports" -]; -var KNOWLEDGE_STORAGE_TABLES = STORAGE_TABLES; -var DEPRECATED_CLOUD_ALIASES = ["remote", "hybrid", "self_hosted"]; -var KNOWLEDGE_STORAGE_MODE_ENV = "HASNA_KNOWLEDGE_STORAGE_MODE"; -var KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV = "KNOWLEDGE_STORAGE_MODE"; -var STORAGE_MODE_ENV = [KNOWLEDGE_STORAGE_MODE_ENV, KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV]; -function readEnv(name) { - const value = process.env[name]?.trim(); - return value || undefined; -} -function normalizeStorageMode4(value) { - const normalized = value?.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return "local"; - if (normalized === "cloud") - return "cloud"; - if (normalized && DEPRECATED_CLOUD_ALIASES.includes(normalized)) - return "cloud"; - return; -} -function openScopedDb(options = {}) { - const workspace = ensureKnowledgeWorkspace(resolveScopedWorkspace(options.scope, options.cwd).home); - migrateKnowledgeDb(workspace.knowledgeDbPath); +// src/registry-contract.ts +var KNOWLEDGE_REGISTRY_CONTRACT_VERSION = 2; +function knowledgeRegistryContract(input) { return { - db: openKnowledgeDb(workspace.knowledgeDbPath), - path: workspace.knowledgeDbPath, - scope: options.scope ?? "global" + contract_version: KNOWLEDGE_REGISTRY_CONTRACT_VERSION, + service: "open-knowledge", + mode: input.mode, + capabilities: [ + "registry", + "notes-read", + "notes-write", + "open-files-source-refs", + "s3-generated-artifacts" + ], + endpoints: { + registry: "/v1/registry", + notes: "/v1/notes", + note: "/v1/notes/{id}", + health: "/health", + version: "/version", + ready: "/ready", + openapi: "/openapi.json" + }, + source_contract: { + owner: "open-files", + preferred_ref: "open-files", + allowed_schemes: input.sourceSchemes, + raw_source_bytes_stored_in_open_knowledge: false + }, + artifact_contract: { + storage_type: input.storageType, + uri_prefix: input.artifactUriPrefix, + generated_only: true + } }; } -function getStorageMode() { - const mode2 = normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_ENV)) ?? normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV)); - if (mode2) - return mode2; - return "local"; + +// src/store.ts +import { + chmodSync as chmodSync2, + closeSync, + existsSync as existsSync2, + fsyncSync, + lstatSync, + openSync, + readFileSync as readFileSync4, + renameSync, + unlinkSync, + writeFileSync as writeFileSync2 +} from "fs"; +import { randomUUID } from "crypto"; +import { basename, dirname as dirname2, join as join3 } from "path"; +function defaultStorePath() { + return workspaceForHome(globalKnowledgeHome()).jsonStorePath; } -function getSyncMetaAll(options = {}) { - const local = openScopedDb(options); - try { - ensureSyncMetaTable(local.db); - return local.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all(); - } finally { - local.db.close(); +function ensureStore(path) { + if (path === defaultStorePath() && existsSync2(legacyGlobalStorePath())) { + importLegacyGlobalStore(); } -} -function getStorageStatus(options = {}) { - const local = openScopedDb(options); - try { - ensureSyncMetaTable(local.db); - const sync = local.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all(); - return { - mode: getStorageMode(), - service: "knowledge", - scope: local.scope, - databasePath: local.path, - tables: STORAGE_TABLES, - sync - }; - } finally { - local.db.close(); + if (!existsSync2(path)) { + ensureParentDir(path); + writeFileAtomic(path, `${JSON.stringify({ items: [] }, null, 2)} +`); } } -function resolveTables(tables) { - if (!tables || tables.length === 0) - return [...STORAGE_TABLES]; - const allowed = new Set(STORAGE_TABLES); - const requested = tables.map((table) => table.trim()).filter(Boolean); - const invalid = requested.filter((table) => !allowed.has(table)); - if (invalid.length > 0) - throw new Error(`Unknown knowledge sync table(s): ${invalid.join(", ")}`); - return requested; +function timestampForPath(now) { + return now.toISOString().replace(/[:.]/g, "-"); } -function parseStorageTables(value) { - if (!value) - return; - return resolveTables(Array.isArray(value) ? value : value.split(",")); +function storeIdentityKeys(item) { + const keys = [`id:${item.id}`]; + if (typeof item.short_id === "string" && item.short_id.length > 0) { + keys.push(`short_id:${item.short_id}`); + } + return keys; } -function ensureSyncMetaTable(db) { - db.exec(` - CREATE TABLE IF NOT EXISTS _knowledge_sync_meta ( - table_name TEXT NOT NULL, - last_synced_at TEXT, - direction TEXT NOT NULL CHECK(direction IN ('push', 'pull')), - PRIMARY KEY (table_name, direction) - ) - `); +function indexStoreItems(items) { + const index = new Set; + for (const item of items) { + for (const key of storeIdentityKeys(item)) + index.add(key); + } + return index; } -// src/db/remote-storage.ts -var KNOWLEDGE_APP_NAME = "knowledge"; -function createKnowledgeCloudClient() { - return createCloudPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; +function storeContainsItem(index, item) { + return storeIdentityKeys(item).some((key) => index.has(key)); +} +function writeJsonFile(path, value) { + ensureParentDir(path); + writeFileSync2(path, `${JSON.stringify(value, null, 2)} +`, { mode: 384 }); + chmodSync2(path, 384); +} +function readStoreFileForImport(path) { + const value = JSON.parse(readFileSync4(path, "utf8")); + if (!value || typeof value !== "object" || !Array.isArray(value.items)) { + return { store: { items: [] }, skippedInvalid: 0 }; + } + const store = { items: [] }; + let skippedInvalid = 0; + for (const item of value.items) { + if (item && typeof item === "object" && typeof item.id === "string" && item.id.length > 0) { + store.items.push(item); + } else { + skippedInvalid += 1; + } + } + return { store, skippedInvalid }; +} +function importLegacyGlobalStore(options = {}) { + if (options.dryRun === true) + return importLegacyGlobalStoreUnlocked(options); + return withLock(defaultStorePath(), () => importLegacyGlobalStoreUnlocked(options), { createParent: true }); +} +function importLegacyGlobalStoreUnlocked(options = {}) { + const dryRun = options.dryRun === true; + const now = options.now ?? new Date; + const workspace = workspaceForHome(globalKnowledgeHome()); + const legacyPath = legacyGlobalStorePath(); + const canonicalPath = workspace.jsonStorePath; + const legacyExists = existsSync2(legacyPath); + const canonicalExisted = existsSync2(canonicalPath); + const result = { + ok: true, + dry_run: dryRun, + legacy_path: legacyPath, + canonical_path: canonicalPath, + legacy_exists: legacyExists, + canonical_existed: canonicalExisted, + canonical_created: false, + would_create_canonical: false, + imported: 0, + skipped_existing: 0, + skipped_invalid: 0, + backup_path: null, + report_path: null, + errors: [], + message: legacyExists ? "Legacy global store already imported" : "No legacy global store found" + }; + if (!legacyExists) + return result; + let legacyStore; + try { + const legacy = readStoreFileForImport(legacyPath); + legacyStore = legacy.store; + result.skipped_invalid = legacy.skippedInvalid; + } catch (error) { + result.ok = false; + result.errors.push(`Could not read legacy store: ${error instanceof Error ? error.message : String(error)}`); + result.message = "Legacy global store import failed"; + return result; + } + let canonicalStore = { items: [] }; + if (canonicalExisted) { + try { + canonicalStore = readStoreFileForImport(canonicalPath).store; + } catch (error) { + result.ok = false; + result.errors.push(`Could not read canonical store: ${error instanceof Error ? error.message : String(error)}`); + result.message = "Legacy global store import failed"; + return result; + } + } + const index = indexStoreItems(canonicalStore.items); + const merged = { items: [...canonicalStore.items] }; + for (const item of legacyStore.items) { + if (!item?.id) { + result.skipped_invalid += 1; + continue; + } + if (storeContainsItem(index, item)) { + result.skipped_existing += 1; + continue; + } + merged.items.push(item); + for (const key of storeIdentityKeys(item)) + index.add(key); + result.imported += 1; + } + result.would_create_canonical = !canonicalExisted && result.imported > 0; + result.canonical_created = !dryRun && result.would_create_canonical; + result.message = result.imported > 0 ? `Imported ${result.imported} legacy item(s) into canonical knowledge store` : "Legacy global store already imported"; + if (dryRun || result.imported === 0) + return result; + const suffix = `${timestampForPath(now)}-${randomUUID().slice(0, 8)}`; + if (canonicalExisted) { + result.backup_path = join3(workspace.exportsDir, `legacy-open-knowledge-db-before-import-${suffix}.json`); + writeJsonFile(result.backup_path, canonicalStore); + } + writeJsonFile(canonicalPath, merged); + result.report_path = join3(workspace.runsDir, `legacy-open-knowledge-import-${suffix}.json`); + writeJsonFile(result.report_path, result); + return result; +} +function loadStoreIfExists(path) { + if (!existsSync2(path)) + return { exists: false, items: [] }; + const raw = readFileSync4(path, "utf8"); + const parsed = JSON.parse(raw); + if (!parsed || !Array.isArray(parsed.items)) { + return { exists: true, items: [] }; + } + return { exists: true, items: parsed.items }; +} +function lockPath(path) { + return `${path}.lock`; +} +var LOCK_MAX_WAIT_MS = 1e4; +var LOCK_RETRY_MS = 25; +var LOCK_STALE_MS = 120000; +var SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4)); +function errCode(error) { + return typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined; +} +function syncParentDir(path) { + let fd = null; + try { + fd = openSync(dirname2(path), "r"); + fsyncSync(fd); + } catch {} finally { + if (fd !== null) { + try { + closeSync(fd); + } catch {} + } + } +} +var heldLockPaths = new Set; +function writeFileAtomic(path, contents) { + ensureParentDir(path); + const tmp = join3(dirname2(path), `.${basename(path)}.tmp.${randomUUID()}`); + let fd = null; + try { + fd = openSync(tmp, "wx", 384); + writeFileSync2(fd, contents); + fsyncSync(fd); + closeSync(fd); + fd = null; + renameSync(tmp, path); + try { + chmodSync2(path, 384); + } catch {} + syncParentDir(path); + } catch (error) { + if (fd !== null) { + try { + closeSync(fd); + } catch {} + } + try { + unlinkSync(tmp); + } catch {} + throw error; + } +} +function sleepSync(ms) { + Atomics.wait(SLEEP_BUFFER, 0, 0, ms); +} +function processIsAlive(pid) { + if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) + return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return errCode(error) !== "ESRCH"; + } +} +function lockIsStale(path, now) { + try { + const raw = readFileSync4(path, "utf8"); + const lock = JSON.parse(raw); + if (typeof lock.ts === "number") { + return now - lock.ts > LOCK_STALE_MS && !processIsAlive(lock.pid); + } + } catch {} + try { + return now - lstatSync(path).mtimeMs > LOCK_STALE_MS; + } catch { + return false; + } +} +function moveStaleLock(path) { + const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); + const stalePath = `${path}.stale.${stamp}.${randomUUID()}`; + try { + renameSync(path, stalePath); + } catch (error) { + if (errCode(error) !== "ENOENT") + throw error; + return; + } +} +function breakStaleLock(lockPath2) { + const owner = randomUUID(); + const breakerPath = `${lockPath2}.breaker`; + const start = Date.now(); + while (Date.now() - start < LOCK_MAX_WAIT_MS) { + if (tryAcquireLock(breakerPath, owner)) { + try { + if (lockIsStale(lockPath2, Date.now())) { + moveStaleLock(lockPath2); + } + } finally { + releaseLock(breakerPath, owner); + } + return; + } + sleepSync(LOCK_RETRY_MS); + } + throw new Error(`Could not acquire stale-lock breaker on ${breakerPath} after ${LOCK_MAX_WAIT_MS}ms`); +} +function tryAcquireLock(path, ownerId) { + let fd = null; + let created = false; + try { + fd = openSync(path, "wx", 384); + created = true; + writeFileSync2(fd, `${JSON.stringify({ owner: ownerId, pid: process.pid, ts: Date.now() })} +`); + fsyncSync(fd); + closeSync(fd); + fd = null; + syncParentDir(path); + return true; + } catch (error) { + if (fd !== null) { + try { + closeSync(fd); + } catch {} + } + if (created) { + try { + unlinkSync(path); + } catch {} + } + if (errCode(error) === "EEXIST") + return false; + throw error; + } +} +function acquireLock(lockPath2, ownerId) { + const start = Date.now(); + while (Date.now() - start < LOCK_MAX_WAIT_MS) { + if (tryAcquireLock(lockPath2, ownerId)) + return; + if (lockIsStale(lockPath2, Date.now())) { + breakStaleLock(lockPath2); + } + sleepSync(LOCK_RETRY_MS); + } + throw new Error(`Could not acquire lock on ${lockPath2} after ${LOCK_MAX_WAIT_MS}ms`); +} +function releaseLock(lockPath2, ownerId) { + try { + if (existsSync2(lockPath2)) { + const lock = JSON.parse(readFileSync4(lockPath2, "utf8")); + if (lock.owner === ownerId) { + unlinkSync(lockPath2); + } + } + } catch {} +} +function loadStore(path) { + ensureStore(path); + const raw = readFileSync4(path, "utf8"); + const parsed = JSON.parse(raw); + if (!parsed || !Array.isArray(parsed.items)) { + return { items: [] }; + } + return parsed; +} +function saveStore(path, store) { + writeFileAtomic(path, `${JSON.stringify(store, null, 2)} +`); +} +function withLock(path, fn, options = {}) { + const owner = randomUUID(); + const lpath = lockPath(path); + if (heldLockPaths.has(lpath)) + return fn(); + if (options.createParent) + ensureParentDir(lpath); + acquireLock(lpath, owner); + heldLockPaths.add(lpath); + try { + return fn(); + } finally { + heldLockPaths.delete(lpath); + releaseLock(lpath, owner); + } +} +function makeId() { + return `k_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`; +} +function makeShortId(id) { + return id.replace(/^k_/, "").slice(0, 12); } -// src/db/pg-migrations.ts -var PG_MIGRATIONS = [ - `CREATE TABLE IF NOT EXISTS sources ( - id TEXT PRIMARY KEY, - uri TEXT NOT NULL UNIQUE, - kind TEXT NOT NULL, - title TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - acl_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS wiki_pages ( - id TEXT PRIMARY KEY, - path TEXT NOT NULL UNIQUE, - title TEXT NOT NULL, - artifact_uri TEXT, - content_hash TEXT, - status TEXT NOT NULL DEFAULT 'active', - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS source_revisions ( - id TEXT PRIMARY KEY, - source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE, - revision TEXT NOT NULL, - hash TEXT, - extracted_text_uri TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - UNIQUE(source_id, revision) - )`, - `CREATE TABLE IF NOT EXISTS chunks ( - id TEXT PRIMARY KEY, - source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, - wiki_page_id TEXT REFERENCES wiki_pages(id) ON DELETE CASCADE, - kind TEXT NOT NULL, - ordinal INTEGER NOT NULL, - text TEXT NOT NULL, - token_count INTEGER, - start_offset INTEGER, - end_offset INTEGER, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS chunk_embeddings ( - id TEXT PRIMARY KEY, - chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, - provider TEXT NOT NULL, - model TEXT NOT NULL, - dimensions INTEGER NOT NULL, - vector_json TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT NOW()::text, - UNIQUE(chunk_id, provider, model) - )`, - `CREATE TABLE IF NOT EXISTS wiki_backlinks ( - from_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, - to_page_id TEXT NOT NULL REFERENCES wiki_pages(id) ON DELETE CASCADE, - label TEXT, - created_at TEXT NOT NULL DEFAULT NOW()::text, - PRIMARY KEY(from_page_id, to_page_id) - )`, - `CREATE TABLE IF NOT EXISTS citations ( - id TEXT PRIMARY KEY, - wiki_page_id TEXT REFERENCES wiki_pages(id) ON DELETE CASCADE, - chunk_id TEXT REFERENCES chunks(id) ON DELETE SET NULL, - source_uri TEXT NOT NULL, - quote TEXT, - start_offset INTEGER, - end_offset INTEGER, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS knowledge_indexes ( - id TEXT PRIMARY KEY, - kind TEXT NOT NULL, - name TEXT NOT NULL, - artifact_uri TEXT, - shard_key TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text, - UNIQUE(kind, name, shard_key) - )`, - `CREATE TABLE IF NOT EXISTS runs ( - id TEXT PRIMARY KEY, - type TEXT NOT NULL, - prompt TEXT, - status TEXT NOT NULL, - provider TEXT, - model TEXT, - cost_tokens INTEGER NOT NULL DEFAULT 0, - cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS run_events ( - id TEXT PRIMARY KEY, - run_id TEXT NOT NULL REFERENCES runs(id) ON DELETE CASCADE, - level TEXT NOT NULL, - event TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS provider_usage ( - id TEXT PRIMARY KEY, - run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, - provider TEXT NOT NULL, - model TEXT NOT NULL, - input_tokens INTEGER NOT NULL DEFAULT 0, - output_tokens INTEGER NOT NULL DEFAULT 0, - cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS redaction_findings ( - id TEXT PRIMARY KEY, - source_uri TEXT, - run_id TEXT REFERENCES runs(id) ON DELETE SET NULL, - severity TEXT NOT NULL, - finding_type TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS storage_objects ( - id TEXT PRIMARY KEY, - artifact_uri TEXT NOT NULL UNIQUE, - kind TEXT NOT NULL, - content_type TEXT, - hash TEXT, - size_bytes INTEGER, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS audit_events ( - id TEXT PRIMARY KEY, - event_type TEXT NOT NULL, - action TEXT NOT NULL, - target_uri TEXT, - decision TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS approval_gates ( - id TEXT PRIMARY KEY, - action TEXT NOT NULL, - target_uri TEXT, - status TEXT NOT NULL, - reason TEXT, - approved_by TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS vector_index_entries ( - id TEXT PRIMARY KEY, - chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, - source_revision_id TEXT REFERENCES source_revisions(id) ON DELETE CASCADE, - provider TEXT NOT NULL, - model TEXT NOT NULL, - dimensions INTEGER NOT NULL, - vector_json TEXT NOT NULL, - vector_norm DOUBLE PRECISION NOT NULL, - source_uri TEXT, - source_ref TEXT, - revision TEXT, - hash TEXT, - start_offset INTEGER, - end_offset INTEGER, - token_count INTEGER, - status TEXT NOT NULL DEFAULT 'active', - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text, - UNIQUE(chunk_id, provider, model) - )`, - `CREATE TABLE IF NOT EXISTS reindex_queue ( - id TEXT PRIMARY KEY, - kind TEXT NOT NULL, - target_id TEXT NOT NULL, - source_uri TEXT, - reason TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text, - UNIQUE(kind, target_id, reason) - )`, - `CREATE TABLE IF NOT EXISTS knowledge_machines ( - machine_id TEXT PRIMARY KEY, - hostname TEXT, - platform TEXT, - user_label TEXT, - workspace_home TEXT, - tailscale_dns TEXT, - tailscale_ips_json TEXT NOT NULL DEFAULT '[]', - ssh_target TEXT, - last_seen_at TEXT, - capabilities_json TEXT NOT NULL DEFAULT '{}', - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS knowledge_sync_snapshots ( - id TEXT PRIMARY KEY, - machine_id TEXT NOT NULL, - scope TEXT NOT NULL, - workspace_home TEXT NOT NULL, - sqlite_schema_version INTEGER NOT NULL, - artifact_root_uri TEXT NOT NULL, - content_hash TEXT NOT NULL, - tables_json TEXT NOT NULL, - artifact_hashes_json TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS knowledge_sync_changes ( - id TEXT PRIMARY KEY, - origin_machine_id TEXT NOT NULL, - updated_by_machine_id TEXT NOT NULL, - entity_kind TEXT NOT NULL, - entity_id TEXT NOT NULL, - operation TEXT NOT NULL, - base_hash TEXT, - next_hash TEXT, - source_ref TEXT, - source_revision_id TEXT, - artifact_uri TEXT, - logical_clock INTEGER NOT NULL DEFAULT 0, - bundle_id TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `ALTER TABLE knowledge_sync_changes ADD COLUMN IF NOT EXISTS logical_clock INTEGER NOT NULL DEFAULT 0`, - `ALTER TABLE knowledge_sync_changes ADD COLUMN IF NOT EXISTS bundle_id TEXT`, - `CREATE TABLE IF NOT EXISTS knowledge_sync_conflicts ( - id TEXT PRIMARY KEY, - entity_kind TEXT NOT NULL, - entity_id TEXT NOT NULL, - local_machine_id TEXT NOT NULL, - remote_machine_id TEXT NOT NULL, - local_hash TEXT, - remote_hash TEXT, - base_hash TEXT, - status TEXT NOT NULL, - resolution_strategy TEXT, - proposed_patch_uri TEXT, - approved_by TEXT, - resolved_at TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE TABLE IF NOT EXISTS knowledge_sync_table_clocks ( - table_name TEXT NOT NULL, - machine_id TEXT NOT NULL, - logical_clock INTEGER NOT NULL DEFAULT 0, - high_water_hash TEXT, - high_water_bundle_id TEXT, - origin_machine_id TEXT, - updated_by_machine_id TEXT, - last_applied_at TEXT, - metadata_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text, - PRIMARY KEY(table_name, machine_id) - )`, - `CREATE TABLE IF NOT EXISTS knowledge_sync_imports ( - bundle_id TEXT PRIMARY KEY, - source_machine_id TEXT NOT NULL, - target_machine_id TEXT NOT NULL, - direction TEXT NOT NULL, - status TEXT NOT NULL, - content_hash TEXT NOT NULL, - table_clocks_json TEXT NOT NULL, - tables_json TEXT NOT NULL, - generated_at TEXT NOT NULL, - applied_at TEXT NOT NULL, - metadata_json TEXT NOT NULL DEFAULT '{}' - )`, - `CREATE INDEX IF NOT EXISTS idx_source_revisions_source ON source_revisions(source_id)`, - `CREATE INDEX IF NOT EXISTS idx_chunks_source_revision ON chunks(source_revision_id)`, - `CREATE INDEX IF NOT EXISTS idx_chunks_wiki_page ON chunks(wiki_page_id)`, - `CREATE INDEX IF NOT EXISTS idx_citations_wiki_page ON citations(wiki_page_id)`, - `CREATE INDEX IF NOT EXISTS idx_citations_chunk ON citations(chunk_id)`, - `CREATE INDEX IF NOT EXISTS idx_run_events_run ON run_events(run_id)`, - `CREATE INDEX IF NOT EXISTS idx_provider_usage_run ON provider_usage(run_id)`, - `CREATE INDEX IF NOT EXISTS idx_audit_events_action ON audit_events(action)`, - `CREATE INDEX IF NOT EXISTS idx_audit_events_target ON audit_events(target_uri)`, - `CREATE INDEX IF NOT EXISTS idx_audit_events_created ON audit_events(created_at)`, - `CREATE INDEX IF NOT EXISTS idx_approval_gates_action ON approval_gates(action)`, - `CREATE INDEX IF NOT EXISTS idx_approval_gates_status ON approval_gates(status)`, - `CREATE INDEX IF NOT EXISTS idx_vector_index_provider_model ON vector_index_entries(provider, model)`, - `CREATE INDEX IF NOT EXISTS idx_vector_index_source_revision ON vector_index_entries(source_revision_id)`, - `CREATE INDEX IF NOT EXISTS idx_vector_index_source_uri ON vector_index_entries(source_uri)`, - `CREATE INDEX IF NOT EXISTS idx_vector_index_status ON vector_index_entries(status)`, - `CREATE INDEX IF NOT EXISTS idx_reindex_queue_status ON reindex_queue(status)`, - `CREATE INDEX IF NOT EXISTS idx_reindex_queue_kind_target ON reindex_queue(kind, target_id)`, - `CREATE INDEX IF NOT EXISTS idx_reindex_queue_source_uri ON reindex_queue(source_uri)`, - `CREATE INDEX IF NOT EXISTS idx_knowledge_machines_last_seen ON knowledge_machines(last_seen_at)`, - `CREATE INDEX IF NOT EXISTS idx_sync_snapshots_machine_created ON knowledge_sync_snapshots(machine_id, created_at)`, - `CREATE INDEX IF NOT EXISTS idx_sync_snapshots_hash ON knowledge_sync_snapshots(content_hash)`, - `CREATE INDEX IF NOT EXISTS idx_sync_changes_entity ON knowledge_sync_changes(entity_kind, entity_id)`, - `CREATE INDEX IF NOT EXISTS idx_sync_changes_origin ON knowledge_sync_changes(origin_machine_id)`, - `CREATE INDEX IF NOT EXISTS idx_sync_changes_created ON knowledge_sync_changes(created_at)`, - `CREATE INDEX IF NOT EXISTS idx_sync_changes_bundle ON knowledge_sync_changes(bundle_id)`, - `CREATE INDEX IF NOT EXISTS idx_sync_changes_clock ON knowledge_sync_changes(entity_kind, logical_clock)`, - `CREATE INDEX IF NOT EXISTS idx_sync_conflicts_status ON knowledge_sync_conflicts(status)`, - `CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON knowledge_sync_conflicts(entity_kind, entity_id)`, - `CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_machine ON knowledge_sync_table_clocks(machine_id)`, - `CREATE INDEX IF NOT EXISTS idx_sync_table_clocks_updated ON knowledge_sync_table_clocks(updated_at)`, - `CREATE INDEX IF NOT EXISTS idx_sync_imports_source ON knowledge_sync_imports(source_machine_id, applied_at)`, - `CREATE INDEX IF NOT EXISTS idx_sync_imports_target ON knowledge_sync_imports(target_machine_id, applied_at)`, - `CREATE INDEX IF NOT EXISTS idx_sync_imports_status ON knowledge_sync_imports(status)`, - `CREATE TABLE IF NOT EXISTS knowledge_items ( - id TEXT PRIMARY KEY, - short_id TEXT, - title TEXT NOT NULL, - content TEXT NOT NULL DEFAULT '', - url TEXT, - tags JSONB NOT NULL DEFAULT '[]'::jsonb, - metadata JSONB NOT NULL DEFAULT '{}'::jsonb, - archived BOOLEAN NOT NULL DEFAULT FALSE, - created_at TEXT NOT NULL DEFAULT NOW()::text, - updated_at TEXT NOT NULL DEFAULT NOW()::text - )`, - `CREATE INDEX IF NOT EXISTS idx_knowledge_items_short_id ON knowledge_items(short_id)`, - `CREATE INDEX IF NOT EXISTS idx_knowledge_items_archived ON knowledge_items(archived)`, - `CREATE INDEX IF NOT EXISTS idx_knowledge_items_created ON knowledge_items(created_at)`, - `ALTER TABLE knowledge_items - ADD COLUMN IF NOT EXISTS search_vector tsvector - GENERATED ALWAYS AS ( - setweight(to_tsvector('english', coalesce(title, '')), 'A') || - setweight(to_tsvector('english', coalesce(content, '')), 'B') - ) STORED`, - `CREATE INDEX IF NOT EXISTS idx_knowledge_items_search_vector - ON knowledge_items USING GIN (search_vector)`, - `ALTER TABLE knowledge_items ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 1`, - `CREATE TABLE IF NOT EXISTS knowledge_item_versions ( - id TEXT PRIMARY KEY, - item_id TEXT NOT NULL REFERENCES knowledge_items(id) ON DELETE CASCADE, - tenant_id TEXT, - version INTEGER NOT NULL, - title TEXT NOT NULL, - content TEXT, - body_uri TEXT, - content_hash TEXT NOT NULL, - content_bytes INTEGER NOT NULL, - url TEXT, - tags JSONB NOT NULL DEFAULT '[]'::jsonb, - metadata JSONB NOT NULL DEFAULT '{}'::jsonb, - archived BOOLEAN NOT NULL DEFAULT FALSE, - actor TEXT, - reason TEXT, - valid_from TEXT, - valid_to TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), - UNIQUE(item_id, version) - )`, - `CREATE INDEX IF NOT EXISTS idx_knowledge_item_versions_item - ON knowledge_item_versions(item_id, version DESC)`, - `CREATE INDEX IF NOT EXISTS idx_knowledge_item_versions_hash - ON knowledge_item_versions(content_hash)`, - `CREATE OR REPLACE FUNCTION knowledge_items_version_snapshot() - RETURNS TRIGGER AS $knowledge_item_version$ - BEGIN - IF (OLD.title, OLD.content, OLD.url, OLD.tags, OLD.metadata, OLD.archived) - IS NOT DISTINCT FROM - (NEW.title, NEW.content, NEW.url, NEW.tags, NEW.metadata, NEW.archived) THEN - -- No content-bearing change: no version, no snapshot. Pin the counter so - -- a caller cannot move it on a write the trigger otherwise ignores. - NEW.version := OLD.version; - RETURN NEW; - END IF; - - INSERT INTO knowledge_item_versions - (id, item_id, tenant_id, version, title, content, content_hash, content_bytes, - url, tags, metadata, archived, actor, reason, valid_from, valid_to) - VALUES - (gen_random_uuid()::text, - OLD.id, - to_jsonb(OLD)->>'tenant_id', - OLD.version, - OLD.title, - OLD.content, - encode(sha256(convert_to(coalesce(OLD.content, ''), 'UTF8')), 'hex'), - octet_length(coalesce(OLD.content, '')), - OLD.url, - OLD.tags, - OLD.metadata, - OLD.archived, - NULLIF(current_setting('hasna.actor', true), ''), - NULLIF(current_setting('hasna.reason', true), ''), - OLD.updated_at, - to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')); - - -- The bump and the snapshot are ONE write. The counter advances by exactly - -- one and only here, so a caller can neither skip it nor forge it. - NEW.version := OLD.version + 1; - -- updated_at is TEXT and the application fills it with toISOString(), so - -- the trigger must write the SAME shape. NOW()::text renders as - -- '2026-07-28 21:29:56.01+00'; space (0x20) sorts below 'T' (0x54), so a - -- column carrying both formats orders every trigger-written row before - -- every application-written one regardless of actual time, and valid_from - -- (copied verbatim from the row below) would stop being comparable with - -- valid_to. One format, no casts needed at read time. - -- - -- Only stamped when the caller did NOT set it. Import, sync replay, and - -- backfill carry a SOURCE timestamp and kept it before this trigger - -- existed; silently replacing it would be a regression. A writer that says - -- nothing still gets a truthful advance. - IF NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at THEN - NEW.updated_at := to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'); - END IF; - RETURN NEW; - END - $knowledge_item_version$ LANGUAGE plpgsql`, - `DO $knowledge_item_version_trigger$ - BEGIN - IF NOT EXISTS ( - SELECT 1 FROM pg_trigger - WHERE tgname = 'trg_knowledge_items_version' - AND tgrelid = 'knowledge_items'::regclass - ) THEN - CREATE TRIGGER trg_knowledge_items_version - BEFORE UPDATE ON knowledge_items - FOR EACH ROW EXECUTE FUNCTION knowledge_items_version_snapshot(); - END IF; - END - $knowledge_item_version_trigger$`, - `ALTER TABLE knowledge_items ENABLE ALWAYS TRIGGER trg_knowledge_items_version`, - `CREATE OR REPLACE FUNCTION knowledge_item_versions_append_only() - RETURNS TRIGGER AS $knowledge_item_versions_append_only$ - BEGIN - RAISE EXCEPTION 'knowledge_item_versions is append-only: version % of item % cannot be rewritten', - OLD.version, OLD.item_id - USING ERRCODE = 'restrict_violation'; - END - $knowledge_item_versions_append_only$ LANGUAGE plpgsql`, - `DO $knowledge_item_versions_guard$ - BEGIN - IF NOT EXISTS ( - SELECT 1 FROM pg_trigger - WHERE tgname = 'trg_knowledge_item_versions_append_only' - AND tgrelid = 'knowledge_item_versions'::regclass - ) THEN - CREATE TRIGGER trg_knowledge_item_versions_append_only - BEFORE UPDATE ON knowledge_item_versions - FOR EACH ROW EXECUTE FUNCTION knowledge_item_versions_append_only(); - END IF; - END - $knowledge_item_versions_guard$`, - `ALTER TABLE knowledge_item_versions ENABLE ALWAYS TRIGGER trg_knowledge_item_versions_append_only` -]; // src/serve.ts -import { readFileSync as readFileSync4 } from "fs"; +var KNOWLEDGE_SERVE_APP = "knowledge"; +function normalizeCloudDatabaseUrl(env = process.env) { + const key = "HASNA_KNOWLEDGE_DATABASE_URL"; + const url = env[key] ?? env.KNOWLEDGE_DATABASE_URL; + if (!url) + return url; + const lower = url.toLowerCase(); + const needsCompat = (lower.includes("sslmode=require") || lower.includes("sslmode=prefer")) && !lower.includes("uselibpqcompat"); + if (!needsCompat) + return url; + const updated = url.includes("?") ? `${url}&uselibpqcompat=true` : `${url}?uselibpqcompat=true`; + env[key] = updated; + return updated; +} +function resolveVersion() { + if (process.env.HASNA_KNOWLEDGE_VERSION) + return process.env.HASNA_KNOWLEDGE_VERSION; + try { + const url = new URL("../package.json", import.meta.url); + const pkg = JSON.parse(readFileSync5(url, "utf8")); + return pkg.version ?? "0.0.0"; + } catch { + return process.env.npm_package_version ?? "0.0.0"; + } +} +function resolveSigningSecret(env = process.env) { + const secret = env.HASNA_KNOWLEDGE_API_SIGNING_KEY ?? env.API_KEY_SIGNING_SECRET ?? env.HASNA_API_SIGNING_KEY; + if (!secret) { + throw new Error("knowledge-serve requires an API signing secret: set HASNA_KNOWLEDGE_API_SIGNING_KEY " + "(or API_KEY_SIGNING_SECRET / HASNA_API_SIGNING_KEY)."); + } + return secret; +} -// node_modules/@hasna/contracts/dist/auth/index.js -import { createHash as createHash2, createHmac, randomBytes, timingSafeEqual } from "crypto"; -var API_KEY_TOKEN_VERSION = 1; -var API_KEY_NAMESPACE = "hasna"; -var TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/; -var DEFAULT_API_KEY_TTL_SECONDS = 90 * 24 * 60 * 60; -function toBuffer(secret) { - return typeof secret === "string" ? Buffer.from(secret, "utf8") : secret; +class VersionConflictError extends Error { + expected; + current; + code = "version_conflict"; + constructor(expected, current) { + super(`version_conflict: expected version ${expected}, stored version is ${current}`); + this.expected = expected; + this.current = current; + this.name = "VersionConflictError"; + } } -function hmac(signingSecret, message) { - return createHmac("sha256", toBuffer(signingSecret)).update(message, "utf8").digest(); +function parseJsonColumn(value, fallback) { + if (value == null) + return fallback; + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return fallback; + } + } + return value; } -function apiKeyPrefix(app) { - return `${API_KEY_NAMESPACE}_${app}_`; +function rowToVersion(row) { + return { + id: String(row.id), + item_id: String(row.item_id), + tenant_id: row.tenant_id ?? null, + version: Number(row.version), + title: String(row.title ?? ""), + content: row.content ?? null, + body_uri: row.body_uri ?? null, + content_hash: String(row.content_hash ?? ""), + content_bytes: Number(row.content_bytes ?? 0), + url: row.url ?? null, + tags: parseJsonColumn(row.tags, []), + metadata: parseJsonColumn(row.metadata, {}), + archived: Boolean(row.archived), + actor: row.actor ?? null, + reason: row.reason ?? null, + valid_from: row.valid_from ?? null, + valid_to: String(row.valid_to ?? "") + }; } -function parseApiKey(token) { - if (typeof token !== "string") - return null; - const match = TOKEN_PATTERN.exec(token); - if (!match) - return null; - const [, app, body, sig] = match; - if (!app || !body || !sig) - return null; - let claims; - try { - claims = JSON.parse(Buffer.from(body, "base64url").toString("utf8")); - } catch { - return null; +function rowToItem(row) { + const parseJson = (value, fallback) => { + if (value == null) + return fallback; + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return fallback; + } + } + return value; + }; + return { + id: String(row.id), + short_id: row.short_id ?? null, + title: String(row.title ?? ""), + content: String(row.content ?? ""), + url: row.url ?? null, + tags: parseJson(row.tags, []), + metadata: parseJson(row.metadata, {}), + archived: Boolean(row.archived), + created_at: String(row.created_at), + updated_at: String(row.updated_at), + version: row.version == null ? 1 : Number(row.version) + }; +} + +class NoteRepo { + client; + constructor(client) { + this.client = client; + } + async write(options, fn) { + return this.client.transaction(async (tx) => { + await tx.execute(`SELECT set_config('hasna.actor', $1, true), set_config('hasna.reason', $2, true)`, [ + options.actor ?? "", + options.reason ?? "" + ]); + return fn(tx); + }); + } + async create(input, options = {}) { + if (!input.title || typeof input.title !== "string") { + throw new HttpError(400, "title is required"); + } + const now = new Date().toISOString(); + const suppliedId = typeof input.id === "string" ? input.id.trim() : ""; + if (suppliedId) { + const row2 = await this.write(options, (tx) => tx.get(`INSERT INTO knowledge_items (id, short_id, title, content, url, tags, metadata, archived, created_at, updated_at) + VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7::jsonb,FALSE,$8,$8) + ON CONFLICT (id) DO UPDATE SET + title = EXCLUDED.title, + content = EXCLUDED.content, + url = EXCLUDED.url, + tags = EXCLUDED.tags, + metadata = EXCLUDED.metadata, + updated_at = EXCLUDED.updated_at + RETURNING *`, [ + suppliedId, + makeShortId(suppliedId), + input.title, + input.content ?? "", + input.url ?? null, + JSON.stringify(input.tags ?? []), + JSON.stringify(input.metadata ?? {}), + now + ])); + return rowToItem(row2); + } + const id = makeId(); + const row = await this.write(options, (tx) => tx.get(`INSERT INTO knowledge_items (id, short_id, title, content, url, tags, metadata, archived, created_at, updated_at) + VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7::jsonb,FALSE,$8,$9) + RETURNING *`, [ + id, + makeShortId(id), + input.title, + input.content ?? "", + input.url ?? null, + JSON.stringify(input.tags ?? []), + JSON.stringify(input.metadata ?? {}), + now, + now + ])); + return rowToItem(row); } - if (typeof claims !== "object" || claims === null || typeof claims.kid !== "string" || typeof claims.app !== "string" || !Array.isArray(claims.scopes)) { - return null; + async list(options = {}) { + const limit = Math.min(Math.max(options.limit ?? 50, 1), 200); + const offset = Math.max(options.offset ?? 0, 0); + const where = []; + const params = []; + if (!options.includeArchived) + where.push("archived = FALSE"); + const search = options.search?.trim(); + let tsQueryExpr = null; + if (search) { + params.push(search); + tsQueryExpr = `websearch_to_tsquery('english', $${params.length})`; + where.push(`search_vector @@ ${tsQueryExpr}`); + } + const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : ""; + const orderSql = tsQueryExpr ? `ORDER BY ts_rank_cd(search_vector, ${tsQueryExpr}) DESC, created_at DESC` : "ORDER BY created_at DESC"; + const totalRow = await this.client.get(`SELECT count(*)::text AS count FROM knowledge_items ${whereSql}`, params); + const rows = await this.client.many(`SELECT * FROM knowledge_items ${whereSql} ${orderSql} LIMIT ${limit} OFFSET ${offset}`, params); + return { items: rows.map(rowToItem), total: Number(totalRow?.count ?? 0) }; } - return { app, body, sig, claims }; -} -function verifyApiKeyToken(token, options) { - const parsed = parseApiKey(token); - if (!parsed) { - return { ok: false, reason: "malformed", message: "Token is malformed." }; + async get(idOrShort) { + const row = await this.client.get(`SELECT * FROM knowledge_items WHERE id = $1 OR short_id = $1 LIMIT 1`, [idOrShort]); + return row ? rowToItem(row) : null; } - const { app, body, sig, claims } = parsed; - if (claims.v !== API_KEY_TOKEN_VERSION) { - return { ok: false, reason: "unsupported_version", message: `Unsupported token version ${claims.v}.` }; + async update(idOrShort, patch, options = {}) { + const existing = await this.get(idOrShort); + if (!existing) + return null; + const sets = []; + const params = []; + const push = (col, val, cast = "") => { + params.push(val); + sets.push(`${col} = $${params.length}${cast}`); + }; + if (patch.title !== undefined) + push("title", patch.title); + if (patch.content !== undefined) + push("content", patch.content); + if (patch.url !== undefined) + push("url", patch.url); + if (patch.tags !== undefined) + push("tags", JSON.stringify(patch.tags), "::jsonb"); + if (patch.metadata !== undefined) + push("metadata", JSON.stringify(patch.metadata), "::jsonb"); + if (patch.archived !== undefined) + push("archived", patch.archived); + push("updated_at", new Date().toISOString()); + params.push(existing.id); + let where = `id = $${params.length}`; + const { expectedVersion } = options; + if (expectedVersion !== undefined) { + params.push(expectedVersion); + where += ` AND version = $${params.length}`; + } + const row = await this.write(options, (tx) => tx.get(`UPDATE knowledge_items SET ${sets.join(", ")} WHERE ${where} RETURNING *`, params)); + if (row) + return rowToItem(row); + if (expectedVersion === undefined) + return null; + const current = await this.get(existing.id); + if (!current) + return null; + throw new VersionConflictError(expectedVersion, current.version ?? 1); } - if (claims.app !== app) { - return { ok: false, reason: "app_mismatch", message: "Token prefix app does not match claims." }; + async listVersions(idOrShort, options = {}) { + const existing = await this.get(idOrShort); + if (!existing) + return null; + const limit = Math.min(Math.max(options.limit ?? 50, 1), 200); + const offset = Math.max(options.offset ?? 0, 0); + const totalRow = await this.client.get(`SELECT count(*)::text AS count FROM knowledge_item_versions WHERE item_id = $1`, [existing.id]); + const rows = await this.client.many(`SELECT * FROM knowledge_item_versions WHERE item_id = $1 + ORDER BY version DESC LIMIT ${limit} OFFSET ${offset}`, [existing.id]); + return { + item_id: existing.id, + current_version: existing.version ?? 1, + total: Number(totalRow?.count ?? 0), + items: rows.map(rowToVersion) + }; } - if (options.expectedApp !== undefined && app !== options.expectedApp) { - return { ok: false, reason: "app_mismatch", message: `Token is for app '${app}', expected '${options.expectedApp}'.` }; + async getVersion(idOrShort, version) { + const existing = await this.get(idOrShort); + if (!existing) + return null; + const row = await this.client.get(`SELECT * FROM knowledge_item_versions WHERE item_id = $1 AND version = $2`, [existing.id, version]); + return row ? rowToVersion(row) : null; } - const expected = hmac(options.signingSecret, `${apiKeyPrefix(app)}${body}`); - let provided; - try { - provided = Buffer.from(sig, "base64url"); - } catch { - return { ok: false, reason: "bad_signature", message: "Signature is not valid base64url." }; + async delete(idOrShort) { + const existing = await this.get(idOrShort); + if (!existing) + return false; + await this.client.execute(`DELETE FROM knowledge_items WHERE id = $1`, [existing.id]); + return true; } - if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) { - return { ok: false, reason: "bad_signature", message: "Signature verification failed." }; +} +function knowledgeOpenApi(version) { + const noteSchema = { + type: "object", + properties: { + id: { type: "string" }, + short_id: { type: "string", nullable: true }, + title: { type: "string" }, + content: { type: "string" }, + url: { type: "string", nullable: true }, + tags: { type: "array", items: { type: "string" } }, + metadata: { type: "object", additionalProperties: true }, + archived: { type: "boolean" }, + created_at: { type: "string" }, + updated_at: { type: "string" }, + version: { type: "integer", description: "Current entry version; send it back as If-Match to write safely." } + }, + required: ["id", "title", "content", "tags", "archived", "created_at", "updated_at", "version"] + }; + const noteVersionSchema = { + type: "object", + description: "An immutable snapshot of the entry as it stood BEFORE the edit that produced the next version.", + properties: { + id: { type: "string" }, + item_id: { type: "string" }, + tenant_id: { type: "string", nullable: true }, + version: { type: "integer" }, + title: { type: "string" }, + content: { type: "string", nullable: true }, + body_uri: { type: "string", nullable: true }, + content_hash: { type: "string" }, + content_bytes: { type: "integer" }, + url: { type: "string", nullable: true }, + tags: { type: "array", items: { type: "string" } }, + metadata: { type: "object", additionalProperties: true }, + archived: { type: "boolean" }, + actor: { type: "string", nullable: true }, + reason: { type: "string", nullable: true }, + valid_from: { type: "string", nullable: true }, + valid_to: { type: "string" } + }, + required: ["id", "item_id", "version", "title", "content_hash", "content_bytes", "tags", "archived", "valid_to"] + }; + const noteInput = { + type: "object", + properties: { + id: { type: "string" }, + title: { type: "string" }, + content: { type: "string" }, + url: { type: "string", nullable: true }, + tags: { type: "array", items: { type: "string" } }, + metadata: { type: "object", additionalProperties: true } + }, + required: ["title"] + }; + const notePatch = { + type: "object", + properties: { + title: { type: "string" }, + content: { type: "string" }, + url: { type: "string", nullable: true }, + tags: { type: "array", items: { type: "string" } }, + metadata: { type: "object", additionalProperties: true }, + archived: { type: "boolean" }, + expected_version: { + type: "integer", + description: "Optimistic concurrency guard, equivalent to the If-Match header, for clients that cannot set headers. " + "The write applies only if the stored entry is still at this version; otherwise 409 version_conflict." + } + } + }; + const versionConflict = { + type: "object", + properties: { + error: { type: "string", enum: ["version_conflict"] }, + expected: { type: "integer" }, + current: { type: "integer" } + }, + required: ["error", "expected", "current"] + }; + return { + openapi: "3.0.3", + info: { title: "Knowledge", version, description: "@hasna/knowledge self-hosted HTTP API" }, + components: { + securitySchemes: { apiKey: { type: "apiKey", in: "header", name: "x-api-key" } }, + schemas: { + Note: noteSchema, + NoteInput: noteInput, + NotePatch: notePatch, + NoteVersion: noteVersionSchema, + VersionConflict: versionConflict, + NoteList: { + type: "object", + properties: { + items: { type: "array", items: { $ref: "#/components/schemas/Note" } }, + total: { type: "integer" } + }, + required: ["items", "total"] + }, + NoteVersionList: { + type: "object", + properties: { + item_id: { type: "string" }, + current_version: { type: "integer" }, + total: { type: "integer" }, + items: { type: "array", items: { $ref: "#/components/schemas/NoteVersion" } } + }, + required: ["item_id", "current_version", "total", "items"] + } + } + }, + security: [{ apiKey: [] }], + paths: { + "/v1/notes": { + get: { + operationId: "listNotes", + summary: "List knowledge items", + parameters: [ + { name: "limit", in: "query", schema: { type: "integer" } }, + { name: "offset", in: "query", schema: { type: "integer" } }, + { name: "search", in: "query", schema: { type: "string" } } + ], + responses: { + "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/NoteList" } } } } + } + }, + post: { + operationId: "createNote", + summary: "Create a knowledge item", + requestBody: { + required: true, + content: { "application/json": { schema: { $ref: "#/components/schemas/NoteInput" } } } + }, + responses: { + "201": { content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } } } + } + } + }, + "/v1/notes/{id}": { + get: { + operationId: "getNote", + summary: "Fetch a knowledge item", + parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], + responses: { + "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } } } + } + }, + patch: { + operationId: "updateNote", + summary: "Update a knowledge item", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + { + name: "If-Match", + in: "header", + required: false, + schema: { type: "string" }, + description: "Optimistic concurrency guard: the version the client last read. The write applies only if the " + "stored entry is still at that version, otherwise 409 version_conflict. Optional in this phase so " + 'already-installed clients keep working; `*` means "any existing version".' + } + ], + requestBody: { + required: true, + content: { "application/json": { schema: { $ref: "#/components/schemas/NotePatch" } } } + }, + responses: { + "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } } }, + "409": { + description: "The stored entry moved on; nothing was written.", + content: { "application/json": { schema: { $ref: "#/components/schemas/VersionConflict" } } } + } + } + }, + delete: { + operationId: "deleteNote", + summary: "Delete a knowledge item", + parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], + responses: { "204": {} } + } + }, + "/v1/notes/{id}/versions": { + get: { + operationId: "listNoteVersions", + summary: "List prior versions of a knowledge item (newest first)", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + { name: "limit", in: "query", schema: { type: "integer" } }, + { name: "offset", in: "query", schema: { type: "integer" } } + ], + responses: { + "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/NoteVersionList" } } } }, + "404": { description: "No such entry. An entry that exists but was never edited returns 200 with an empty list." } + } + } + }, + "/v1/notes/{id}/versions/{version}": { + get: { + operationId: "getNoteVersion", + summary: "Fetch one prior version of a knowledge item", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + { name: "version", in: "path", required: true, schema: { type: "integer" } } + ], + responses: { + "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/NoteVersion" } } } }, + "404": { description: "No such entry, or no such version of it." } + } + } + }, + "/v1/registry": { + get: { + operationId: "getRegistry", + summary: "Knowledge registry contract", + responses: { + "200": { content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } + } + } + } + } + }; +} + +class HttpError extends Error { + status; + constructor(status, message) { + super(message); + this.status = status; } - const now = Math.floor((options.nowMs ?? Date.now()) / 1000); - const leeway = options.leewaySeconds ?? 0; - if (typeof claims.iat === "number" && now + leeway < claims.iat) { - return { ok: false, reason: "not_yet_valid", message: "Token is not yet valid." }; +} +function json(body, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" } + }); +} +function principalActor(principal) { + return principal.agent ? `agent:${principal.agent}` : `key:${principal.kid}`; +} +function parseExpectedVersion(req, body) { + const header = req.headers.get("if-match"); + if (header != null && header.trim() !== "" && header.trim() !== "*") { + const cleaned = header.trim().replace(/^W\//i, "").replace(/^"(.*)"$/, "$1"); + const parsed2 = Number(cleaned); + if (!Number.isInteger(parsed2) || parsed2 < 1) { + throw new HttpError(400, `If-Match must be an entry version number (got ${header}).`); + } + return parsed2; } - if (claims.exp !== null && typeof claims.exp === "number" && now - leeway >= claims.exp) { - return { ok: false, reason: "expired", message: "Token has expired." }; + const fromBody = body.expected_version; + if (fromBody === undefined || fromBody === null) + return; + const parsed = Number(fromBody); + if (!Number.isInteger(parsed) || parsed < 1) { + throw new HttpError(400, "expected_version must be a positive integer entry version."); } - if (options.requiredScopes && options.requiredScopes.length > 0) { - const granted = claims.scopes; - const satisfies = (required) => granted.some((g) => { - if (g === "*") - return true; - const gi = g.indexOf(":"); - const ri = required.indexOf(":"); - if (gi < 0 || ri < 0) - return false; - const gApp = g.slice(0, gi); - const gAction = g.slice(gi + 1); - const rApp = required.slice(0, ri); - const rAction = required.slice(ri + 1); - return (gApp === "*" || gApp === rApp) && (gAction === "*" || gAction === rAction); + return parsed; +} +function createServeHandler(deps) { + const repo = new NoteRepo(deps.client); + const mode2 = "postgres"; + const authOrThrow = async (req, requiredScopes) => { + const url = new URL(req.url); + const decision = await deps.verifier.authenticate(req.headers, { + method: req.method, + path: url.pathname, + requiredScopes }); - for (const required of options.requiredScopes) { - if (!satisfies(required)) { - return { ok: false, reason: "insufficient_scope", message: `Missing required scope '${required}'.` }; + if (decision.ok === false) { + throw new HttpError(decision.status, decision.message); + } + deps.store.touchLastUsed(decision.principal.kid).catch(() => {}); + return decision.principal; + }; + return async (req) => { + const url = new URL(req.url); + const path = url.pathname.replace(/\/+$/, "") || "/"; + const method = req.method.toUpperCase(); + try { + if (path === "/health" && method === "GET") { + return json({ status: "ok", version: deps.version, mode: mode2 }); + } + if (path === "/version" && method === "GET") { + return json({ status: "ok", version: deps.version, mode: mode2 }); + } + if (path === "/ready" && method === "GET") { + try { + await deps.client.query("SELECT 1"); + return json({ status: "ready", version: deps.version, mode: mode2 }); + } catch { + return json({ status: "unavailable", version: deps.version, mode: mode2 }, 503); + } + } + if (path === "/openapi.json" && method === "GET") { + return json(knowledgeOpenApi(deps.version)); + } + if (path === "/v1/registry" && method === "GET") { + await authOrThrow(req, ["knowledge:read"]); + return json(knowledgeRegistryContract({ + mode: "hosted", + sourceSchemes: ["open-files", "s3", "web", "file"], + storageType: "s3", + artifactUriPrefix: process.env.HASNA_KNOWLEDGE_S3_PREFIX ?? null + })); + } + if (path === "/v1/notes") { + if (method === "GET") { + await authOrThrow(req, ["knowledge:read"]); + const result = await repo.list({ + limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined, + offset: url.searchParams.has("offset") ? Number(url.searchParams.get("offset")) : undefined, + search: url.searchParams.get("search") ?? undefined, + includeArchived: url.searchParams.get("includeArchived") === "true" + }); + return json(result); + } + if (method === "POST") { + const principal = await authOrThrow(req, ["knowledge:write"]); + const body = await req.json().catch(() => ({})); + const item = await repo.create(body, { actor: principalActor(principal) }); + return json(item, 201); + } + return json({ error: "method_not_allowed" }, 405); + } + const versionListMatch = path.match(/^\/v1\/notes\/([^/]+)\/versions$/); + if (versionListMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + await authOrThrow(req, ["knowledge:read"]); + const history = await repo.listVersions(decodeURIComponent(versionListMatch[1]), { + limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined, + offset: url.searchParams.has("offset") ? Number(url.searchParams.get("offset")) : undefined + }); + return history ? json(history) : json({ error: "not_found" }, 404); + } + const versionOneMatch = path.match(/^\/v1\/notes\/([^/]+)\/versions\/(\d+)$/); + if (versionOneMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + await authOrThrow(req, ["knowledge:read"]); + const snapshot = await repo.getVersion(decodeURIComponent(versionOneMatch[1]), Number(versionOneMatch[2])); + return snapshot ? json(snapshot) : json({ error: "not_found" }, 404); + } + const noteMatch = path.match(/^\/v1\/notes\/([^/]+)$/); + if (noteMatch) { + const id = decodeURIComponent(noteMatch[1]); + if (method === "GET") { + await authOrThrow(req, ["knowledge:read"]); + const item = await repo.get(id); + return item ? json(item) : json({ error: "not_found" }, 404); + } + if (method === "PATCH") { + const principal = await authOrThrow(req, ["knowledge:write"]); + const body = await req.json().catch(() => ({})); + const expectedVersion = parseExpectedVersion(req, body); + const { expected_version: _ignored, ...patch } = body; + try { + const item = await repo.update(id, patch, { + expectedVersion, + actor: principalActor(principal) + }); + return item ? json(item) : json({ error: "not_found" }, 404); + } catch (error) { + if (error instanceof VersionConflictError) { + return json({ error: "version_conflict", expected: error.expected, current: error.current }, 409); + } + throw error; + } + } + if (method === "DELETE") { + await authOrThrow(req, ["knowledge:write"]); + const ok = await repo.delete(id); + return ok ? new Response(null, { status: 204 }) : json({ error: "not_found" }, 404); + } + return json({ error: "method_not_allowed" }, 405); } + return json({ error: "not_found", path }, 404); + } catch (error) { + if (error instanceof HttpError) { + const reason = error.status === 401 || error.status === 403 ? "unauthorized" : "error"; + return json({ error: reason, message: error.message }, error.status); + } + const message = error instanceof Error ? error.message : "internal error"; + return json({ error: "internal", message }, 500); } - } - return { ok: true, claims, kid: claims.kid, app }; -} -var DEFAULT_API_KEYS_TABLE = "api_keys"; -function createTableSql(table) { - return `CREATE TABLE IF NOT EXISTS ${table} ( - kid TEXT PRIMARY KEY, - app TEXT NOT NULL, - agent TEXT, - scopes JSONB NOT NULL, - token_hash TEXT NOT NULL UNIQUE, - issued_at TIMESTAMPTZ NOT NULL, - expires_at TIMESTAMPTZ, - revoked_at TIMESTAMPTZ, - revoked_reason TEXT, - last_used_at TIMESTAMPTZ, - created_by TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() - )`; -} -function apiKeyMigrations(table = DEFAULT_API_KEYS_TABLE) { - return [ - { id: `hasna_auth_0001_${table}`, sql: createTableSql(table) }, - { - id: `hasna_auth_0002_${table}_indexes`, - sql: `CREATE INDEX IF NOT EXISTS ${table}_app_idx ON ${table} (app); - CREATE INDEX IF NOT EXISTS ${table}_token_hash_idx ON ${table} (token_hash);` - } - ]; -} -function toIso(value) { - if (value === null || value === undefined) - return null; - if (value instanceof Date) - return value.toISOString(); - return new Date(String(value)).toISOString(); + }; } -function parseScopes(value) { - if (Array.isArray(value)) - return value.map((v) => String(v)); - if (typeof value === "string") { - try { - const parsed = JSON.parse(value); - return Array.isArray(parsed) ? parsed.map((v) => String(v)) : []; - } catch { - return []; +async function startKnowledgeServe(options = {}) { + const env = options.env ?? process.env; + const port = options.port ?? Number(env.PORT ?? env.HASNA_KNOWLEDGE_SERVE_PORT ?? 8080); + const hostname = options.hostname ?? env.HOST ?? "0.0.0.0"; + const version = resolveVersion(); + normalizeCloudDatabaseUrl(env); + const client = createKnowledgeCloudClient(); + const store = new ApiKeyStore(client); + const verifier = verifyApiKey({ + app: KNOWLEDGE_SERVE_APP, + signingSecret: resolveSigningSecret(env), + isRevoked: store.isRevoked, + audit: (e) => { + if (e.outcome === "deny") { + console.warn(`[knowledge-serve] auth deny kid=${e.kid ?? "-"} reason=${e.reason} ${e.method} ${e.path}`); + } } + }); + const handler = createServeHandler({ client, verifier, store, version }); + const BunGlobal = globalThis.Bun; + if (!BunGlobal?.serve) { + throw new Error("knowledge-serve requires the Bun runtime (Bun.serve unavailable)."); } - return []; -} -function rowToRecord(row) { + const server = BunGlobal.serve({ port, hostname, fetch: handler }); + console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=postgres, version=${version})`); return { - kid: String(row.kid), - app: String(row.app), - agent: row.agent === null || row.agent === undefined ? null : String(row.agent), - scopes: parseScopes(row.scopes), - tokenHash: String(row.token_hash), - issuedAt: toIso(row.issued_at) ?? new Date(0).toISOString(), - expiresAt: toIso(row.expires_at), - revokedAt: toIso(row.revoked_at), - revokedReason: row.revoked_reason === null || row.revoked_reason === undefined ? null : String(row.revoked_reason), - lastUsedAt: toIso(row.last_used_at), - createdBy: row.created_by === null || row.created_by === undefined ? null : String(row.created_by) + port: server.port, + hostname, + stop: async () => { + server.stop(); + await client.close(); + } }; } -class ApiKeyStore { - client; - table; - constructor(client, options = {}) { - this.client = client; - this.table = options.table ?? DEFAULT_API_KEYS_TABLE; - if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.table)) { - throw new Error(`Invalid api-keys table name '${this.table}'.`); - } +// src/artifact-store.ts +import { chmodSync as chmodSync3, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync6, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs"; +import { dirname as dirname3, join as join4, relative, sep } from "path"; +import { pathToFileURL } from "url"; +function normalizeArtifactKey(key) { + const raw = key.replace(/\\/g, "/").trim(); + if (!raw || raw.startsWith("/")) { + throw new Error(`Invalid artifact key: ${key}`); } - migrations() { - return apiKeyMigrations(this.table); + const segments = raw.split("/").filter(Boolean); + if (segments.length === 0 || segments.some((segment) => segment === "." || segment === "..")) { + throw new Error(`Invalid artifact key: ${key}`); } - async ensureSchema() { - for (const migration of this.migrations()) { - await this.client.execute(migration.sql); - } + return segments.join("/"); +} +function assertInside(root, target) { + const rel = relative(root, target); + if (rel.startsWith("..") || rel === ".." || rel.startsWith(`..${sep}`)) { + throw new Error(`Artifact path escapes root: ${target}`); } - async insert(input) { - await this.client.execute(`INSERT INTO ${this.table} - (kid, app, agent, scopes, token_hash, issued_at, expires_at, created_by) - VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)`, [ - input.kid, - input.app, - input.agent ?? null, - JSON.stringify(input.scopes), - input.tokenHash, - input.issuedAt.toISOString(), - input.expiresAt ? input.expiresAt.toISOString() : null, - input.createdBy ?? null - ]); +} +function s3UserMetadata(metadata) { + if (!metadata) + return; + const output = {}; + for (const [key, value] of Object.entries(metadata)) { + if (typeof value === "string") + output[key] = value; + else if (typeof value === "number" || typeof value === "boolean") + output[key] = String(value); } - async insertMinted(minted, createdBy) { - const claims = minted.claims; - await this.insert({ - kid: minted.kid, - app: claims.app, - agent: claims.agent ?? null, - scopes: claims.scopes, - tokenHash: minted.tokenHash, - issuedAt: new Date(claims.iat * 1000), - expiresAt: claims.exp === null ? null : new Date(claims.exp * 1000), - createdBy: createdBy ?? null - }); + return Object.keys(output).length > 0 ? output : undefined; +} + +class LocalArtifactStore { + root; + type = "local"; + canRead = true; + canWrite = true; + constructor(root) { + this.root = root; + mkdirSync2(root, { recursive: true, mode: 448 }); } - async findByKid(kid) { - const row = await this.client.get(`SELECT * FROM ${this.table} WHERE kid = $1`, [kid]); - return row ? rowToRecord(row) : null; + async put(entry) { + const key = normalizeArtifactKey(entry.key); + const path = join4(this.root, key); + assertInside(this.root, path); + mkdirSync2(dirname3(path), { recursive: true, mode: 448 }); + writeFileSync3(path, entry.body, { mode: 384 }); + chmodSync3(path, 384); + return { key, uri: pathToFileURL(path).href, modified_at: statSync2(path).mtime.toISOString() }; } - async findByTokenHash(tokenHash) { - const row = await this.client.get(`SELECT * FROM ${this.table} WHERE token_hash = $1`, [tokenHash]); - return row ? rowToRecord(row) : null; + async getText(key) { + const normalizedKey = normalizeArtifactKey(key); + const path = join4(this.root, normalizedKey); + assertInside(this.root, path); + return readFileSync6(path, "utf8"); } - isRevoked = async (kid) => { - const row = await this.client.get(`SELECT revoked_at FROM ${this.table} WHERE kid = $1`, [kid]); - if (!row) - return false; - return row.revoked_at !== null && row.revoked_at !== undefined; - }; - async status(kid, nowMs = Date.now()) { - const record = await this.findByKid(kid); - if (!record) - return "unknown"; - if (record.revokedAt) - return "revoked"; - if (record.expiresAt && new Date(record.expiresAt).getTime() <= nowMs) - return "expired"; - return "active"; + async exists(key) { + const normalizedKey = normalizeArtifactKey(key); + const path = join4(this.root, normalizedKey); + assertInside(this.root, path); + return existsSync3(path); } - statusChecker() { - return async (kid) => { - const status = await this.status(kid); - return status !== "active"; - }; +} + +class S3ArtifactStore { + options; + type = "s3"; + canRead = true; + canWrite = true; + client; + constructor(options) { + this.options = options; + this.client = options.client; } - async revoke(kid, reason, atMs = Date.now()) { - const row = await this.client.get(`UPDATE ${this.table} - SET revoked_at = COALESCE(revoked_at, $2), revoked_reason = COALESCE(revoked_reason, $3) - WHERE kid = $1 - RETURNING kid`, [kid, new Date(atMs).toISOString(), reason ?? null]); - return row !== null; + async getClient() { + if (this.client) + return this.client; + const [{ S3Client }, { fromIni }] = await Promise.all([ + import("@aws-sdk/client-s3"), + import("@aws-sdk/credential-providers") + ]); + this.client = new S3Client({ + region: this.options.region, + credentials: this.options.profile ? fromIni({ profile: this.options.profile }) : undefined, + maxAttempts: this.options.max_attempts + }); + return this.client; } - async touchLastUsed(kid, atMs = Date.now()) { - await this.client.execute(`UPDATE ${this.table} SET last_used_at = $2 WHERE kid = $1`, [ - kid, - new Date(atMs).toISOString() + objectKey(key) { + const normalizedKey = normalizeArtifactKey(key); + const prefix = this.options.prefix ? normalizeArtifactKey(this.options.prefix) : ""; + return prefix ? `${prefix}/${normalizedKey}` : normalizedKey; + } + async put(entry) { + const [{ PutObjectCommand }, client] = await Promise.all([ + import("@aws-sdk/client-s3"), + this.getClient() + ]); + const logicalKey = normalizeArtifactKey(entry.key); + const key = this.objectKey(logicalKey); + await client.send(new PutObjectCommand({ + Bucket: this.options.bucket, + Key: key, + Body: entry.body, + ContentType: entry.content_type, + Metadata: s3UserMetadata(entry.metadata), + ServerSideEncryption: this.options.server_side_encryption, + SSEKMSKeyId: this.options.kms_key_id + })); + return { key: logicalKey, uri: `s3://${this.options.bucket}/${key}`, modified_at: new Date().toISOString() }; + } + async getText(key) { + const [{ GetObjectCommand }, client] = await Promise.all([ + import("@aws-sdk/client-s3"), + this.getClient() ]); + const objectKey = this.objectKey(key); + const response = await client.send(new GetObjectCommand({ + Bucket: this.options.bucket, + Key: objectKey + })); + if (!response.Body) + return ""; + return await response.Body.transformToString(); } - async list(options = {}) { - const clauses = []; - const params = []; - if (options.app) { - params.push(options.app); - clauses.push(`app = $${params.length}`); - } - if (!options.includeRevoked) { - clauses.push("revoked_at IS NULL"); + async exists(key) { + const [{ HeadObjectCommand }, client] = await Promise.all([ + import("@aws-sdk/client-s3"), + this.getClient() + ]); + const objectKey = this.objectKey(key); + try { + await client.send(new HeadObjectCommand({ + Bucket: this.options.bucket, + Key: objectKey + })); + return true; + } catch (error) { + const name = error instanceof Error ? error.name : ""; + if (name === "NotFound" || name === "NoSuchKey" || name === "NotFoundError") + return false; + throw error; } - const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""; - const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`); - return rows.map(rowToRecord); } - async revokedKids() { - const rows = await this.client.many(`SELECT kid FROM ${this.table} WHERE revoked_at IS NOT NULL`); - return rows.map((row) => String(row.kid)); +} +function createArtifactStore(config, workspace) { + if (config.storage.type === "s3") { + if (!config.storage.s3?.bucket) + throw new Error("S3 artifact storage requires storage.s3.bucket"); + return new S3ArtifactStore({ + bucket: config.storage.s3.bucket, + prefix: config.storage.s3.prefix, + region: config.storage.s3.region, + profile: config.storage.s3.profile, + max_attempts: config.storage.s3.max_attempts, + server_side_encryption: config.storage.s3.server_side_encryption, + kms_key_id: config.storage.s3.kms_key_id + }); } + return new LocalArtifactStore(workspace.artifactsDir); } -function readHeader(source, name) { - const lower = name.toLowerCase(); - if (typeof source === "function") { - return source(name) ?? source(lower) ?? null; + +// src/service.ts +import { createHash as createHash21 } from "crypto"; +import { spawnSync as spawnSync2 } from "child_process"; +import { existsSync as existsSync14, readFileSync as readFileSync15 } from "fs"; +import { hostname as hostname5 } from "os"; +import { join as join9, resolve as resolve5 } from "path"; + +// src/app-wiki.ts +import { createHash as createHash8, randomUUID as randomUUID4 } from "crypto"; + +// src/storage-contract.ts +import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto"; +import { existsSync as existsSync5, readdirSync } from "fs"; +import { join as join6 } from "path"; +import { pathToFileURL as pathToFileURL2 } from "url"; + +// src/auth.ts +import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync7, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs"; +import { homedir as homedir2 } from "os"; +import { dirname as dirname4, join as join5 } from "path"; +var DEFAULT_KNOWLEDGE_API_URL = "https://knowledge.md"; +function normalizeKnowledgeApiOrigin(apiUrl) { + const url = new URL(apiUrl); + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("Knowledge API URL must use http or https."); } - if (typeof Headers !== "undefined" && source instanceof Headers) { - return source.get(name); + const pathname = url.pathname.replace(/\/+$/, ""); + if (pathname === "/api" || pathname === "/api/v1") { + url.pathname = "/"; + } else if (pathname.endsWith("/api/v1")) { + url.pathname = pathname.slice(0, -"/api/v1".length) || "/"; + } else if (pathname.endsWith("/api")) { + url.pathname = pathname.slice(0, -"/api".length) || "/"; } - const record = source; - const value = record[name] ?? record[lower] ?? record[name.toUpperCase()]; - if (Array.isArray(value)) - return value[0] ?? null; - return value ?? null; + return url.toString().replace(/\/+$/, ""); } -function extractToken(source, headerName = "x-api-key", scheme = "Bearer") { - const direct = readHeader(source, headerName); - if (direct && direct.trim().length > 0) - return direct.trim(); - const authz = readHeader(source, "authorization"); - if (authz) { - const prefix = `${scheme} `; - if (authz.toLowerCase().startsWith(prefix.toLowerCase())) { - const token = authz.slice(prefix.length).trim(); - if (token.length > 0) - return token; - } - } - return null; +function knowledgeAuthPath(env = process.env) { + if (env.HASNA_KNOWLEDGE_AUTH_PATH) + return env.HASNA_KNOWLEDGE_AUTH_PATH; + const root = env.HASNA_KNOWLEDGE_AUTH_DIR ?? join5(homedir2(), ".hasna", "knowledge"); + return join5(root, "auth.json"); } -function verifyApiKey(options) { - if (!options.app) - throw new Error("verifyApiKey requires an 'app' slug."); - if (!options.signingSecret) { - throw new Error("verifyApiKey requires a 'signingSecret'. Set it from HASNA_<APP>_API_SIGNING_KEY."); +function resolveKnowledgeApiUrl(config, env = process.env) { + return normalizeKnowledgeApiOrigin(env.KNOWLEDGE_API_URL ?? config?.hosted?.api_url ?? DEFAULT_KNOWLEDGE_API_URL); +} +function getKnowledgeAuth(env = process.env) { + try { + const path = knowledgeAuthPath(env); + if (!existsSync4(path)) + return null; + const parsed = JSON.parse(readFileSync7(path, "utf8")); + return typeof parsed.api_key === "string" && parsed.api_key.length > 0 ? parsed : null; + } catch { + return null; } - const headerName = options.headerName ?? "x-api-key"; - const scheme = options.scheme ?? "Bearer"; - const clock = options.nowMs ?? (() => Date.now()); - async function emit(event) { - if (!options.audit) - return; - try { - await options.audit(event); - } catch {} +} +function saveKnowledgeAuth(auth, env = process.env) { + const path = knowledgeAuthPath(env); + const stored = { + ...auth, + api_url: auth.api_url ? normalizeKnowledgeApiOrigin(auth.api_url) : undefined, + created_at: auth.created_at ?? new Date().toISOString() + }; + mkdirSync3(dirname4(path), { recursive: true, mode: 448 }); + writeFileSync4(path, `${JSON.stringify(stored, null, 2)} +`, { mode: 384 }); + return stored; +} +function clearKnowledgeAuth(env = process.env) { + try { + unlinkSync2(knowledgeAuthPath(env)); + return true; + } catch { + return false; } - async function authenticate(headers, context = {}) { - const method = context.method ?? null; - const path = context.path ?? null; - const requiredScopes = [...options.requiredScopes ?? [], ...context.requiredScopes ?? []]; - const at = new Date(clock()).toISOString(); - const token = extractToken(headers, headerName, scheme); - if (!token) { - const decision = { - ok: false, - status: 401, - reason: "missing_token", - message: `Missing API key. Send it as '${headerName}: <key>' or 'Authorization: ${scheme} <key>'.` - }; - await emit({ outcome: "deny", app: options.app, kid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at }); - return decision; - } - const verified = verifyApiKeyToken(token, { - signingSecret: options.signingSecret, - expectedApp: options.app, - nowMs: clock(), - ...options.leewaySeconds !== undefined ? { leewaySeconds: options.leewaySeconds } : {}, - requiredScopes - }); - if (!verified.ok) { - const status = verified.reason === "insufficient_scope" ? 403 : 401; - await emit({ outcome: "deny", app: options.app, kid: null, reason: verified.reason, scopesRequired: requiredScopes, method, path, status, at }); - return { ok: false, status, reason: verified.reason, message: verified.message }; - } - if (options.isRevoked) { - const revoked = await options.isRevoked(verified.kid); - if (revoked) { - await emit({ outcome: "deny", app: options.app, kid: verified.kid, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at }); - return { ok: false, status: 401, reason: "revoked", message: "API key has been revoked." }; - } +} +function getKnowledgeApiKey(env = process.env) { + if (env.KNOWLEDGE_API_KEY) + return { apiKey: env.KNOWLEDGE_API_KEY, source: "env" }; + if (env.HASNA_KNOWLEDGE_API_KEY) + return { apiKey: env.HASNA_KNOWLEDGE_API_KEY, source: "env" }; + const auth = getKnowledgeAuth(env); + return auth?.api_key ? { apiKey: auth.api_key, source: "file" } : { apiKey: null, source: "none" }; +} +function knowledgeAuthStatus(config, env = process.env) { + const auth = getKnowledgeAuth(env); + const key = getKnowledgeApiKey(env); + const apiUrl = env.KNOWLEDGE_API_URL ? resolveKnowledgeApiUrl(config, env) : auth?.api_url ? normalizeKnowledgeApiOrigin(auth.api_url) : resolveKnowledgeApiUrl(config, env); + return { + authenticated: Boolean(key.apiKey), + source: key.source, + api_url: apiUrl, + auth_path: knowledgeAuthPath(env), + email: key.source === "file" ? auth?.email ?? null : null, + org_id: key.source === "file" ? auth?.org_id ?? null : null, + org_slug: key.source === "file" ? auth?.org_slug ?? null : null, + user_id: key.source === "file" ? auth?.user_id ?? null : null, + api_key_present: Boolean(key.apiKey) + }; +} + +// src/storage-contract.ts +var GENERATED_ARTIFACTS = [ + { + kind: "schema", + prefix: "schemas/", + description: "Machine-readable agent schemas and source rules." + }, + { + kind: "index", + prefix: "indexes/", + description: "Small orientation indexes and future shard manifests." + }, + { + kind: "log", + prefix: "logs/", + description: "Append-only JSONL run and wiki-maintenance log partitions." + }, + { + kind: "run", + prefix: "runs/", + description: "Prompt/tool/cost ledgers and generated output records." + }, + { + kind: "wiki_page", + prefix: "wiki/", + description: "Generated cited Markdown pages, not raw source files." + }, + { + kind: "export", + prefix: "exports/", + description: "Portable exports and snapshots of derived knowledge state." + } +]; +var FORBIDDEN_WORKSPACE_FILES = [ + "cloud.env", + "knowledge.db.pre-cloud-*.bak", + "db.json.pre-cloud-*.bak", + "migration-exports" +]; +function forbiddenWorkspaceFilesPresent(workspace) { + const present = []; + if (existsSync5(join6(workspace.home, "cloud.env"))) + present.push("cloud.env"); + if (existsSync5(join6(workspace.home, "migration-exports"))) + present.push("migration-exports"); + if (existsSync5(workspace.home)) { + for (const entry of readdirSync(workspace.home)) { + if (/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(entry)) + present.push(entry); } - const principal = { - kid: verified.kid, - app: verified.app, - scopes: verified.claims.scopes, - agent: verified.claims.agent ?? null, - claims: verified.claims - }; - await emit({ outcome: "allow", app: options.app, kid: verified.kid, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at }); - return { ok: true, status: 200, principal }; } - return { authenticate, app: options.app }; + return present; } - -// src/registry-contract.ts -var KNOWLEDGE_REGISTRY_CONTRACT_VERSION = 2; -function knowledgeRegistryContract(input) { +function hashArtifactBody(body) { + const bytes = typeof body === "string" ? Buffer.from(body) : Buffer.from(body); return { - contract_version: KNOWLEDGE_REGISTRY_CONTRACT_VERSION, - service: "open-knowledge", - mode: input.mode, - capabilities: [ - "registry", - "notes-read", - "notes-write", - "open-files-source-refs", - "s3-generated-artifacts" - ], - endpoints: { - registry: "/v1/registry", - notes: "/v1/notes", - note: "/v1/notes/{id}", - health: "/health", - version: "/version", - ready: "/ready", - openapi: "/openapi.json" + hash: `sha256:${createHash3("sha256").update(bytes).digest("hex")}`, + size_bytes: bytes.byteLength + }; +} +function artifactKindForKey(key) { + const match = GENERATED_ARTIFACTS.find((entry) => key.startsWith(entry.prefix)); + return match?.kind ?? "artifact"; +} +function resolveStorageContract(config, workspace, scope = "global") { + const validation = validateStorageConfig(config, workspace); + const s3 = config.storage.s3 ?? null; + const prefix = s3?.prefix?.replace(/^\/+|\/+$/g, "") ?? ""; + const s3UriPrefix = s3 ? `s3://${s3.bucket}/${prefix ? `${prefix}/` : ""}` : ""; + const canonicalPrefix = EXAMPLE_KNOWLEDGE_CANONICAL.s3.prefix.replace(/^\/+|\/+$/g, ""); + const canonicalS3UriPrefix = `s3://${EXAMPLE_KNOWLEDGE_CANONICAL.s3.bucket}/${canonicalPrefix}/`; + const canonicalActive = config.storage.type === "s3" && s3?.bucket === EXAMPLE_KNOWLEDGE_CANONICAL.s3.bucket && (s3.region ?? null) === EXAMPLE_KNOWLEDGE_CANONICAL.s3.region; + return { + scope, + mode: config.mode, + storage_type: config.storage.type, + workspace_home: workspace.home, + local_layout: { + app_path: HASNA_KNOWLEDGE_APP_PATH, + config_path: workspace.configPath, + json_store_path: workspace.jsonStorePath, + knowledge_db_path: workspace.knowledgeDbPath, + directories: { + artifacts: workspace.artifactsDir, + cache: workspace.cacheDir, + exports: workspace.exportsDir, + indexes: workspace.indexesDir, + logs: workspace.logsDir, + runs: workspace.runsDir, + schemas: workspace.schemasDir, + wiki: workspace.wikiDir + } }, - source_contract: { + artifact_store: { + type: config.storage.type, + artifacts_root: config.storage.artifacts_root, + uri_prefix: config.storage.type === "s3" ? s3UriPrefix : pathToFileURL2(`${workspace.artifactsDir}/`).href, + s3: s3 ? { + bucket: s3.bucket, + prefix, + region: s3.region ?? null, + profile: s3.profile ?? null, + server_side_encryption: s3.server_side_encryption ?? null, + kms_key_configured: Boolean(s3.kms_key_id) + } : null + }, + canonical_example: { + division: EXAMPLE_KNOWLEDGE_CANONICAL.division, + app_type: EXAMPLE_KNOWLEDGE_CANONICAL.app_type, + app: EXAMPLE_KNOWLEDGE_CANONICAL.app, + env: EXAMPLE_KNOWLEDGE_CANONICAL.env, + active: canonicalActive, + local_path: EXAMPLE_KNOWLEDGE_CANONICAL.local_path, + s3: { + bucket: EXAMPLE_KNOWLEDGE_CANONICAL.s3.bucket, + region: EXAMPLE_KNOWLEDGE_CANONICAL.s3.region, + profile: EXAMPLE_KNOWLEDGE_CANONICAL.s3.profile, + prefix: canonicalPrefix, + uri_prefix: canonicalS3UriPrefix, + server_side_encryption: EXAMPLE_KNOWLEDGE_CANONICAL.s3.server_side_encryption + }, + secrets: { + env: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.env, + aws: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.aws, + s3: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.s3, + rds: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.rds, + future_rds: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.future_rds + }, + evidence_doc: EXAMPLE_KNOWLEDGE_CANONICAL.evidence_doc + }, + hosted: { + enabled: config.mode === "hosted", + api_url: normalizeKnowledgeApiOrigin(config.hosted?.api_url ?? DEFAULT_KNOWLEDGE_API_URL), + api_url_env: "KNOWLEDGE_API_URL", + api_key_env: "KNOWLEDGE_API_KEY", + auth_storage: "~/.hasna/knowledge/auth.json", + registry_contract_version: KNOWLEDGE_REGISTRY_CONTRACT_VERSION, + requires_hosted_account_for_local_use: false + }, + secret_handling: { + workspace_env_files_supported: false, + forbidden_workspace_files: FORBIDDEN_WORKSPACE_FILES, + forbidden_workspace_files_present: forbiddenWorkspaceFilesPresent(workspace), + runtime_env_keys: [ + "HASNA_KNOWLEDGE_STORAGE_MODE", + "KNOWLEDGE_STORAGE_MODE", + "HASNA_KNOWLEDGE_DATABASE_URL", + "KNOWLEDGE_DATABASE_URL" + ], + secret_ref_authority: "open-secrets", + approved_secret_refs: { + env: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.env, + aws: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.aws, + s3: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.s3, + rds: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.rds + }, + db_url_rotation_decision: { + status: "blocked_without_secret_authority", + reason: "No live secret mutation authority is available in @hasna/knowledge. Rotate the DB URL only through the approved secret authority if separate evidence proves the URL propagated to backups, exports, sync bundles, reports, or copied artifacts.", + authority_required: true + } + }, + source_ownership: { owner: "open-files", - preferred_ref: "open-files", - allowed_schemes: input.sourceSchemes, - raw_source_bytes_stored_in_open_knowledge: false + preferred_ref: config.sources.preferred_ref, + allowed_schemes: config.sources.allowed_schemes, + raw_source_bytes_stored_in_open_knowledge: false, + stores: [ + "source refs", + "source revisions and hashes", + "citation spans", + "redacted extracted chunks", + "embeddings", + "generated wiki artifacts", + "indexes", + "run ledgers" + ], + does_not_store: [ + "raw open-files bytes", + "S3 object credentials", + "connector secrets", + "hosted tenant ownership state" + ] }, - artifact_contract: { - storage_type: input.storageType, - uri_prefix: input.artifactUriPrefix, - generated_only: true - } + private_fleet_boundary: { + manifest_authority: "open-machines", + source_ref_authority: "open-files", + secret_ref_authority: "open-secrets", + raw_private_manifest_bytes_stored_in_open_knowledge: false, + accepted_source_ref_schemes: config.sources.allowed_schemes.filter((scheme) => ["open-files", "s3", "file"].includes(scheme)), + stores: [ + "source refs for private manifests", + "redacted setup decisions", + "runbook summaries", + "citation spans into approved knowledge sources", + "machine setup evidence hashes" + ], + does_not_store: [ + "private fleet manifests", + "machine hostnames", + "machine serial numbers", + "sudo passwords", + "VNC passwords", + "SSH private keys", + "GitHub App private keys", + "secret values" + ], + example_manifest_ref: "open-files://source/private-fleet-manifest/path/machines.json" + }, + generated_artifacts: GENERATED_ARTIFACTS, + scalability: { + catalog: "knowledge.db tracks sources, revisions, chunks, citations, indexes, runs, and storage_objects.", + indexes: "Indexes are cataloged DB rows plus sharded artifacts, not one giant index.md.", + logs: "Logs use dated JSONL partitions under logs/yyyy/mm/dd.jsonl.", + markdown: "Markdown pages are the readable wiki layer over DB/object-store state." + }, + warnings: validation.warnings }; } - -// src/store.ts -import { - chmodSync as chmodSync2, - closeSync, - existsSync as existsSync2, - fsyncSync, - lstatSync, - openSync, - readFileSync as readFileSync3, - renameSync, - unlinkSync, - writeFileSync as writeFileSync2 -} from "fs"; -import { randomUUID } from "crypto"; -import { basename, dirname as dirname2, join as join2 } from "path"; -function defaultStorePath() { - return workspaceForHome(globalKnowledgeHome()).jsonStorePath; -} -function ensureStore(path) { - if (path === defaultStorePath() && existsSync2(legacyGlobalStorePath())) { - importLegacyGlobalStore(); - } - if (!existsSync2(path)) { - ensureParentDir(path); - writeFileAtomic(path, `${JSON.stringify({ items: [] }, null, 2)} -`); +function validateStorageConfig(config, workspace) { + const errors = []; + const warnings = []; + const forbiddenFiles = forbiddenWorkspaceFilesPresent(workspace); + for (const file of forbiddenFiles) { + errors.push(`Forbidden Knowledge workspace file present: ${file}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`); } -} -function timestampForPath(now) { - return now.toISOString().replace(/[:.]/g, "-"); -} -function storeIdentityKeys(item) { - const keys = [`id:${item.id}`]; - if (typeof item.short_id === "string" && item.short_id.length > 0) { - keys.push(`short_id:${item.short_id}`); + if (!workspace.home.endsWith(HASNA_KNOWLEDGE_APP_PATH)) { + warnings.push(`Workspace home does not end with ${HASNA_KNOWLEDGE_APP_PATH}: ${workspace.home}`); } - return keys; -} -function indexStoreItems(items) { - const index = new Set; - for (const item of items) { - for (const key of storeIdentityKeys(item)) - index.add(key); + if (config.storage.type === "s3") { + if (!config.storage.s3?.bucket) + errors.push("storage.s3.bucket is required when storage.type is s3."); + if (!config.storage.s3?.prefix) + warnings.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root."); + if (config.mode === "local") + warnings.push("storage.type is s3 while mode is local; this is valid for BYO S3, but hosted wrappers should set mode to hosted."); } - return index; -} -function storeContainsItem(index, item) { - return storeIdentityKeys(item).some((key) => index.has(key)); -} -function writeJsonFile(path, value) { - ensureParentDir(path); - writeFileSync2(path, `${JSON.stringify(value, null, 2)} -`, { mode: 384 }); - chmodSync2(path, 384); -} -function readStoreFileForImport(path) { - const value = JSON.parse(readFileSync3(path, "utf8")); - if (!value || typeof value !== "object" || !Array.isArray(value.items)) { - return { store: { items: [] }, skippedInvalid: 0 }; + if (config.storage.type === "local" && config.storage.s3) { + warnings.push("storage.s3 is configured but ignored while storage.type is local."); } - const store = { items: [] }; - let skippedInvalid = 0; - for (const item of value.items) { - if (item && typeof item === "object" && typeof item.id === "string" && item.id.length > 0) { - store.items.push(item); - } else { - skippedInvalid += 1; - } + if (config.sources.preferred_ref !== "open-files") { + warnings.push("sources.preferred_ref should stay open-files for durable company knowledge."); } - return { store, skippedInvalid }; -} -function importLegacyGlobalStore(options = {}) { - if (options.dryRun === true) - return importLegacyGlobalStoreUnlocked(options); - return withLock(defaultStorePath(), () => importLegacyGlobalStoreUnlocked(options), { createParent: true }); -} -function importLegacyGlobalStoreUnlocked(options = {}) { - const dryRun = options.dryRun === true; - const now = options.now ?? new Date; - const workspace = workspaceForHome(globalKnowledgeHome()); - const legacyPath = legacyGlobalStorePath(); - const canonicalPath = workspace.jsonStorePath; - const legacyExists = existsSync2(legacyPath); - const canonicalExisted = existsSync2(canonicalPath); - const result = { - ok: true, - dry_run: dryRun, - legacy_path: legacyPath, - canonical_path: canonicalPath, - legacy_exists: legacyExists, - canonical_existed: canonicalExisted, - canonical_created: false, - would_create_canonical: false, - imported: 0, - skipped_existing: 0, - skipped_invalid: 0, - backup_path: null, - report_path: null, - errors: [], - message: legacyExists ? "Legacy global store already imported" : "No legacy global store found" - }; - if (!legacyExists) - return result; - let legacyStore; - try { - const legacy = readStoreFileForImport(legacyPath); - legacyStore = legacy.store; - result.skipped_invalid = legacy.skippedInvalid; - } catch (error) { - result.ok = false; - result.errors.push(`Could not read legacy store: ${error instanceof Error ? error.message : String(error)}`); - result.message = "Legacy global store import failed"; - return result; + if (!config.sources.allowed_schemes.includes("open-files")) { + errors.push("sources.allowed_schemes must include open-files."); } - let canonicalStore = { items: [] }; - if (canonicalExisted) { + if (config.mode === "hosted" && config.hosted?.api_url) { try { - canonicalStore = readStoreFileForImport(canonicalPath).store; - } catch (error) { - result.ok = false; - result.errors.push(`Could not read canonical store: ${error instanceof Error ? error.message : String(error)}`); - result.message = "Legacy global store import failed"; - return result; + normalizeKnowledgeApiOrigin(config.hosted.api_url); + } catch { + errors.push("hosted.api_url must be an http(s) URL when mode is hosted."); } } - const index = indexStoreItems(canonicalStore.items); - const merged = { items: [...canonicalStore.items] }; - for (const item of legacyStore.items) { - if (!item?.id) { - result.skipped_invalid += 1; - continue; - } - if (storeContainsItem(index, item)) { - result.skipped_existing += 1; - continue; + return { + ok: errors.length === 0, + errors, + warnings + }; +} +function recordStorageObjects(db, objects, now = new Date) { + const timestamp = now.toISOString(); + const statement = db.prepare(` + INSERT INTO storage_objects ( + id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(artifact_uri) DO UPDATE SET + kind = excluded.kind, + content_type = excluded.content_type, + hash = excluded.hash, + size_bytes = excluded.size_bytes, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at + `); + const insert = db.transaction((entries) => { + for (const entry of entries) { + const metadata = { + key: entry.key, + ...entry.modified_at ? { artifact_modified_at: entry.modified_at } : {}, + ...entry.metadata ?? {} + }; + statement.run(randomUUID2(), entry.uri, entry.kind, entry.content_type ?? null, entry.hash ?? null, entry.size_bytes ?? null, JSON.stringify(metadata), timestamp, timestamp); } - merged.items.push(item); - for (const key of storeIdentityKeys(item)) - index.add(key); - result.imported += 1; - } - result.would_create_canonical = !canonicalExisted && result.imported > 0; - result.canonical_created = !dryRun && result.would_create_canonical; - result.message = result.imported > 0 ? `Imported ${result.imported} legacy item(s) into canonical knowledge store` : "Legacy global store already imported"; - if (dryRun || result.imported === 0) - return result; - const suffix = `${timestampForPath(now)}-${randomUUID().slice(0, 8)}`; - if (canonicalExisted) { - result.backup_path = join2(workspace.exportsDir, `legacy-open-knowledge-db-before-import-${suffix}.json`); - writeJsonFile(result.backup_path, canonicalStore); - } - writeJsonFile(canonicalPath, merged); - result.report_path = join2(workspace.runsDir, `legacy-open-knowledge-import-${suffix}.json`); - writeJsonFile(result.report_path, result); - return result; + }); + insert(objects); } -function loadStoreIfExists(path) { - if (!existsSync2(path)) - return { exists: false, items: [] }; - const raw = readFileSync3(path, "utf8"); - const parsed = JSON.parse(raw); - if (!parsed || !Array.isArray(parsed.items)) { - return { exists: true, items: [] }; - } - return { exists: true, items: parsed.items }; + +// src/provenance.ts +function isStaleStatus(status) { + return ["deleted", "stale", "invalidated", "reindex_required"].includes((status ?? "").toLowerCase()); } -function lockPath(path) { - return `${path}.lock`; +function sourceProvenance(input) { + const status = input.status ?? null; + return { + source_owner: "open-files", + source_ref: input.source_ref ?? null, + source_uri: input.source_uri ?? null, + source_kind: input.source_kind ?? null, + source_revision_id: input.source_revision_id ?? null, + revision: input.revision ?? null, + hash: input.hash ?? null, + chunk_id: input.chunk_id ?? null, + start_offset: input.start_offset ?? null, + end_offset: input.end_offset ?? null, + status, + read_only: true, + citation_required: true, + resolver: input.resolver ?? null, + stale: isStaleStatus(status) + }; } -var LOCK_MAX_WAIT_MS = 1e4; -var LOCK_RETRY_MS = 25; -var LOCK_STALE_MS = 120000; -var SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4)); -function errCode(error) { - return typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined; +function generatedArtifactProvenance(input) { + return { + source_owner: "open-files", + generated_from: input.generated_from, + artifact_key: input.artifact_key, + source_refs: input.source_refs ?? [], + read_only_sources: true, + citation_required: input.citation_required ?? true, + raw_source_bytes_stored_in_open_knowledge: false + }; } -function syncParentDir(path) { - let fd = null; - try { - fd = openSync(dirname2(path), "r"); - fsyncSync(fd); - } catch {} finally { - if (fd !== null) { - try { - closeSync(fd); - } catch {} - } - } +function withProvenance(metadata, provenance) { + return { + ...metadata, + provenance + }; } -var heldLockPaths = new Set; -function writeFileAtomic(path, contents) { - ensureParentDir(path); - const tmp = join2(dirname2(path), `.${basename(path)}.tmp.${randomUUID()}`); - let fd = null; - try { - fd = openSync(tmp, "wx", 384); - writeFileSync2(fd, contents); - fsyncSync(fd); - closeSync(fd); - fd = null; - renameSync(tmp, path); - try { - chmodSync2(path, 384); - } catch {} - syncParentDir(path); - } catch (error) { - if (fd !== null) { - try { - closeSync(fd); - } catch {} + +// src/source-ingest.ts +import { createHash as createHash7 } from "crypto"; +import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs"; +import { basename as basename3 } from "path"; + +// src/manifest-ingest.ts +import { createHash as createHash6 } from "crypto"; +import { existsSync as existsSync6, readFileSync as readFileSync8 } from "fs"; +import { basename as basename2 } from "path"; + +// src/source-ref.ts +import { fileURLToPath } from "url"; +function assertNonEmpty(value, message) { + if (!value) + throw new Error(message); + return value; +} +function parseOpenFilesRef(uri) { + const withoutScheme = uri.slice("open-files://".length); + const parts = withoutScheme.split("/").filter(Boolean); + const entity = parts[0]; + if (entity !== "file" && entity !== "source") { + throw new Error("Invalid open-files ref. Expected open-files://file/<id>, open-files://file/<id>/revision/<revision_id>, or open-files://source/<id>/path/<path>."); + } + const id = assertNonEmpty(parts[1], "Invalid open-files ref. Missing id."); + if (entity === "file") { + if (parts.length === 2) + return { kind: "open-files", uri, entity, id }; + if (parts[2] === "revision" && parts[3] && parts.length === 4) { + return { kind: "open-files", uri, entity, id, revision_id: decodeURIComponent(parts[3]) }; } - try { - unlinkSync(tmp); - } catch {} - throw error; + throw new Error("Invalid open-files file ref. Expected open-files://file/<id>/revision/<revision_id>."); } + const pathIndex = parts.indexOf("path"); + const path = pathIndex >= 0 ? decodeURIComponent(parts.slice(pathIndex + 1).join("/")) : undefined; + return { kind: "open-files", uri, entity, id, path }; } -function sleepSync(ms) { - Atomics.wait(SLEEP_BUFFER, 0, 0, ms); +function parseS3Ref(uri) { + const parsed = new URL(uri); + const bucket = assertNonEmpty(parsed.hostname, "Invalid s3 ref. Missing bucket."); + const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); + if (!key) + throw new Error("Invalid s3 ref. Missing object key."); + return { kind: "s3", uri, bucket, key }; } -function processIsAlive(pid) { - if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) - return false; - try { - process.kill(pid, 0); - return true; - } catch (error) { - return errCode(error) !== "ESRCH"; +function parseFileRef(uri) { + return { kind: "file", uri, path: fileURLToPath(uri) }; +} +function parseWebRef(uri) { + const parsed = new URL(uri); + return { kind: "web", uri, url: parsed.toString() }; +} +function parseSourceRef(uri) { + if (uri.startsWith("open-files://")) + return parseOpenFilesRef(uri); + if (uri.startsWith("s3://")) + return parseS3Ref(uri); + if (uri.startsWith("file://")) + return parseFileRef(uri); + if (uri.startsWith("https://") || uri.startsWith("http://")) + return parseWebRef(uri); + throw new Error(`Unsupported source ref scheme: ${uri}`); +} +function catalogSourceUriForRef(uri, parsed = parseSourceRef(uri)) { + if (parsed.kind === "open-files" && parsed.entity === "file" && parsed.revision_id) { + return uri.replace(/\/revision\/[^/]+$/, ""); } + return uri; } -function lockIsStale(path, now) { - try { - const raw = readFileSync3(path, "utf8"); - const lock = JSON.parse(raw); - if (typeof lock.ts === "number") { - return now - lock.ts > LOCK_STALE_MS && !processIsAlive(lock.pid); - } - } catch {} +function revisionIdForSourceRef(uri) { + const parsed = parseSourceRef(uri); + return parsed.kind === "open-files" && parsed.entity === "file" ? parsed.revision_id ?? null : null; +} +function isSupportedSourceRef(uri) { try { - return now - lstatSync(path).mtimeMs > LOCK_STALE_MS; + parseSourceRef(uri); + return true; } catch { return false; } } -function moveStaleLock(path) { - const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); - const stalePath = `${path}.stale.${stamp}.${randomUUID()}`; - try { - renameSync(path, stalePath); - } catch (error) { - if (errCode(error) !== "ENOENT") - throw error; - return; - } + +// src/safety.ts +import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto"; +import { relative as relative2, resolve as resolve2, sep as sep2 } from "path"; +function envEnabled(name) { + const value = process.env[name]; + return value === "1" || value === "true" || value === "yes"; } -function breakStaleLock(lockPath2) { - const owner = randomUUID(); - const breakerPath = `${lockPath2}.breaker`; - const start = Date.now(); - while (Date.now() - start < LOCK_MAX_WAIT_MS) { - if (tryAcquireLock(breakerPath, owner)) { - try { - if (lockIsStale(lockPath2, Date.now())) { - moveStaleLock(lockPath2); - } - } finally { - releaseLock(breakerPath, owner); - } - return; +function resolveSafetyPolicy(config, workspace) { + const extended = config; + const configuredBuckets = new Set(extended.safety?.network?.allowed_s3_buckets ?? []); + if (config.storage.type === "s3" && config.storage.s3?.bucket) + configuredBuckets.add(config.storage.s3.bucket); + if (process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS) { + for (const bucket of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((entry) => entry.trim()).filter(Boolean)) { + configuredBuckets.add(bucket); } - sleepSync(LOCK_RETRY_MS); } - throw new Error(`Could not acquire stale-lock breaker on ${breakerPath} after ${LOCK_MAX_WAIT_MS}ms`); -} -function tryAcquireLock(path, ownerId) { - let fd = null; - let created = false; - try { - fd = openSync(path, "wx", 384); - created = true; - writeFileSync2(fd, `${JSON.stringify({ owner: ownerId, pid: process.pid, ts: Date.now() })} -`); - fsyncSync(fd); - closeSync(fd); - fd = null; - syncParentDir(path); - return true; - } catch (error) { - if (fd !== null) { - try { - closeSync(fd); - } catch {} - } - if (created) { - try { - unlinkSync(path); - } catch {} + return { + mode: config.mode, + allowWriteRoots: [ + workspace.home, + workspace.artifactsDir, + workspace.cacheDir, + workspace.exportsDir, + workspace.indexesDir, + workspace.logsDir, + workspace.runsDir, + workspace.schemasDir, + workspace.wikiDir + ].map((entry) => resolve2(entry)), + readOnlySourceAccess: true, + network: { + webSearchEnabled: extended.safety?.network?.web_search_enabled ?? envEnabled("HASNA_KNOWLEDGE_WEB_SEARCH"), + s3ReadsEnabled: extended.safety?.network?.s3_reads_enabled ?? envEnabled("HASNA_KNOWLEDGE_ALLOW_S3_READS"), + allowedS3Buckets: [...configuredBuckets].sort() + }, + redaction: { + enabled: extended.safety?.redaction?.enabled ?? true + }, + approvals: { + generatedWritesRequireApproval: extended.safety?.approvals?.generated_writes_require_approval ?? true } - if (errCode(error) === "EEXIST") - return false; - throw error; - } + }; } -function acquireLock(lockPath2, ownerId) { - const start = Date.now(); - while (Date.now() - start < LOCK_MAX_WAIT_MS) { - if (tryAcquireLock(lockPath2, ownerId)) - return; - if (lockIsStale(lockPath2, Date.now())) { - breakStaleLock(lockPath2); - } - sleepSync(LOCK_RETRY_MS); - } - throw new Error(`Could not acquire lock on ${lockPath2} after ${LOCK_MAX_WAIT_MS}ms`); +function isInside(root, target) { + const rel = relative2(root, target); + return rel === "" || !rel.startsWith("..") && rel !== ".." && !rel.startsWith(`..${sep2}`); } -function releaseLock(lockPath2, ownerId) { - try { - if (existsSync2(lockPath2)) { - const lock = JSON.parse(readFileSync3(lockPath2, "utf8")); - if (lock.owner === ownerId) { - unlinkSync(lockPath2); - } - } - } catch {} +function assertWriteAllowed(targetPath, policy) { + const resolved = resolve2(targetPath); + if (!policy.allowWriteRoots.some((root) => isInside(root, resolved))) { + throw new Error(`Safety policy denied write outside .hasna/knowledge: ${targetPath}`); + } } -function loadStore(path) { - ensureStore(path); - const raw = readFileSync3(path, "utf8"); - const parsed = JSON.parse(raw); - if (!parsed || !Array.isArray(parsed.items)) { - return { items: [] }; +function assertS3ReadAllowed(uri, policy) { + const parsed = new URL(uri); + const bucket = parsed.hostname; + if (!policy.network.s3ReadsEnabled) { + throw new Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1."); + } + if (!policy.network.allowedS3Buckets.includes(bucket)) { + throw new Error(`Safety policy denied S3 bucket "${bucket}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`); } - return parsed; } -function saveStore(path, store) { - writeFileAtomic(path, `${JSON.stringify(store, null, 2)} -`); +function assertWebSearchAllowed(policy) { + if (!policy.network.webSearchEnabled) { + throw new Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1."); + } } -function withLock(path, fn, options = {}) { - const owner = randomUUID(); - const lpath = lockPath(path); - if (heldLockPaths.has(lpath)) - return fn(); - if (options.createParent) - ensureParentDir(lpath); - acquireLock(lpath, owner); - heldLockPaths.add(lpath); - try { - return fn(); - } finally { - heldLockPaths.delete(lpath); - releaseLock(lpath, owner); +var REDACTION_PATTERNS = [ + { type: "private_key_block", severity: "high", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, replacement: "[REDACTED:private_key_block]" }, + { type: "secret_assignment", severity: "high", regex: /\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi, replacement: "[REDACTED:secret_assignment]" }, + { type: "openai_api_key", severity: "high", regex: /\bsk-[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:openai_api_key]" }, + { type: "anthropic_api_key", severity: "high", regex: new RegExp(`\\b${["sk", "ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`, "g"), replacement: "[REDACTED:anthropic_api_key]" }, + { type: "aws_access_key_id", severity: "high", regex: /\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g, replacement: "[REDACTED:aws_access_key_id]" } +]; +function redactSecrets(text, policy) { + if (policy && !policy.redaction.enabled) + return { text, findings: [] }; + let output = text; + const findings = []; + for (const pattern of REDACTION_PATTERNS) { + output = output.replace(pattern.regex, (match, ...args) => { + const offset = typeof args.at(-2) === "number" ? args.at(-2) : output.indexOf(match); + findings.push({ + type: pattern.type, + severity: pattern.severity, + start: Math.max(0, offset), + end: Math.max(0, offset + match.length) + }); + return pattern.replacement; + }); } + return { text: output, findings }; } -function makeId() { - return `k_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`; +function auditId(input) { + return `audit_${createHash4("sha256").update(`${input.event_type}\x00${input.action}\x00${input.target_uri ?? ""}\x00${input.created_at ?? ""}\x00${JSON.stringify(input.metadata ?? {})}\x00${randomUUID3()}`).digest("hex").slice(0, 24)}`; } -function makeShortId(id) { - return id.replace(/^k_/, "").slice(0, 12); +function truncateAuditMetadata(value, depth = 0) { + if (depth > 6) + return "[Truncated:depth]"; + if (typeof value === "string") { + return value.length > 1000 ? `${value.slice(0, 1000)}...[Truncated:${value.length - 1000} chars]` : value; + } + if (typeof value === "number" || typeof value === "boolean" || value === null || value === undefined) + return value; + if (Array.isArray(value)) { + const entries = value.slice(0, 25).map((entry) => truncateAuditMetadata(entry, depth + 1)); + if (value.length > 25) + entries.push(`[Truncated:${value.length - 25} items]`); + return entries; + } + if (typeof value === "object") { + const output = {}; + const entries = Object.entries(value).slice(0, 50); + for (const [key, entry] of entries) + output[key] = truncateAuditMetadata(entry, depth + 1); + const total = Object.keys(value).length; + if (total > entries.length) + output.__truncated_keys = total - entries.length; + return output; + } + return String(value); } - -// src/serve.ts -var KNOWLEDGE_SERVE_APP = "knowledge"; -function normalizeCloudDatabaseUrl(env = process.env) { - const key = "HASNA_KNOWLEDGE_DATABASE_URL"; - const url = env[key] ?? env.KNOWLEDGE_DATABASE_URL; - if (!url) - return url; - const lower = url.toLowerCase(); - const needsCompat = (lower.includes("sslmode=require") || lower.includes("sslmode=prefer")) && !lower.includes("uselibpqcompat"); - if (!needsCompat) - return url; - const updated = url.includes("?") ? `${url}&uselibpqcompat=true` : `${url}?uselibpqcompat=true`; - env[key] = updated; - return updated; +function recordAuditEvent(db, input) { + const createdAt = input.created_at ?? new Date().toISOString(); + const metadata = truncateAuditMetadata(input.metadata ?? {}); + const id = auditId({ ...input, metadata, created_at: createdAt }); + db.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, [ + id, + input.event_type, + input.action, + input.target_uri ?? null, + input.decision, + JSON.stringify(metadata), + createdAt + ]); + return id; } -function resolveVersion() { - if (process.env.HASNA_KNOWLEDGE_VERSION) - return process.env.HASNA_KNOWLEDGE_VERSION; - try { - const url = new URL("../package.json", import.meta.url); - const pkg = JSON.parse(readFileSync4(url, "utf8")); - return pkg.version ?? "0.0.0"; - } catch { - return process.env.npm_package_version ?? "0.0.0"; +function recordRedactionFindings(db, input) { + const createdAt = input.created_at ?? new Date().toISOString(); + for (const finding of input.findings) { + db.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, [ + `redact_${randomUUID3()}`, + input.source_uri ?? null, + input.run_id ?? null, + finding.severity, + finding.type, + JSON.stringify({ ...input.metadata ?? {}, start: finding.start, end: finding.end }), + createdAt + ]); } + return input.findings.length; } -function resolveSigningSecret(env = process.env) { - const secret = env.HASNA_KNOWLEDGE_API_SIGNING_KEY ?? env.API_KEY_SIGNING_SECRET ?? env.HASNA_API_SIGNING_KEY; - if (!secret) { - throw new Error("knowledge-serve requires an API signing secret: set HASNA_KNOWLEDGE_API_SIGNING_KEY " + "(or API_KEY_SIGNING_SECRET / HASNA_API_SIGNING_KEY)."); - } - return secret; +function createApprovalGate(db, input) { + const now = input.created_at ?? new Date().toISOString(); + const id = `approval_${randomUUID3()}`; + db.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + id, + input.action, + input.target_uri ?? null, + "approved", + input.reason ?? null, + input.approved_by ?? "local-cli", + JSON.stringify(input.metadata ?? {}), + now, + now + ]); + return { id, status: "approved" }; } +var COMMON_BARE_TOKEN_PATTERNS = [ + { type: "github_token", severity: "high", regex: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_token]" }, + { type: "github_pat_token", severity: "high", regex: /\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_pat_token]" }, + { type: "package_registry_token", severity: "high", regex: /\bnpm_[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:package_registry_token]" }, + { type: "context7_token", severity: "high", regex: /\bctx7sk[-][A-Za-z0-9_-]{10,}\b/g, replacement: "[REDACTED:context7_token]" }, + { type: "xai_api_key", severity: "high", regex: /\bxai[-][A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:xai_api_key]" }, + { type: "google_api_key", severity: "high", regex: /\bAIza[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:google_api_key]" } +]; +REDACTION_PATTERNS.push(...COMMON_BARE_TOKEN_PATTERNS); -class VersionConflictError extends Error { - expected; - current; - code = "version_conflict"; - constructor(expected, current) { - super(`version_conflict: expected version ${expected}, stored version is ${current}`); - this.expected = expected; - this.current = current; - this.name = "VersionConflictError"; - } +// src/private-ref.ts +import { createHash as createHash5 } from "crypto"; +import { realpathSync } from "fs"; +import { homedir as homedir3, tmpdir } from "os"; +var PATH_TAIL = String.raw`[^\s"'<>),\]}]`; +var PATH_SEGMENT = String.raw`[^/\\\s"'<>]+`; +var FILE_URI_RE = /file:\/\/[^\s"'<>),\]}]+/gi; +var ABSOLUTE_HASNA_PATH_RE = /\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g; +var HASNA_PATH_RE = /(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi; +var PRIVATE_WORKSPACE_PATH_RE = new RegExp(String.raw`/(?:home|Users)/${PATH_SEGMENT}/(?:workspace|Workspace)/${PATH_TAIL}*`, "g"); +var LOCAL_PATH_PATTERNS = [ + new RegExp(String.raw`/(?:home|Users)/${PATH_SEGMENT}(?:/${PATH_TAIL}*)?`, "g"), + new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${PATH_TAIL}+`, "g"), + new RegExp(String.raw`(?:/private)?/tmp/${PATH_TAIL}+`, "g"), + new RegExp(String.raw`(?<![A-Za-z0-9])[A-Za-z]:[\\/]${PATH_TAIL}+`, "g"), + new RegExp(String.raw`\\\\${PATH_SEGMENT}\\${PATH_TAIL}+`, "g") +]; +var RAW_DB_OR_ENV_RE = /\b(?:knowledge\.db(?:[-.][A-Za-z0-9_-]+)?|db\.json(?:[-.][A-Za-z0-9_-]+)?|cloud\.env|migration-exports\/[^\s"'<>),\]}]+)\b/gi; +var DATABASE_URL_RE = /\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi; +var OPAQUE_EXPORT_KEYS = new Set(["content_base64"]); +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -function parseJsonColumn(value, fallback) { - if (value == null) - return fallback; - if (typeof value === "string") { +function isUsableRoot(root) { + return root.length >= 4 && root !== "/" && !/^[A-Za-z]:[\\/]?$/.test(root); +} +var hostRootCacheKey = null; +var hostRootCache = []; +function hostRootPatterns() { + const roots = new Set; + for (const root of [homedir3(), tmpdir()]) { + if (!root) + continue; + roots.add(root); try { - return JSON.parse(value); - } catch { - return fallback; - } + roots.add(realpathSync(root)); + } catch {} } - return value; + const key = [...roots].sort().join("\x00"); + if (key === hostRootCacheKey) + return hostRootCache; + hostRootCacheKey = key; + hostRootCache = [...roots].filter(isUsableRoot).sort((a, b) => b.length - a.length).map((root) => new RegExp(`${escapeRegExp(root)}(?:[/\\\\]${PATH_TAIL}*)?`, "g")); + return hostRootCache; } -function rowToVersion(row) { - return { - id: String(row.id), - item_id: String(row.item_id), - tenant_id: row.tenant_id ?? null, - version: Number(row.version), - title: String(row.title ?? ""), - content: row.content ?? null, - body_uri: row.body_uri ?? null, - content_hash: String(row.content_hash ?? ""), - content_bytes: Number(row.content_bytes ?? 0), - url: row.url ?? null, - tags: parseJsonColumn(row.tags, []), - metadata: parseJsonColumn(row.metadata, {}), - archived: Boolean(row.archived), - actor: row.actor ?? null, - reason: row.reason ?? null, - valid_from: row.valid_from ?? null, - valid_to: String(row.valid_to ?? "") - }; +function fingerprint(value) { + return createHash5("sha256").update(value).digest("hex").slice(0, 12); } -function rowToItem(row) { - const parseJson = (value, fallback) => { - if (value == null) - return fallback; - if (typeof value === "string") { - try { - return JSON.parse(value); - } catch { - return fallback; - } - } - return value; - }; - return { - id: String(row.id), - short_id: row.short_id ?? null, - title: String(row.title ?? ""), - content: String(row.content ?? ""), - url: row.url ?? null, - tags: parseJson(row.tags, []), - metadata: parseJson(row.metadata, {}), - archived: Boolean(row.archived), - created_at: String(row.created_at), - updated_at: String(row.updated_at), - version: row.version == null ? 1 : Number(row.version) - }; +function preview(value) { + return value.length <= 80 ? value : `${value.slice(0, 77)}...`; } - -class NoteRepo { - client; - constructor(client) { - this.client = client; +function includesPrivateKnowledgeArtifact(value) { + return /(?:^|\/)\.hasna(?:\/|$)/i.test(value) || /\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test(value) || /\bmigration-exports\//i.test(value); +} +function addStringIssues(value, path, options, issues) { + for (const match of value.matchAll(FILE_URI_RE)) { + const uri = match[0]; + if (!options.allowFileSourceRefs || includesPrivateKnowledgeArtifact(uri)) { + issues.push({ + type: includesPrivateKnowledgeArtifact(uri) ? "private_file_uri" : "local_file_uri", + severity: "high", + path, + preview: preview(uri.replace(/^file:\/\/.*/, `[redacted:file-uri:${fingerprint(uri)}]`)) + }); + } + } + for (const match of value.matchAll(HASNA_PATH_RE)) { + issues.push({ + type: "private_hasna_path", + severity: "high", + path, + preview: `[redacted:.hasna:${fingerprint(match[0])}]` + }); + } + for (const match of value.matchAll(RAW_DB_OR_ENV_RE)) { + issues.push({ + type: match[0].toLowerCase() === "cloud.env" ? "workspace_env_file" : "raw_database_or_export_ref", + severity: "high", + path, + preview: `[redacted:${fingerprint(match[0])}]` + }); } - async write(options, fn) { - return this.client.transaction(async (tx) => { - await tx.execute(`SELECT set_config('hasna.actor', $1, true), set_config('hasna.reason', $2, true)`, [ - options.actor ?? "", - options.reason ?? "" - ]); - return fn(tx); + for (const match of value.matchAll(DATABASE_URL_RE)) { + issues.push({ + type: "database_url", + severity: "high", + path, + preview: `[redacted:database-url:${fingerprint(match[0])}]` }); } - async create(input, options = {}) { - if (!input.title || typeof input.title !== "string") { - throw new HttpError(400, "title is required"); - } - const now = new Date().toISOString(); - const suppliedId = typeof input.id === "string" ? input.id.trim() : ""; - if (suppliedId) { - const row2 = await this.write(options, (tx) => tx.get(`INSERT INTO knowledge_items (id, short_id, title, content, url, tags, metadata, archived, created_at, updated_at) - VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7::jsonb,FALSE,$8,$8) - ON CONFLICT (id) DO UPDATE SET - title = EXCLUDED.title, - content = EXCLUDED.content, - url = EXCLUDED.url, - tags = EXCLUDED.tags, - metadata = EXCLUDED.metadata, - updated_at = EXCLUDED.updated_at - RETURNING *`, [ - suppliedId, - makeShortId(suppliedId), - input.title, - input.content ?? "", - input.url ?? null, - JSON.stringify(input.tags ?? []), - JSON.stringify(input.metadata ?? {}), - now - ])); - return rowToItem(row2); + if (!options.allowPrivateWorkspaceRefs) { + for (const match of value.matchAll(PRIVATE_WORKSPACE_PATH_RE)) { + issues.push({ + type: "private_workspace_path", + severity: "medium", + path, + preview: `[redacted:workspace:${fingerprint(match[0])}]` + }); } - const id = makeId(); - const row = await this.write(options, (tx) => tx.get(`INSERT INTO knowledge_items (id, short_id, title, content, url, tags, metadata, archived, created_at, updated_at) - VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7::jsonb,FALSE,$8,$9) - RETURNING *`, [ - id, - makeShortId(id), - input.title, - input.content ?? "", - input.url ?? null, - JSON.stringify(input.tags ?? []), - JSON.stringify(input.metadata ?? {}), - now, - now - ])); - return rowToItem(row); } - async list(options = {}) { - const limit = Math.min(Math.max(options.limit ?? 50, 1), 200); - const offset = Math.max(options.offset ?? 0, 0); - const where = []; - const params = []; - if (!options.includeArchived) - where.push("archived = FALSE"); - const search = options.search?.trim(); - let tsQueryExpr = null; - if (search) { - params.push(search); - tsQueryExpr = `websearch_to_tsquery('english', $${params.length})`; - where.push(`search_vector @@ ${tsQueryExpr}`); +} +function lintPrivateRefs(value, options = {}, path = "$") { + const issues = []; + const visit = (entry, entryPath) => { + if (typeof entry === "string") { + addStringIssues(entry, entryPath, options, issues); + return; } - const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : ""; - const orderSql = tsQueryExpr ? `ORDER BY ts_rank_cd(search_vector, ${tsQueryExpr}) DESC, created_at DESC` : "ORDER BY created_at DESC"; - const totalRow = await this.client.get(`SELECT count(*)::text AS count FROM knowledge_items ${whereSql}`, params); - const rows = await this.client.many(`SELECT * FROM knowledge_items ${whereSql} ${orderSql} LIMIT ${limit} OFFSET ${offset}`, params); - return { items: rows.map(rowToItem), total: Number(totalRow?.count ?? 0) }; - } - async get(idOrShort) { - const row = await this.client.get(`SELECT * FROM knowledge_items WHERE id = $1 OR short_id = $1 LIMIT 1`, [idOrShort]); - return row ? rowToItem(row) : null; - } - async update(idOrShort, patch, options = {}) { - const existing = await this.get(idOrShort); - if (!existing) - return null; - const sets = []; - const params = []; - const push = (col, val, cast = "") => { - params.push(val); - sets.push(`${col} = $${params.length}${cast}`); - }; - if (patch.title !== undefined) - push("title", patch.title); - if (patch.content !== undefined) - push("content", patch.content); - if (patch.url !== undefined) - push("url", patch.url); - if (patch.tags !== undefined) - push("tags", JSON.stringify(patch.tags), "::jsonb"); - if (patch.metadata !== undefined) - push("metadata", JSON.stringify(patch.metadata), "::jsonb"); - if (patch.archived !== undefined) - push("archived", patch.archived); - push("updated_at", new Date().toISOString()); - params.push(existing.id); - let where = `id = $${params.length}`; - const { expectedVersion } = options; - if (expectedVersion !== undefined) { - params.push(expectedVersion); - where += ` AND version = $${params.length}`; + if (!entry || typeof entry !== "object") + return; + if (Array.isArray(entry)) { + entry.forEach((item, index) => visit(item, `${entryPath}[${index}]`)); + return; } - const row = await this.write(options, (tx) => tx.get(`UPDATE knowledge_items SET ${sets.join(", ")} WHERE ${where} RETURNING *`, params)); - if (row) - return rowToItem(row); - if (expectedVersion === undefined) - return null; - const current = await this.get(existing.id); - if (!current) - return null; - throw new VersionConflictError(expectedVersion, current.version ?? 1); + for (const [key, item] of Object.entries(entry)) { + visit(item, `${entryPath}.${key}`); + } + }; + visit(value, path); + return issues; +} +function assertNoPrivateRefs(value, options = {}) { + const issues = lintPrivateRefs(value, options); + if (issues.length === 0) + return; + const counts = new Map; + for (const issue of issues) + counts.set(issue.type, (counts.get(issue.type) ?? 0) + 1); + const summary = [...counts.entries()].map(([type, count2]) => `${type}:${count2}`).join(", "); + throw new Error(`Knowledge private-ref lint failed (${summary}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`); +} +function redactString(value) { + let text = redactSecrets(value).text.replace(DATABASE_URL_RE, (match) => `[REDACTED:database-url:${fingerprint(match)}]`).replace(FILE_URI_RE, (match) => `[REDACTED:local-file-uri:${fingerprint(match)}]`).replace(ABSOLUTE_HASNA_PATH_RE, (match) => `[REDACTED:local-hasna-path:${fingerprint(match)}]`).replace(PRIVATE_WORKSPACE_PATH_RE, (match) => `[REDACTED:private-workspace:${fingerprint(match)}]`); + for (const pattern of [...hostRootPatterns(), ...LOCAL_PATH_PATTERNS]) { + text = text.replace(pattern, (match) => `[REDACTED:local-path:${fingerprint(match)}]`); } - async listVersions(idOrShort, options = {}) { - const existing = await this.get(idOrShort); - if (!existing) - return null; - const limit = Math.min(Math.max(options.limit ?? 50, 1), 200); - const offset = Math.max(options.offset ?? 0, 0); - const totalRow = await this.client.get(`SELECT count(*)::text AS count FROM knowledge_item_versions WHERE item_id = $1`, [existing.id]); - const rows = await this.client.many(`SELECT * FROM knowledge_item_versions WHERE item_id = $1 - ORDER BY version DESC LIMIT ${limit} OFFSET ${offset}`, [existing.id]); - return { - item_id: existing.id, - current_version: existing.version ?? 1, - total: Number(totalRow?.count ?? 0), - items: rows.map(rowToVersion) - }; + return text.replace(HASNA_PATH_RE, (match) => `[REDACTED:hasna-path:${fingerprint(match)}]`).replace(RAW_DB_OR_ENV_RE, (match) => `[REDACTED:private-artifact:${fingerprint(match)}]`); +} +function redactPrivateRefs(value) { + if (typeof value === "string") + return redactString(value); + if (!value || typeof value !== "object") + return value; + if (Array.isArray(value)) + return value.map((entry) => redactPrivateRefs(entry)); + const output = {}; + for (const [key, entry] of Object.entries(value)) { + output[key] = OPAQUE_EXPORT_KEYS.has(key) ? entry : redactPrivateRefs(entry); } - async getVersion(idOrShort, version) { - const existing = await this.get(idOrShort); - if (!existing) - return null; - const row = await this.client.get(`SELECT * FROM knowledge_item_versions WHERE item_id = $1 AND version = $2`, [existing.id, version]); - return row ? rowToVersion(row) : null; + return output; +} + +// src/manifest-ingest.ts +var DEFAULT_MAX_MANIFEST_INPUT_BYTES = 20 * 1024 * 1024; +var DEFAULT_MAX_MANIFEST_ITEMS = 1e4; +var DEFAULT_MANIFEST_PREVIEW_ITEMS = 10; +function stableId(prefix, value) { + return `${prefix}_${createHash6("sha256").update(value).digest("hex").slice(0, 20)}`; +} +function asObject(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : undefined; +} +function asString(value) { + return typeof value === "string" && value.length > 0 ? value : undefined; +} +function asNumber(value) { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} +function buildSourceRefFromItem(item) { + const explicit = asString(item.source_ref) ?? asString(item.source_uri) ?? asString(item.uri); + if (explicit) + return explicit; + const fileId = asString(item.file_id); + if (fileId) { + const revision = asString(item.revision_id) ?? asString(item.revision); + const fileRef = `open-files://file/${encodeURIComponent(fileId)}`; + return revision ? `${fileRef}/revision/${encodeURIComponent(revision)}` : fileRef; } - async delete(idOrShort) { - const existing = await this.get(idOrShort); - if (!existing) - return false; - await this.client.execute(`DELETE FROM knowledge_items WHERE id = $1`, [existing.id]); - return true; + const sourceId = asString(item.source_id); + const path = asString(item.path); + if (sourceId && path) { + return `open-files://source/${encodeURIComponent(sourceId)}/path/${encodeURIComponent(path)}`; } + throw new Error("Manifest item is missing source_ref, file_id, or source_id/path."); } -function knowledgeOpenApi(version) { - const noteSchema = { - type: "object", - properties: { - id: { type: "string" }, - short_id: { type: "string", nullable: true }, - title: { type: "string" }, - content: { type: "string" }, - url: { type: "string", nullable: true }, - tags: { type: "array", items: { type: "string" } }, - metadata: { type: "object", additionalProperties: true }, - archived: { type: "boolean" }, - created_at: { type: "string" }, - updated_at: { type: "string" }, - version: { type: "integer", description: "Current entry version; send it back as If-Match to write safely." } - }, - required: ["id", "title", "content", "tags", "archived", "created_at", "updated_at", "version"] - }; - const noteVersionSchema = { - type: "object", - description: "An immutable snapshot of the entry as it stood BEFORE the edit that produced the next version.", - properties: { - id: { type: "string" }, - item_id: { type: "string" }, - tenant_id: { type: "string", nullable: true }, - version: { type: "integer" }, - title: { type: "string" }, - content: { type: "string", nullable: true }, - body_uri: { type: "string", nullable: true }, - content_hash: { type: "string" }, - content_bytes: { type: "integer" }, - url: { type: "string", nullable: true }, - tags: { type: "array", items: { type: "string" } }, - metadata: { type: "object", additionalProperties: true }, - archived: { type: "boolean" }, - actor: { type: "string", nullable: true }, - reason: { type: "string", nullable: true }, - valid_from: { type: "string", nullable: true }, - valid_to: { type: "string" } - }, - required: ["id", "item_id", "version", "title", "content_hash", "content_bytes", "tags", "archived", "valid_to"] - }; - const noteInput = { - type: "object", - properties: { - id: { type: "string" }, - title: { type: "string" }, - content: { type: "string" }, - url: { type: "string", nullable: true }, - tags: { type: "array", items: { type: "string" } }, - metadata: { type: "object", additionalProperties: true } - }, - required: ["title"] - }; - const notePatch = { - type: "object", - properties: { - title: { type: "string" }, - content: { type: "string" }, - url: { type: "string", nullable: true }, - tags: { type: "array", items: { type: "string" } }, - metadata: { type: "object", additionalProperties: true }, - archived: { type: "boolean" }, - expected_version: { - type: "integer", - description: "Optimistic concurrency guard, equivalent to the If-Match header, for clients that cannot set headers. " + "The write applies only if the stored entry is still at this version; otherwise 409 version_conflict." - } - } - }; - const versionConflict = { - type: "object", - properties: { - error: { type: "string", enum: ["version_conflict"] }, - expected: { type: "integer" }, - current: { type: "integer" } - }, - required: ["error", "expected", "current"] - }; - return { - openapi: "3.0.3", - info: { title: "Knowledge", version, description: "@hasna/knowledge self-hosted HTTP API" }, - components: { - securitySchemes: { apiKey: { type: "apiKey", in: "header", name: "x-api-key" } }, - schemas: { - Note: noteSchema, - NoteInput: noteInput, - NotePatch: notePatch, - NoteVersion: noteVersionSchema, - VersionConflict: versionConflict, - NoteList: { - type: "object", - properties: { - items: { type: "array", items: { $ref: "#/components/schemas/Note" } }, - total: { type: "integer" } - }, - required: ["items", "total"] - }, - NoteVersionList: { - type: "object", - properties: { - item_id: { type: "string" }, - current_version: { type: "integer" }, - total: { type: "integer" }, - items: { type: "array", items: { $ref: "#/components/schemas/NoteVersion" } } - }, - required: ["item_id", "current_version", "total", "items"] - } - } - }, - security: [{ apiKey: [] }], - paths: { - "/v1/notes": { - get: { - operationId: "listNotes", - summary: "List knowledge items", - parameters: [ - { name: "limit", in: "query", schema: { type: "integer" } }, - { name: "offset", in: "query", schema: { type: "integer" } }, - { name: "search", in: "query", schema: { type: "string" } } - ], - responses: { - "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/NoteList" } } } } - } - }, - post: { - operationId: "createNote", - summary: "Create a knowledge item", - requestBody: { - required: true, - content: { "application/json": { schema: { $ref: "#/components/schemas/NoteInput" } } } - }, - responses: { - "201": { content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } } } - } - } - }, - "/v1/notes/{id}": { - get: { - operationId: "getNote", - summary: "Fetch a knowledge item", - parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], - responses: { - "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } } } - } - }, - patch: { - operationId: "updateNote", - summary: "Update a knowledge item", - parameters: [ - { name: "id", in: "path", required: true, schema: { type: "string" } }, - { - name: "If-Match", - in: "header", - required: false, - schema: { type: "string" }, - description: "Optimistic concurrency guard: the version the client last read. The write applies only if the " + "stored entry is still at that version, otherwise 409 version_conflict. Optional in this phase so " + 'already-installed clients keep working; `*` means "any existing version".' - } - ], - requestBody: { - required: true, - content: { "application/json": { schema: { $ref: "#/components/schemas/NotePatch" } } } - }, - responses: { - "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } } }, - "409": { - description: "The stored entry moved on; nothing was written.", - content: { "application/json": { schema: { $ref: "#/components/schemas/VersionConflict" } } } - } - } - }, - delete: { - operationId: "deleteNote", - summary: "Delete a knowledge item", - parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], - responses: { "204": {} } - } - }, - "/v1/notes/{id}/versions": { - get: { - operationId: "listNoteVersions", - summary: "List prior versions of a knowledge item (newest first)", - parameters: [ - { name: "id", in: "path", required: true, schema: { type: "string" } }, - { name: "limit", in: "query", schema: { type: "integer" } }, - { name: "offset", in: "query", schema: { type: "integer" } } - ], - responses: { - "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/NoteVersionList" } } } }, - "404": { description: "No such entry. An entry that exists but was never edited returns 200 with an empty list." } - } - } - }, - "/v1/notes/{id}/versions/{version}": { - get: { - operationId: "getNoteVersion", - summary: "Fetch one prior version of a knowledge item", - parameters: [ - { name: "id", in: "path", required: true, schema: { type: "string" } }, - { name: "version", in: "path", required: true, schema: { type: "integer" } } - ], - responses: { - "200": { content: { "application/json": { schema: { $ref: "#/components/schemas/NoteVersion" } } } }, - "404": { description: "No such entry, or no such version of it." } - } - } - }, - "/v1/registry": { - get: { - operationId: "getRegistry", - summary: "Knowledge registry contract", - responses: { - "200": { content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } - } - } - } - } - }; +function baseSourceUri(sourceRef, parsed) { + if (parsed.kind === "open-files" && parsed.entity === "file" && parsed.revision_id) { + return sourceRef.replace(/\/revision\/[^/]+$/, ""); + } + return sourceRef; +} +function textFromItem(item) { + const direct = asString(item.extracted_text) ?? asString(item.text) ?? asString(item.content_text) ?? asString(item.markdown); + if (direct !== undefined) + return direct; + const content = item.content; + return typeof content === "string" ? content : null; +} +function extractedTextUriFromItem(item) { + const direct = asString(item.extracted_text_ref) ?? asString(item.extracted_text_uri) ?? asString(item.text_ref); + if (direct) + return direct; + const content = asObject(item.content); + return asString(content?.extracted_text_ref) ?? asString(content?.extracted_text_uri) ?? null; +} +function titleFromItem(item) { + const path = asString(item.path); + return asString(item.title) ?? asString(item.name) ?? (path ? basename2(path) : null); +} +function hashFromItem(item) { + return asString(item.hash) ?? asString(item.checksum) ?? asString(item.sha256) ?? null; +} +var OMIT_MANIFEST_METADATA_KEYS = new Set([ + "text", + "content", + "content_text", + "extracted_text", + "markdown", + "raw", + "raw_text", + "raw_bytes", + "raw_content", + "raw_body", + "raw_file", + "source_raw", + "source_raw_bytes", + "source_bytes", + "source_content", + "source_body", + "file_bytes", + "file_content", + "content_bytes", + "content_base64", + "document_bytes", + "document_content", + "document_base64", + "binary", + "binary_content", + "binary_base64", + "bytes", + "body", + "blob", + "data", + "payload" +]); +function normalizeMetadataKey(key) { + return key.toLowerCase().replace(/[\s-]+/g, "_"); } - -class HttpError extends Error { - status; - constructor(status, message) { - super(message); - this.status = status; +function sanitizeManifestMetadataValue(value) { + if (Array.isArray(value)) + return value.map((entry) => sanitizeManifestMetadataValue(entry)); + const object = asObject(value); + if (!object) + return value; + const sanitized = {}; + for (const [key, nestedValue] of Object.entries(object)) { + if (OMIT_MANIFEST_METADATA_KEYS.has(normalizeMetadataKey(key))) + continue; + sanitized[key] = sanitizeManifestMetadataValue(nestedValue); } + return sanitized; } -function json(body, status = 200) { - return new Response(JSON.stringify(body), { - status, - headers: { "content-type": "application/json" } - }); -} -function principalActor(principal) { - return principal.agent ? `agent:${principal.agent}` : `key:${principal.kid}`; +function revisionFromItem(item, parsed, hash) { + const revision = asString(item.revision_id) ?? asString(item.revision) ?? asString(item.version_id) ?? (parsed.kind === "open-files" ? parsed.revision_id : undefined) ?? hash ?? asString(item.updated_at); + return revision ?? "current"; } -function parseExpectedVersion(req, body) { - const header = req.headers.get("if-match"); - if (header != null && header.trim() !== "" && header.trim() !== "*") { - const cleaned = header.trim().replace(/^W\//i, "").replace(/^"(.*)"$/, "$1"); - const parsed2 = Number(cleaned); - if (!Number.isInteger(parsed2) || parsed2 < 1) { - throw new HttpError(400, `If-Match must be an entry version number (got ${header}).`); - } - return parsed2; - } - const fromBody = body.expected_version; - if (fromBody === undefined || fromBody === null) - return; - const parsed = Number(fromBody); - if (!Number.isInteger(parsed) || parsed < 1) { - throw new HttpError(400, "expected_version must be a positive integer entry version."); +function metadataFromItem(item, normalized) { + const metadata = {}; + for (const [key, value] of Object.entries(item)) { + if (OMIT_MANIFEST_METADATA_KEYS.has(normalizeMetadataKey(key))) + continue; + metadata[key] = redactPrivateRefs(sanitizeManifestMetadataValue(value)); } - return parsed; + metadata.source_ref = normalized.sourceRef; + metadata.source_uri = normalized.sourceUri; + metadata.status = normalized.status; + return metadata; } -function createServeHandler(deps) { - const repo = new NoteRepo(deps.client); - const mode2 = "cloud"; - const authOrThrow = async (req, requiredScopes) => { - const url = new URL(req.url); - const decision = await deps.verifier.authenticate(req.headers, { - method: req.method, - path: url.pathname, - requiredScopes - }); - if (decision.ok === false) { - throw new HttpError(decision.status, decision.message); - } - deps.store.touchLastUsed(decision.principal.kid).catch(() => {}); - return decision.principal; +function normalizeManifestItem(item, now, options = {}) { + const sourceRef = buildSourceRefFromItem(item); + assertNoPrivateRefs(sourceRef, { allowFileSourceRefs: options.allowFileSourceRefs === true }); + const parsed = parseSourceRef(sourceRef); + const sourceUri = baseSourceUri(sourceRef, parsed); + const hash = hashFromItem(item); + const status = asString(item.status) ?? "active"; + return { + raw: item, + sourceRef, + sourceUri, + kind: parsed.kind, + title: titleFromItem(item), + revision: revisionFromItem(item, parsed, hash), + hash, + extractedTextUri: extractedTextUriFromItem(item), + text: textFromItem(item), + metadata: metadataFromItem(item, { sourceRef, sourceUri, status }), + acl: item.permissions ?? item.acl ?? {}, + status, + updatedAt: asString(item.updated_at) ?? now }; - return async (req) => { - const url = new URL(req.url); - const path = url.pathname.replace(/\/+$/, "") || "/"; - const method = req.method.toUpperCase(); +} +function parseManifestText(text) { + const trimmed = text.trim(); + if (!trimmed) + return []; + if (trimmed.startsWith("[")) { + const parsed = JSON.parse(trimmed); + if (!Array.isArray(parsed)) + throw new Error("Manifest array parse failed."); + return parsed.map((entry) => { + const item = asObject(entry); + if (!item) + throw new Error("Manifest array entries must be objects."); + return item; + }); + } + if (trimmed.startsWith("{")) { try { - if (path === "/health" && method === "GET") { - return json({ status: "ok", version: deps.version, mode: mode2 }); - } - if (path === "/version" && method === "GET") { - return json({ status: "ok", version: deps.version, mode: mode2 }); - } - if (path === "/ready" && method === "GET") { - try { - await deps.client.query("SELECT 1"); - return json({ status: "ready", version: deps.version, mode: mode2 }); - } catch { - return json({ status: "unavailable", version: deps.version, mode: mode2 }, 503); - } - } - if (path === "/openapi.json" && method === "GET") { - return json(knowledgeOpenApi(deps.version)); - } - if (path === "/v1/registry" && method === "GET") { - await authOrThrow(req, ["knowledge:read"]); - return json(knowledgeRegistryContract({ - mode: "hosted", - sourceSchemes: ["open-files", "s3", "web", "file"], - storageType: "s3", - artifactUriPrefix: process.env.HASNA_KNOWLEDGE_S3_PREFIX ?? null - })); - } - if (path === "/v1/notes") { - if (method === "GET") { - await authOrThrow(req, ["knowledge:read"]); - const result = await repo.list({ - limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined, - offset: url.searchParams.has("offset") ? Number(url.searchParams.get("offset")) : undefined, - search: url.searchParams.get("search") ?? undefined, - includeArchived: url.searchParams.get("includeArchived") === "true" - }); - return json(result); - } - if (method === "POST") { - const principal = await authOrThrow(req, ["knowledge:write"]); - const body = await req.json().catch(() => ({})); - const item = await repo.create(body, { actor: principalActor(principal) }); - return json(item, 201); - } - return json({ error: "method_not_allowed" }, 405); - } - const versionListMatch = path.match(/^\/v1\/notes\/([^/]+)\/versions$/); - if (versionListMatch) { - if (method !== "GET") - return json({ error: "method_not_allowed" }, 405); - await authOrThrow(req, ["knowledge:read"]); - const history = await repo.listVersions(decodeURIComponent(versionListMatch[1]), { - limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined, - offset: url.searchParams.has("offset") ? Number(url.searchParams.get("offset")) : undefined + const parsed = JSON.parse(trimmed); + const object = asObject(parsed); + if (!object) + throw new Error("Manifest object parse failed."); + if (Array.isArray(object.items)) { + return object.items.map((entry) => { + const item = asObject(entry); + if (!item) + throw new Error("Manifest items entries must be objects."); + return item; }); - return history ? json(history) : json({ error: "not_found" }, 404); - } - const versionOneMatch = path.match(/^\/v1\/notes\/([^/]+)\/versions\/(\d+)$/); - if (versionOneMatch) { - if (method !== "GET") - return json({ error: "method_not_allowed" }, 405); - await authOrThrow(req, ["knowledge:read"]); - const snapshot = await repo.getVersion(decodeURIComponent(versionOneMatch[1]), Number(versionOneMatch[2])); - return snapshot ? json(snapshot) : json({ error: "not_found" }, 404); - } - const noteMatch = path.match(/^\/v1\/notes\/([^/]+)$/); - if (noteMatch) { - const id = decodeURIComponent(noteMatch[1]); - if (method === "GET") { - await authOrThrow(req, ["knowledge:read"]); - const item = await repo.get(id); - return item ? json(item) : json({ error: "not_found" }, 404); - } - if (method === "PATCH") { - const principal = await authOrThrow(req, ["knowledge:write"]); - const body = await req.json().catch(() => ({})); - const expectedVersion = parseExpectedVersion(req, body); - const { expected_version: _ignored, ...patch } = body; - try { - const item = await repo.update(id, patch, { - expectedVersion, - actor: principalActor(principal) - }); - return item ? json(item) : json({ error: "not_found" }, 404); - } catch (error) { - if (error instanceof VersionConflictError) { - return json({ error: "version_conflict", expected: error.expected, current: error.current }, 409); - } - throw error; - } - } - if (method === "DELETE") { - await authOrThrow(req, ["knowledge:write"]); - const ok = await repo.delete(id); - return ok ? new Response(null, { status: 204 }) : json({ error: "not_found" }, 404); - } - return json({ error: "method_not_allowed" }, 405); } - return json({ error: "not_found", path }, 404); + if ("source_ref" in object || "source_uri" in object || "file_id" in object) + return [object]; } catch (error) { - if (error instanceof HttpError) { - const reason = error.status === 401 || error.status === 403 ? "unauthorized" : "error"; - return json({ error: reason, message: error.message }, error.status); - } - const message = error instanceof Error ? error.message : "internal error"; - return json({ error: "internal", message }, 500); + const lines = trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0); + if (lines.length <= 1) + throw error; + return lines.map((line) => { + const item = asObject(JSON.parse(line)); + if (!item) + throw new Error("Manifest JSONL entries must be objects."); + return item; + }); } - }; + } + return trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => { + const item = asObject(JSON.parse(line)); + if (!item) + throw new Error("Manifest JSONL entries must be objects."); + return item; + }); } -async function startKnowledgeServe(options = {}) { - const env = options.env ?? process.env; - const port = options.port ?? Number(env.PORT ?? env.HASNA_KNOWLEDGE_SERVE_PORT ?? 8080); - const hostname = options.hostname ?? env.HOST ?? "0.0.0.0"; - const version = resolveVersion(); - normalizeCloudDatabaseUrl(env); - const client = createKnowledgeCloudClient(); - const store = new ApiKeyStore(client); - const verifier = verifyApiKey({ - app: KNOWLEDGE_SERVE_APP, - signingSecret: resolveSigningSecret(env), - isRevoked: store.isRevoked, - audit: (e) => { - if (e.outcome === "deny") { - console.warn(`[knowledge-serve] auth deny kid=${e.kid ?? "-"} reason=${e.reason} ${e.method} ${e.path}`); +async function readS3Text(uri, config, safetyPolicy) { + const parsed = new URL(uri); + const bucket = parsed.hostname; + const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); + if (!bucket || !key) + throw new Error(`Invalid S3 manifest URI: ${uri}`); + if (safetyPolicy) + assertS3ReadAllowed(uri, safetyPolicy); + const [{ S3Client, GetObjectCommand }, { fromIni }] = await Promise.all([ + import("@aws-sdk/client-s3"), + import("@aws-sdk/credential-providers") + ]); + const s3Config = config?.storage.type === "s3" && config.storage.s3?.bucket === bucket ? config.storage.s3 : undefined; + const client = new S3Client({ + region: s3Config?.region, + credentials: s3Config?.profile ? fromIni({ profile: s3Config.profile }) : undefined, + maxAttempts: s3Config?.max_attempts + }); + const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key })); + if (!response.Body) + return ""; + return await response.Body.transformToString(); +} +async function readManifestInput(input, config, safetyPolicy, maxInputBytes = DEFAULT_MAX_MANIFEST_INPUT_BYTES) { + const text = input.startsWith("s3://") ? await readS3Text(input, config, safetyPolicy) : (() => { + if (!existsSync6(input)) + throw new Error(`Manifest not found: ${input}`); + return readFileSync8(input, "utf8"); + })(); + const bytes = Buffer.byteLength(text); + if (bytes > maxInputBytes) { + throw new Error(`Manifest input is too large: ${bytes} bytes exceeds ${maxInputBytes} byte limit.`); + } + return text; +} +function chunkText(text, maxChars, overlapChars) { + const normalized = text.replace(/\r\n/g, ` +`); + if (!normalized.trim()) + return []; + const chunks = []; + let start = 0; + while (start < normalized.length) { + const hardEnd = Math.min(normalized.length, start + maxChars); + let end = hardEnd; + if (hardEnd < normalized.length) { + const paragraphBreak = normalized.lastIndexOf(` + +`, hardEnd); + const sentenceBreak = normalized.lastIndexOf(". ", hardEnd); + const candidate = Math.max(paragraphBreak, sentenceBreak); + if (candidate > start + Math.floor(maxChars * 0.5)) + end = candidate + (candidate === paragraphBreak ? 2 : 1); + } + const chunk = normalized.slice(start, end).trim(); + if (chunk) { + chunks.push({ + ordinal: chunks.length, + text: chunk, + startOffset: start, + endOffset: end + }); + } + if (end >= normalized.length) + break; + start = Math.max(0, end - overlapChars); + } + return chunks; +} +function estimateTokenCount(text) { + const words = text.trim().split(/\s+/).filter(Boolean).length; + return Math.max(1, Math.ceil(words * 1.25)); +} +function deleteChunksForRevision(db, sourceRevisionId) { + const rows = db.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(sourceRevisionId); + for (const row of rows) { + db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); + } + db.run("DELETE FROM chunks WHERE source_revision_id = ?", [sourceRevisionId]); + return rows.length; +} +function upsertSource(db, item, now) { + const sourceId = stableId("src", item.sourceUri); + db.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(uri) DO UPDATE SET + kind = excluded.kind, + title = excluded.title, + metadata_json = excluded.metadata_json, + acl_json = excluded.acl_json, + updated_at = excluded.updated_at`, [ + sourceId, + item.sourceUri, + item.kind, + item.title, + JSON.stringify(item.metadata), + JSON.stringify(item.acl ?? {}), + now, + item.updatedAt + ]); + const row = db.query("SELECT id FROM sources WHERE uri = ?").get(item.sourceUri); + if (!row) + throw new Error(`Failed to upsert source: ${item.sourceUri}`); + return row.id; +} +function upsertRevision(db, sourceId, item, now) { + const revisionId = stableId("rev", `${sourceId}\x00${item.revision}`); + db.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(source_id, revision) DO UPDATE SET + hash = excluded.hash, + extracted_text_uri = excluded.extracted_text_uri, + metadata_json = excluded.metadata_json`, [ + revisionId, + sourceId, + item.revision, + item.hash, + item.extractedTextUri, + JSON.stringify(item.metadata), + now + ]); + const row = db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(sourceId, item.revision); + if (!row) + throw new Error(`Failed to upsert source revision: ${item.sourceRef}`); + return row.id; +} +function insertChunks(db, sourceRevisionId, item, now, maxChars, overlapChars, safetyPolicy) { + if (!item.text || item.status.toLowerCase() === "deleted") + return { chunksInserted: 0, redactions: 0 }; + const redacted = redactSecrets(item.text, safetyPolicy); + if (redacted.findings.length > 0) { + recordRedactionFindings(db, { + source_uri: item.sourceUri, + findings: redacted.findings, + metadata: { source_ref: item.sourceRef, revision: item.revision }, + created_at: now + }); + recordAuditEvent(db, { + event_type: "redaction", + action: "source_text_redact", + target_uri: item.sourceUri, + decision: "redacted", + metadata: { findings: redacted.findings.length, source_ref: item.sourceRef, revision: item.revision }, + created_at: now + }); + } + const chunks = chunkText(redacted.text, maxChars, overlapChars); + for (const chunk of chunks) { + const chunkId = stableId("chk", `${sourceRevisionId}\x00${chunk.ordinal}\x00${chunk.text}`); + const provenance = sourceProvenance({ + source_ref: item.sourceRef, + source_uri: item.sourceUri, + source_kind: item.kind, + source_revision_id: sourceRevisionId, + revision: item.revision, + hash: item.hash, + chunk_id: chunkId, + start_offset: chunk.startOffset, + end_offset: chunk.endOffset, + status: item.status, + resolver: "open-files-read-only" + }); + const metadata = withProvenance({ + source_ref: item.sourceRef, + source_uri: item.sourceUri, + source_kind: item.kind, + source_revision_id: sourceRevisionId, + revision: item.revision, + hash: item.hash, + status: item.status, + path: asString(item.raw.path) ?? null, + mime: asString(item.raw.mime) ?? asString(item.raw.content_type) ?? null, + size: asNumber(item.raw.size) ?? null + }, provenance); + db.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + chunkId, + sourceRevisionId, + "source", + chunk.ordinal, + chunk.text, + estimateTokenCount(chunk.text), + chunk.startOffset, + chunk.endOffset, + JSON.stringify(metadata), + now + ]); + db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [chunkId, chunk.text, item.title ?? "", item.sourceUri]); + } + return { chunksInserted: chunks.length, redactions: redacted.findings.length }; +} +async function ingestOpenFilesManifest(options) { + const now = options.now ?? new Date; + if (options.safetyPolicy) + assertWriteAllowed(options.dbPath, options.safetyPolicy); + migrateKnowledgeDb(options.dbPath); + const text = await readManifestInput(options.input, options.config, options.safetyPolicy, options.maxInputBytes); + const items = parseManifestText(text); + const maxItems = options.maxItems ?? DEFAULT_MAX_MANIFEST_ITEMS; + if (items.length > maxItems) { + throw new Error(`Manifest contains too many items: ${items.length} exceeds ${maxItems} item limit.`); + } + return ingestOpenFilesManifestItems({ + dbPath: options.dbPath, + items, + sourceLabel: options.input, + allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") === true, + safetyPolicy: options.safetyPolicy, + now, + maxChunkChars: options.maxChunkChars, + chunkOverlapChars: options.chunkOverlapChars, + maxItems: options.maxItems + }); +} +async function ingestOpenFilesManifestItems(options) { + const now = (options.now ?? new Date).toISOString(); + const maxChunkChars = options.maxChunkChars ?? 4000; + const chunkOverlapChars = options.chunkOverlapChars ?? 200; + const maxItems = options.maxItems ?? DEFAULT_MAX_MANIFEST_ITEMS; + if (maxChunkChars < 500) + throw new Error("maxChunkChars must be at least 500."); + if (chunkOverlapChars < 0 || chunkOverlapChars >= maxChunkChars) + throw new Error("chunkOverlapChars must be less than maxChunkChars."); + if (options.items.length > maxItems) { + throw new Error(`Manifest contains too many items: ${options.items.length} exceeds ${maxItems} item limit.`); + } + if (options.safetyPolicy) + assertWriteAllowed(options.dbPath, options.safetyPolicy); + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + try { + const result = db.transaction(() => { + const seenSources = new Set; + const seenRevisions = new Set; + let chunksInserted = 0; + let chunksDeleted = 0; + let redactions = 0; + let skipped = 0; + const preview2 = []; + recordAuditEvent(db, { + event_type: "source_read", + action: options.readAction ?? (options.sourceLabel.startsWith("s3://") ? "s3_manifest_read" : "local_manifest_read"), + target_uri: options.sourceLabel, + decision: "allow", + metadata: { items: options.items.length, read_only: true }, + created_at: now + }); + for (const raw of options.items) { + const item = normalizeManifestItem(raw, now, { allowFileSourceRefs: options.allowFileSourceRefs }); + if (preview2.length < DEFAULT_MANIFEST_PREVIEW_ITEMS) { + preview2.push({ + source_ref: item.sourceRef, + title: item.title, + status: item.status, + has_text: Boolean(item.text) + }); + } + const sourceId = upsertSource(db, item, now); + const revisionId = upsertRevision(db, sourceId, item, now); + seenSources.add(sourceId); + seenRevisions.add(revisionId); + if (item.text || item.status.toLowerCase() === "deleted") { + chunksDeleted += deleteChunksForRevision(db, revisionId); + } + const inserted = insertChunks(db, revisionId, item, now, maxChunkChars, chunkOverlapChars, options.safetyPolicy); + chunksInserted += inserted.chunksInserted; + redactions += inserted.redactions; } - } - }); - const handler = createServeHandler({ client, verifier, store, version }); - const BunGlobal = globalThis.Bun; - if (!BunGlobal?.serve) { - throw new Error("knowledge-serve requires the Bun runtime (Bun.serve unavailable)."); + recordAuditEvent(db, { + event_type: "write", + action: "knowledge_manifest_ingest", + target_uri: options.dbPath, + decision: "allow", + metadata: { items: options.items.length, sources: seenSources.size, revisions: seenRevisions.size, chunks_inserted: chunksInserted, redactions }, + created_at: now + }); + return { + path: options.sourceLabel, + db_path: options.dbPath, + items_seen: options.items.length, + sources_upserted: seenSources.size, + revisions_upserted: seenRevisions.size, + chunks_inserted: chunksInserted, + chunks_deleted: chunksDeleted, + redactions, + skipped, + items_preview: preview2 + }; + })(); + return result; + } finally { + db.close(); } - const server = BunGlobal.serve({ port, hostname, fetch: handler }); - console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=cloud, version=${version})`); - return { - port: server.port, - hostname, - stop: async () => { - server.stop(); - await client.close(); - } - }; } -// src/artifact-store.ts -import { chmodSync as chmodSync3, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, statSync, writeFileSync as writeFileSync3 } from "fs"; -import { dirname as dirname3, join as join3, relative, sep } from "path"; -import { pathToFileURL } from "url"; -function normalizeArtifactKey(key) { - const raw = key.replace(/\\/g, "/").trim(); - if (!raw || raw.startsWith("/")) { - throw new Error(`Invalid artifact key: ${key}`); - } - const segments = raw.split("/").filter(Boolean); - if (segments.length === 0 || segments.some((segment) => segment === "." || segment === "..")) { - throw new Error(`Invalid artifact key: ${key}`); +// src/source-resolver.ts +function parseJsonObject(value) { + if (!value) + return {}; + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; } - return segments.join("/"); } -function assertInside(root, target) { - const rel = relative(root, target); - if (rel.startsWith("..") || rel === ".." || rel.startsWith(`..${sep}`)) { - throw new Error(`Artifact path escapes root: ${target}`); +function metadataString(metadata, keys) { + for (const key of keys) { + const value = metadata[key]; + if (typeof value === "string" && value.length > 0) + return value; } + return null; } -function s3UserMetadata(metadata) { - if (!metadata) - return; - const output = {}; - for (const [key, value] of Object.entries(metadata)) { - if (typeof value === "string") - output[key] = value; - else if (typeof value === "number" || typeof value === "boolean") - output[key] = String(value); +function metadataNumber(metadata, keys) { + for (const key of keys) { + const value = metadata[key]; + if (typeof value === "number" && Number.isFinite(value)) + return value; } - return Object.keys(output).length > 0 ? output : undefined; + return null; } - -class LocalArtifactStore { - root; - type = "local"; - canRead = true; - canWrite = true; - constructor(root) { - this.root = root; - mkdirSync2(root, { recursive: true, mode: 448 }); - } - async put(entry) { - const key = normalizeArtifactKey(entry.key); - const path = join3(this.root, key); - assertInside(this.root, path); - mkdirSync2(dirname3(path), { recursive: true, mode: 448 }); - writeFileSync3(path, entry.body, { mode: 384 }); - chmodSync3(path, 384); - return { key, uri: pathToFileURL(path).href, modified_at: statSync(path).mtime.toISOString() }; +function assertPurposeAllowed(permissions, purpose) { + const mode2 = permissions.mode; + if (typeof mode2 === "string" && mode2 !== "read_only") { + throw new Error(`Source resolver denied ${purpose}. Permission mode is ${mode2}, expected read_only.`); } - async getText(key) { - const normalizedKey = normalizeArtifactKey(key); - const path = join3(this.root, normalizedKey); - assertInside(this.root, path); - return readFileSync5(path, "utf8"); + const denied = permissions.denied_purposes; + if (Array.isArray(denied) && denied.includes(purpose)) { + throw new Error(`Source resolver denied ${purpose}. Purpose is explicitly denied.`); } - async exists(key) { - const normalizedKey = normalizeArtifactKey(key); - const path = join3(this.root, normalizedKey); - assertInside(this.root, path); - return existsSync3(path); + const allowed = permissions.allowed_purposes; + if (Array.isArray(allowed) && allowed.length > 0 && !allowed.includes(purpose)) { + throw new Error(`Source resolver denied ${purpose}. Allowed purposes: ${allowed.join(", ")}`); } } - -class S3ArtifactStore { - options; - type = "s3"; - canRead = true; - canWrite = true; - client; - constructor(options) { - this.options = options; - this.client = options.client; - } - async getClient() { - if (this.client) - return this.client; - const [{ S3Client }, { fromIni }] = await Promise.all([ - import("@aws-sdk/client-s3"), - import("@aws-sdk/credential-providers") - ]); - this.client = new S3Client({ - region: this.options.region, - credentials: this.options.profile ? fromIni({ profile: this.options.profile }) : undefined, - maxAttempts: this.options.max_attempts - }); - return this.client; - } - objectKey(key) { - const normalizedKey = normalizeArtifactKey(key); - const prefix = this.options.prefix ? normalizeArtifactKey(this.options.prefix) : ""; - return prefix ? `${prefix}/${normalizedKey}` : normalizedKey; - } - async put(entry) { - const [{ PutObjectCommand }, client] = await Promise.all([ - import("@aws-sdk/client-s3"), - this.getClient() - ]); - const logicalKey = normalizeArtifactKey(entry.key); - const key = this.objectKey(logicalKey); - await client.send(new PutObjectCommand({ - Bucket: this.options.bucket, - Key: key, - Body: entry.body, - ContentType: entry.content_type, - Metadata: s3UserMetadata(entry.metadata), - ServerSideEncryption: this.options.server_side_encryption, - SSEKMSKeyId: this.options.kms_key_id - })); - return { key: logicalKey, uri: `s3://${this.options.bucket}/${key}`, modified_at: new Date().toISOString() }; - } - async getText(key) { - const [{ GetObjectCommand }, client] = await Promise.all([ - import("@aws-sdk/client-s3"), - this.getClient() - ]); - const objectKey = this.objectKey(key); - const response = await client.send(new GetObjectCommand({ - Bucket: this.options.bucket, - Key: objectKey - })); - if (!response.Body) - return ""; - return await response.Body.transformToString(); - } - async exists(key) { - const [{ HeadObjectCommand }, client] = await Promise.all([ - import("@aws-sdk/client-s3"), - this.getClient() - ]); - const objectKey = this.objectKey(key); - try { - await client.send(new HeadObjectCommand({ - Bucket: this.options.bucket, - Key: objectKey - })); - return true; - } catch (error) { - const name = error instanceof Error ? error.name : ""; - if (name === "NotFound" || name === "NoSuchKey" || name === "NotFoundError") - return false; - throw error; +function sourceRevisionRef(sourceUri, revision, fallback) { + if (!revision) + return fallback; + try { + const parsed = parseSourceRef(sourceUri); + if (parsed.kind === "open-files" && parsed.entity === "file") { + return `${sourceUri}/revision/${encodeURIComponent(revision.revision)}`; } + } catch { + return fallback; } + return fallback; } -function createArtifactStore(config, workspace) { - if (config.storage.type === "s3") { - if (!config.storage.s3?.bucket) - throw new Error("S3 artifact storage requires storage.s3.bucket"); - return new S3ArtifactStore({ - bucket: config.storage.s3.bucket, - prefix: config.storage.s3.prefix, - region: config.storage.s3.region, - profile: config.storage.s3.profile, - max_attempts: config.storage.s3.max_attempts, - server_side_encryption: config.storage.s3.server_side_encryption, - kms_key_id: config.storage.s3.kms_key_id - }); - } - return new LocalArtifactStore(workspace.artifactsDir); +function selectSource(db, sourceUri, requestedRef) { + return db.query(`SELECT id, uri, kind, title, metadata_json, acl_json, updated_at + FROM sources + WHERE uri = ? OR uri = ? + ORDER BY CASE WHEN uri = ? THEN 0 ELSE 1 END + LIMIT 1`).get(sourceUri, requestedRef, sourceUri) ?? null; } - -// src/service.ts -import { createHash as createHash21 } from "crypto"; -import { spawnSync as spawnSync2 } from "child_process"; -import { existsSync as existsSync14, readFileSync as readFileSync14 } from "fs"; -import { hostname as hostname5 } from "os"; -import { join as join8, resolve as resolve5 } from "path"; - -// src/app-wiki.ts -import { createHash as createHash8, randomUUID as randomUUID4 } from "crypto"; - -// src/storage-contract.ts -import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto"; -import { existsSync as existsSync5, readdirSync } from "fs"; -import { join as join5 } from "path"; -import { pathToFileURL as pathToFileURL2 } from "url"; - -// src/auth.ts -import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs"; -import { homedir as homedir2 } from "os"; -import { dirname as dirname4, join as join4 } from "path"; -var DEFAULT_KNOWLEDGE_API_URL = "https://knowledge.md"; -function normalizeKnowledgeApiOrigin(apiUrl) { - const url = new URL(apiUrl); - if (url.protocol !== "http:" && url.protocol !== "https:") { - throw new Error("Knowledge API URL must use http or https."); - } - const pathname = url.pathname.replace(/\/+$/, ""); - if (pathname === "/api" || pathname === "/api/v1") { - url.pathname = "/"; - } else if (pathname.endsWith("/api/v1")) { - url.pathname = pathname.slice(0, -"/api/v1".length) || "/"; - } else if (pathname.endsWith("/api")) { - url.pathname = pathname.slice(0, -"/api".length) || "/"; +function selectRevision(db, sourceId, revisionId) { + if (revisionId) { + return db.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at + FROM source_revisions + WHERE source_id = ? AND revision = ? + LIMIT 1`).get(sourceId, revisionId) ?? null; } - return url.toString().replace(/\/+$/, ""); + return db.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at + FROM source_revisions + WHERE source_id = ? + ORDER BY created_at DESC, revision DESC + LIMIT 1`).get(sourceId) ?? null; } -function knowledgeAuthPath(env = process.env) { - if (env.HASNA_KNOWLEDGE_AUTH_PATH) - return env.HASNA_KNOWLEDGE_AUTH_PATH; - const root = env.HASNA_KNOWLEDGE_AUTH_DIR ?? join4(homedir2(), ".hasna", "knowledge"); - return join4(root, "auth.json"); +function countChunks(db, revisionId) { + if (!revisionId) + return 0; + const row = db.query("SELECT COUNT(*) AS n FROM chunks WHERE source_revision_id = ?").get(revisionId); + return row?.n ?? 0; } -function resolveKnowledgeApiUrl(config, env = process.env) { - return normalizeKnowledgeApiOrigin(env.KNOWLEDGE_API_URL ?? config?.hosted?.api_url ?? DEFAULT_KNOWLEDGE_API_URL); +function selectChunks(db, revisionId, limit) { + if (!revisionId || limit <= 0) + return []; + return db.query(`SELECT id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json + FROM chunks + WHERE source_revision_id = ? + ORDER BY ordinal ASC + LIMIT ?`).all(revisionId, limit); } -function getKnowledgeAuth(env = process.env) { - try { - const path = knowledgeAuthPath(env); - if (!existsSync4(path)) - return null; - const parsed = JSON.parse(readFileSync6(path, "utf8")); - return typeof parsed.api_key === "string" && parsed.api_key.length > 0 ? parsed : null; - } catch { - return null; +async function resolveOpenFilesSource(options) { + const purpose = options.purpose ?? "knowledge_answer"; + const limit = Math.max(0, Math.min(options.limit ?? 10, 100)); + const resolvedAt = (options.now ?? new Date).toISOString(); + const parsed = parseSourceRef(options.sourceRef); + const sourceUri = catalogSourceUriForRef(options.sourceRef, parsed); + const requestedRevision = revisionIdForSourceRef(options.sourceRef); + if (options.safetyPolicy) { + if (!options.safetyPolicy.readOnlySourceAccess) + throw new Error("Safety policy denied source resolution."); + assertWriteAllowed(options.dbPath, options.safetyPolicy); } -} -function saveKnowledgeAuth(auth, env = process.env) { - const path = knowledgeAuthPath(env); - const stored = { - ...auth, - api_url: auth.api_url ? normalizeKnowledgeApiOrigin(auth.api_url) : undefined, - created_at: auth.created_at ?? new Date().toISOString() - }; - mkdirSync3(dirname4(path), { recursive: true, mode: 448 }); - writeFileSync4(path, `${JSON.stringify(stored, null, 2)} -`, { mode: 384 }); - return stored; -} -function clearKnowledgeAuth(env = process.env) { + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); try { - unlinkSync2(knowledgeAuthPath(env)); - return true; - } catch { - return false; + return db.transaction(() => { + const source = selectSource(db, sourceUri, options.sourceRef); + if (!source) { + recordAuditEvent(db, { + event_type: "source_read", + action: "open_files_resolve_missing", + target_uri: options.sourceRef, + decision: "allow", + metadata: { purpose, read_only: true, source_uri: sourceUri }, + created_at: resolvedAt + }); + return { + source_ref: options.sourceRef, + source_uri: sourceUri, + purpose, + read_only: true, + resolved: false, + resolver: { + name: "open-files-read-only", + mode: "local_catalog", + contract: "open-files-knowledge-source-v1" + }, + source: null, + revision: null, + content: { + mime: null, + size: null, + hash: null, + text_available: false, + chunks_total: 0, + chunks_returned: 0, + char_count_returned: 0, + extracted_text_ref: null, + bytes_available: false, + bytes_exposed: false + }, + chunks: [], + citations: [] + }; + } + const sourceMetadata = parseJsonObject(source.metadata_json); + const permissions = parseJsonObject(source.acl_json); + try { + assertPurposeAllowed(permissions, purpose); + } catch (error) { + recordAuditEvent(db, { + event_type: "source_read", + action: "open_files_resolve", + target_uri: options.sourceRef, + decision: "deny", + metadata: { + purpose, + read_only: true, + source_uri: source.uri, + error: error instanceof Error ? error.message : String(error) + }, + created_at: resolvedAt + }); + throw error; + } + const revision = selectRevision(db, source.id, requestedRevision); + const revisionMetadata = parseJsonObject(revision?.metadata_json); + const totalChunks = countChunks(db, revision?.id ?? null); + const rows = selectChunks(db, revision?.id ?? null, limit); + const effectiveSourceRef = sourceRevisionRef(source.uri, revision, options.sourceRef); + const chunks = rows.map((row) => { + const metadata = parseJsonObject(row.metadata_json); + const evidence = { + resolver: "open-files-read-only", + mode: "local_catalog", + purpose, + read_only: true, + source_ref: metadataString(metadata, ["source_ref"]) ?? effectiveSourceRef, + source_uri: source.uri, + source_revision_id: revision?.id ?? null, + revision: revision?.revision ?? null, + hash: revision?.hash ?? metadataString(metadata, ["hash"]), + chunk_id: row.id, + start_offset: row.start_offset, + end_offset: row.end_offset, + resolved_at: resolvedAt + }; + const provenance = sourceProvenance({ + source_ref: evidence.source_ref, + source_uri: evidence.source_uri, + source_kind: source.kind, + source_revision_id: evidence.source_revision_id, + revision: evidence.revision, + hash: evidence.hash, + chunk_id: row.id, + start_offset: row.start_offset, + end_offset: row.end_offset, + status: metadataString(metadata, ["status"]), + resolver: evidence.resolver + }); + return { + id: row.id, + kind: row.kind, + ordinal: row.ordinal, + text: row.text, + token_count: row.token_count, + start_offset: row.start_offset, + end_offset: row.end_offset, + metadata, + evidence, + provenance + }; + }); + const citations = chunks.map((chunk) => ({ + source_ref: chunk.evidence.source_ref, + source_uri: source.uri, + chunk_id: chunk.id, + quote: chunk.text.slice(0, 500), + start_offset: chunk.start_offset, + end_offset: chunk.end_offset, + evidence: chunk.evidence, + provenance: chunk.provenance + })); + recordAuditEvent(db, { + event_type: "source_read", + action: "open_files_resolve", + target_uri: options.sourceRef, + decision: "allow", + metadata: { + purpose, + read_only: true, + source_uri: source.uri, + revision: revision?.revision ?? null, + chunks_returned: chunks.length, + chunks_total: totalChunks + }, + created_at: resolvedAt + }); + const mime = metadataString(sourceMetadata, ["mime", "content_type"]) ?? metadataString(revisionMetadata, ["mime", "content_type"]); + const size = metadataNumber(sourceMetadata, ["size", "size_bytes"]) ?? metadataNumber(revisionMetadata, ["size", "size_bytes"]); + return { + source_ref: effectiveSourceRef, + source_uri: source.uri, + purpose, + read_only: true, + resolved: true, + resolver: { + name: "open-files-read-only", + mode: "local_catalog", + contract: "open-files-knowledge-source-v1" + }, + source: { + id: source.id, + uri: source.uri, + kind: source.kind, + title: source.title, + metadata: sourceMetadata, + permissions, + updated_at: source.updated_at + }, + revision: revision ? { + id: revision.id, + revision: revision.revision, + hash: revision.hash, + extracted_text_uri: revision.extracted_text_uri, + metadata: revisionMetadata, + created_at: revision.created_at, + reindex_required: revisionMetadata.reindex_required === true + } : null, + content: { + mime, + size, + hash: revision?.hash ?? metadataString(sourceMetadata, ["hash", "checksum", "sha256"]), + text_available: totalChunks > 0, + chunks_total: totalChunks, + chunks_returned: chunks.length, + char_count_returned: chunks.reduce((sum, chunk) => sum + chunk.text.length, 0), + extracted_text_ref: revision?.extracted_text_uri ?? metadataString(revisionMetadata, ["extracted_text_ref", "extracted_text_uri"]), + bytes_available: false, + bytes_exposed: false + }, + chunks, + citations + }; + })(); + } finally { + db.close(); } } -function getKnowledgeApiKey(env = process.env) { - if (env.KNOWLEDGE_API_KEY) - return { apiKey: env.KNOWLEDGE_API_KEY, source: "env" }; - if (env.HASNA_KNOWLEDGE_API_KEY) - return { apiKey: env.HASNA_KNOWLEDGE_API_KEY, source: "env" }; - const auth = getKnowledgeAuth(env); - return auth?.api_key ? { apiKey: auth.api_key, source: "file" } : { apiKey: null, source: "none" }; -} -function knowledgeAuthStatus(config, env = process.env) { - const auth = getKnowledgeAuth(env); - const key = getKnowledgeApiKey(env); - const apiUrl = env.KNOWLEDGE_API_URL ? resolveKnowledgeApiUrl(config, env) : auth?.api_url ? normalizeKnowledgeApiOrigin(auth.api_url) : resolveKnowledgeApiUrl(config, env); - return { - authenticated: Boolean(key.apiKey), - source: key.source, - api_url: apiUrl, - auth_path: knowledgeAuthPath(env), - email: key.source === "file" ? auth?.email ?? null : null, - org_id: key.source === "file" ? auth?.org_id ?? null : null, - org_slug: key.source === "file" ? auth?.org_slug ?? null : null, - user_id: key.source === "file" ? auth?.user_id ?? null : null, - api_key_present: Boolean(key.apiKey) - }; -} -// src/storage-contract.ts -var GENERATED_ARTIFACTS = [ - { - kind: "schema", - prefix: "schemas/", - description: "Machine-readable agent schemas and source rules." - }, - { - kind: "index", - prefix: "indexes/", - description: "Small orientation indexes and future shard manifests." - }, - { - kind: "log", - prefix: "logs/", - description: "Append-only JSONL run and wiki-maintenance log partitions." - }, - { - kind: "run", - prefix: "runs/", - description: "Prompt/tool/cost ledgers and generated output records." - }, - { - kind: "wiki_page", - prefix: "wiki/", - description: "Generated cited Markdown pages, not raw source files." - }, - { - kind: "export", - prefix: "exports/", - description: "Portable exports and snapshots of derived knowledge state." - } -]; -var FORBIDDEN_WORKSPACE_FILES = [ - "cloud.env", - "knowledge.db.pre-cloud-*.bak", - "db.json.pre-cloud-*.bak", - "migration-exports" -]; -function forbiddenWorkspaceFilesPresent(workspace) { - const present = []; - if (existsSync5(join5(workspace.home, "cloud.env"))) - present.push("cloud.env"); - if (existsSync5(join5(workspace.home, "migration-exports"))) - present.push("migration-exports"); - if (existsSync5(workspace.home)) { - for (const entry of readdirSync(workspace.home)) { - if (/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(entry)) - present.push(entry); - } - } - return present; +// src/source-ingest.ts +function sha256Text(text) { + return `sha256:${createHash7("sha256").update(text).digest("hex")}`; } -function hashArtifactBody(body) { - const bytes = typeof body === "string" ? Buffer.from(body) : Buffer.from(body); - return { - hash: `sha256:${createHash3("sha256").update(bytes).digest("hex")}`, - size_bytes: bytes.byteLength - }; +function stripHtml(html) { + return html.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\s+\n/g, ` +`).replace(/\n\s+/g, ` +`).replace(/[ \t]{2,}/g, " ").trim(); } -function artifactKindForKey(key) { - const match = GENERATED_ARTIFACTS.find((entry) => key.startsWith(entry.prefix)); - return match?.kind ?? "artifact"; +async function readS3Text2(uri, config, safetyPolicy) { + const parsed = new URL(uri); + const bucket = parsed.hostname; + const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); + if (!bucket || !key) + throw new Error(`Invalid S3 source URI: ${uri}`); + if (safetyPolicy) + assertS3ReadAllowed(uri, safetyPolicy); + const [{ S3Client, GetObjectCommand }, { fromIni }] = await Promise.all([ + import("@aws-sdk/client-s3"), + import("@aws-sdk/credential-providers") + ]); + const s3Config = config?.storage.type === "s3" && config.storage.s3?.bucket === bucket ? config.storage.s3 : undefined; + const client = new S3Client({ + region: s3Config?.region, + credentials: s3Config?.profile ? fromIni({ profile: s3Config.profile }) : undefined, + maxAttempts: s3Config?.max_attempts + }); + const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key })); + if (!response.Body) + return ""; + return await response.Body.transformToString(); } -function resolveStorageContract(config, workspace, scope = "global") { - const validation = validateStorageConfig(config, workspace); - const s3 = config.storage.s3 ?? null; - const prefix = s3?.prefix?.replace(/^\/+|\/+$/g, "") ?? ""; - const s3UriPrefix = s3 ? `s3://${s3.bucket}/${prefix ? `${prefix}/` : ""}` : ""; - const canonicalPrefix = EXAMPLE_KNOWLEDGE_CANONICAL.s3.prefix.replace(/^\/+|\/+$/g, ""); - const canonicalS3UriPrefix = `s3://${EXAMPLE_KNOWLEDGE_CANONICAL.s3.bucket}/${canonicalPrefix}/`; - const canonicalActive = config.storage.type === "s3" && s3?.bucket === EXAMPLE_KNOWLEDGE_CANONICAL.s3.bucket && (s3.region ?? null) === EXAMPLE_KNOWLEDGE_CANONICAL.s3.region; - return { - scope, - mode: config.mode, - storage_type: config.storage.type, - workspace_home: workspace.home, - local_layout: { - app_path: HASNA_KNOWLEDGE_APP_PATH, - config_path: workspace.configPath, - json_store_path: workspace.jsonStorePath, - knowledge_db_path: workspace.knowledgeDbPath, - directories: { - artifacts: workspace.artifactsDir, - cache: workspace.cacheDir, - exports: workspace.exportsDir, - indexes: workspace.indexesDir, - logs: workspace.logsDir, - runs: workspace.runsDir, - schemas: workspace.schemasDir, - wiki: workspace.wikiDir - } - }, - artifact_store: { - type: config.storage.type, - artifacts_root: config.storage.artifacts_root, - uri_prefix: config.storage.type === "s3" ? s3UriPrefix : pathToFileURL2(`${workspace.artifactsDir}/`).href, - s3: s3 ? { - bucket: s3.bucket, - prefix, - region: s3.region ?? null, - profile: s3.profile ?? null, - server_side_encryption: s3.server_side_encryption ?? null, - kms_key_configured: Boolean(s3.kms_key_id) - } : null - }, - canonical_example: { - division: EXAMPLE_KNOWLEDGE_CANONICAL.division, - app_type: EXAMPLE_KNOWLEDGE_CANONICAL.app_type, - app: EXAMPLE_KNOWLEDGE_CANONICAL.app, - env: EXAMPLE_KNOWLEDGE_CANONICAL.env, - active: canonicalActive, - local_path: EXAMPLE_KNOWLEDGE_CANONICAL.local_path, - s3: { - bucket: EXAMPLE_KNOWLEDGE_CANONICAL.s3.bucket, - region: EXAMPLE_KNOWLEDGE_CANONICAL.s3.region, - profile: EXAMPLE_KNOWLEDGE_CANONICAL.s3.profile, - prefix: canonicalPrefix, - uri_prefix: canonicalS3UriPrefix, - server_side_encryption: EXAMPLE_KNOWLEDGE_CANONICAL.s3.server_side_encryption - }, - secrets: { - env: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.env, - aws: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.aws, - s3: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.s3, - rds: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.rds, - future_rds: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.future_rds - }, - evidence_doc: EXAMPLE_KNOWLEDGE_CANONICAL.evidence_doc - }, - hosted: { - enabled: config.mode === "hosted", - api_url: normalizeKnowledgeApiOrigin(config.hosted?.api_url ?? DEFAULT_KNOWLEDGE_API_URL), - api_url_env: "KNOWLEDGE_API_URL", - api_key_env: "KNOWLEDGE_API_KEY", - auth_storage: "~/.hasna/knowledge/auth.json", - registry_contract_version: KNOWLEDGE_REGISTRY_CONTRACT_VERSION, - requires_hosted_account_for_local_use: false - }, - secret_handling: { - workspace_env_files_supported: false, - forbidden_workspace_files: FORBIDDEN_WORKSPACE_FILES, - forbidden_workspace_files_present: forbiddenWorkspaceFilesPresent(workspace), - runtime_env_keys: [ - "HASNA_KNOWLEDGE_STORAGE_MODE", - "KNOWLEDGE_STORAGE_MODE", - "HASNA_KNOWLEDGE_DATABASE_URL", - "KNOWLEDGE_DATABASE_URL" - ], - secret_ref_authority: "open-secrets", - approved_secret_refs: { - env: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.env, - aws: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.aws, - s3: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.s3, - rds: EXAMPLE_KNOWLEDGE_CANONICAL.secrets.rds - }, - db_url_rotation_decision: { - status: "blocked_without_secret_authority", - reason: "No live secret mutation authority is available in @hasna/knowledge. Rotate the DB URL only through the approved secret authority if separate evidence proves the URL propagated to backups, exports, sync bundles, reports, or copied artifacts.", - authority_required: true - } - }, - source_ownership: { - owner: "open-files", - preferred_ref: config.sources.preferred_ref, - allowed_schemes: config.sources.allowed_schemes, - raw_source_bytes_stored_in_open_knowledge: false, - stores: [ - "source refs", - "source revisions and hashes", - "citation spans", - "redacted extracted chunks", - "embeddings", - "generated wiki artifacts", - "indexes", - "run ledgers" - ], - does_not_store: [ - "raw open-files bytes", - "S3 object credentials", - "connector secrets", - "hosted tenant ownership state" - ] - }, - private_fleet_boundary: { - manifest_authority: "open-machines", - source_ref_authority: "open-files", - secret_ref_authority: "open-secrets", - raw_private_manifest_bytes_stored_in_open_knowledge: false, - accepted_source_ref_schemes: config.sources.allowed_schemes.filter((scheme) => ["open-files", "s3", "file"].includes(scheme)), - stores: [ - "source refs for private manifests", - "redacted setup decisions", - "runbook summaries", - "citation spans into approved knowledge sources", - "machine setup evidence hashes" - ], - does_not_store: [ - "private fleet manifests", - "machine hostnames", - "machine serial numbers", - "sudo passwords", - "VNC passwords", - "SSH private keys", - "GitHub App private keys", - "secret values" - ], - example_manifest_ref: "open-files://source/private-fleet-manifest/path/machines.json" - }, - generated_artifacts: GENERATED_ARTIFACTS, - scalability: { - catalog: "knowledge.db tracks sources, revisions, chunks, citations, indexes, runs, and storage_objects.", - indexes: "Indexes are cataloged DB rows plus sharded artifacts, not one giant index.md.", - logs: "Logs use dated JSONL partitions under logs/yyyy/mm/dd.jsonl.", - markdown: "Markdown pages are the readable wiki layer over DB/object-store state." - }, - warnings: validation.warnings - }; +async function readWebText(uri, safetyPolicy) { + if (safetyPolicy) + assertWebSearchAllowed(safetyPolicy); + const response = await guardedFetch(uri, { + headers: { + accept: "text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5", + "user-agent": "@hasna/knowledge source-ingest" + } + }); + if (!response.ok) + throw new Error(`Web source read failed ${response.status}: ${uri}`); + const mime = response.headers.get("content-type"); + const body = await response.text(); + return { text: mime?.includes("html") ? stripHtml(body) : body, mime }; } -function validateStorageConfig(config, workspace) { - const errors = []; - const warnings = []; - const forbiddenFiles = forbiddenWorkspaceFilesPresent(workspace); - for (const file of forbiddenFiles) { - errors.push(`Forbidden Knowledge workspace file present: ${file}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`); +function titleForRef(parsed) { + if (parsed.kind === "file") + return basename3(parsed.path); + if (parsed.kind === "s3") + return basename3(parsed.key); + if (parsed.kind === "web") + return basename3(new URL(parsed.url).pathname) || parsed.url; + return parsed.path ? basename3(parsed.path) : parsed.id; +} +async function readDirectSourceText(parsed, config, safetyPolicy) { + if (parsed.kind === "file") { + if (!existsSync7(parsed.path)) + throw new Error(`Source file not found: ${parsed.path}`); + const text = readFileSync9(parsed.path, "utf8"); + return { + text, + contentSource: "file", + title: titleForRef(parsed), + mime: "text/plain", + size: text.length, + hash: sha256Text(text), + revision: null, + extractedTextRef: null, + metadata: { path: parsed.path }, + permissions: { mode: "read_only" } + }; } - if (!workspace.home.endsWith(HASNA_KNOWLEDGE_APP_PATH)) { - warnings.push(`Workspace home does not end with ${HASNA_KNOWLEDGE_APP_PATH}: ${workspace.home}`); + if (parsed.kind === "s3") { + const text = await readS3Text2(parsed.uri, config, safetyPolicy); + return { + text, + contentSource: "s3", + title: titleForRef(parsed), + mime: "text/plain", + size: text.length, + hash: sha256Text(text), + revision: null, + extractedTextRef: null, + metadata: { bucket: parsed.bucket, key: parsed.key }, + permissions: { mode: "read_only" } + }; } - if (config.storage.type === "s3") { - if (!config.storage.s3?.bucket) - errors.push("storage.s3.bucket is required when storage.type is s3."); - if (!config.storage.s3?.prefix) - warnings.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root."); - if (config.mode === "local") - warnings.push("storage.type is s3 while mode is local; this is valid for BYO S3, but hosted wrappers should set mode to hosted."); + if (parsed.kind === "web") { + const web = await readWebText(parsed.url, safetyPolicy); + return { + text: web.text, + contentSource: "web", + title: titleForRef(parsed), + mime: web.mime, + size: web.text.length, + hash: sha256Text(web.text), + revision: null, + extractedTextRef: null, + metadata: { url: parsed.url }, + permissions: { mode: "read_only" } + }; } - if (config.storage.type === "local" && config.storage.s3) { - warnings.push("storage.s3 is configured but ignored while storage.type is local."); + throw new Error(`Direct source reading is not available for ${parsed.uri}`); +} +async function readTextRef(uri, config, safetyPolicy) { + if (uri.startsWith("open-files://")) { + throw new Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://."); } - if (config.sources.preferred_ref !== "open-files") { - warnings.push("sources.preferred_ref should stay open-files for durable company knowledge."); + const parsed = parseSourceRef(uri); + const direct = await readDirectSourceText(parsed, config, safetyPolicy); + return { text: direct.text, contentSource: "extracted_text_ref" }; +} +async function readOpenFilesSourceText(options) { + const resolved = await resolveOpenFilesSource({ + dbPath: options.dbPath, + sourceRef: options.sourceRef, + purpose: options.purpose ?? "knowledge_index", + limit: 100, + safetyPolicy: options.safetyPolicy, + now: options.now + }); + if (!resolved.resolved) { + throw new Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API."); } - if (!config.sources.allowed_schemes.includes("open-files")) { - errors.push("sources.allowed_schemes must include open-files."); + if (resolved.revision?.extracted_text_uri && !resolved.content.text_available) { + const textRef = await readTextRef(resolved.revision.extracted_text_uri, options.config, options.safetyPolicy); + return { + text: textRef.text, + contentSource: textRef.contentSource, + title: resolved.source?.title ?? null, + mime: resolved.content.mime, + size: textRef.text.length, + hash: resolved.revision.hash ?? sha256Text(textRef.text), + revision: resolved.revision.revision, + extractedTextRef: resolved.revision.extracted_text_uri, + metadata: resolved.source?.metadata ?? {}, + permissions: resolved.source?.permissions ?? { mode: "read_only" } + }; } - if (config.mode === "hosted" && config.hosted?.api_url) { - try { - normalizeKnowledgeApiOrigin(config.hosted.api_url); - } catch { - errors.push("hosted.api_url must be an http(s) URL when mode is hosted."); - } + if (resolved.chunks.length === 0) { + throw new Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first."); } - return { - ok: errors.length === 0, - errors, - warnings - }; -} -function recordStorageObjects(db, objects, now = new Date) { - const timestamp = now.toISOString(); - const statement = db.prepare(` - INSERT INTO storage_objects ( - id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(artifact_uri) DO UPDATE SET - kind = excluded.kind, - content_type = excluded.content_type, - hash = excluded.hash, - size_bytes = excluded.size_bytes, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at - `); - const insert = db.transaction((entries) => { - for (const entry of entries) { - const metadata = { - key: entry.key, - ...entry.modified_at ? { artifact_modified_at: entry.modified_at } : {}, - ...entry.metadata ?? {} - }; - statement.run(randomUUID2(), entry.uri, entry.kind, entry.content_type ?? null, entry.hash ?? null, entry.size_bytes ?? null, JSON.stringify(metadata), timestamp, timestamp); - } - }); - insert(objects); -} + const text = resolved.chunks.map((chunk) => chunk.text).join(` -// src/provenance.ts -function isStaleStatus(status) { - return ["deleted", "stale", "invalidated", "reindex_required"].includes((status ?? "").toLowerCase()); -} -function sourceProvenance(input) { - const status = input.status ?? null; +`); return { - source_owner: "open-files", - source_ref: input.source_ref ?? null, - source_uri: input.source_uri ?? null, - source_kind: input.source_kind ?? null, - source_revision_id: input.source_revision_id ?? null, - revision: input.revision ?? null, - hash: input.hash ?? null, - chunk_id: input.chunk_id ?? null, - start_offset: input.start_offset ?? null, - end_offset: input.end_offset ?? null, - status, - read_only: true, - citation_required: true, - resolver: input.resolver ?? null, - stale: isStaleStatus(status) + text, + contentSource: "catalog_chunks", + title: resolved.source?.title ?? null, + mime: resolved.content.mime, + size: text.length, + hash: resolved.revision?.hash ?? sha256Text(text), + revision: resolved.revision?.revision ?? null, + extractedTextRef: resolved.revision?.extracted_text_uri ?? null, + metadata: resolved.source?.metadata ?? {}, + permissions: resolved.source?.permissions ?? { mode: "read_only" } }; } -function generatedArtifactProvenance(input) { - return { - source_owner: "open-files", - generated_from: input.generated_from, - artifact_key: input.artifact_key, - source_refs: input.source_refs ?? [], - read_only_sources: true, - citation_required: input.citation_required ?? true, - raw_source_bytes_stored_in_open_knowledge: false +function manifestItemForSource(sourceRef, parsed, resolved, purpose) { + const hash = resolved.hash ?? sha256Text(resolved.text); + const metadata = { + ...redactPrivateRefs(resolved.metadata), + source_ref: sourceRef, + content_source: resolved.contentSource, + read_only: true + }; + const item = { + source_ref: sourceRef, + name: resolved.title ?? titleForRef(parsed), + mime: resolved.mime ?? "text/plain", + size: resolved.size ?? resolved.text.length, + hash, + revision: resolved.revision ?? hash, + status: "active", + updated_at: new Date().toISOString(), + permissions: { + mode: "read_only", + allowed_purposes: [purpose], + ...resolved.permissions + }, + metadata, + extracted_text_ref: resolved.extractedTextRef, + extracted_text: resolved.text }; + if (parsed.kind === "open-files") { + if (parsed.entity === "file") + item.file_id = parsed.id; + if (parsed.entity === "source") { + item.source_id = parsed.id; + item.path = parsed.path; + } + } + if (parsed.kind === "file") + item.path = parsed.path; + if (parsed.kind === "s3") + item.path = parsed.key; + if (parsed.kind === "web") + item.url = parsed.url; + return item; } -function withProvenance(metadata, provenance) { +async function ingestSourceRef(options) { + const purpose = options.purpose ?? "knowledge_index"; + assertNoPrivateRefs(options.sourceRef, { + allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") !== false + }); + const parsed = parseSourceRef(options.sourceRef); + const resolved = parsed.kind === "open-files" ? await readOpenFilesSourceText(options) : await readDirectSourceText(parsed, options.config, options.safetyPolicy); + const item = manifestItemForSource(options.sourceRef, parsed, resolved, purpose); + const result = await ingestOpenFilesManifestItems({ + dbPath: options.dbPath, + items: [item], + sourceLabel: options.sourceRef, + readAction: "source_ref_ingest_read", + allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") !== false, + safetyPolicy: options.safetyPolicy, + now: options.now + }); return { - ...metadata, - provenance + ...result, + source_ref: options.sourceRef, + content_source: resolved.contentSource, + read_only: true, + hash: String(item.hash) }; } -// src/source-ingest.ts -import { createHash as createHash7 } from "crypto"; -import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs"; -import { basename as basename3 } from "path"; - -// src/manifest-ingest.ts -import { createHash as createHash6 } from "crypto"; -import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs"; -import { basename as basename2 } from "path"; - -// src/source-ref.ts -import { fileURLToPath } from "url"; -function assertNonEmpty(value, message) { - if (!value) - throw new Error(message); - return value; -} -function parseOpenFilesRef(uri) { - const withoutScheme = uri.slice("open-files://".length); - const parts = withoutScheme.split("/").filter(Boolean); - const entity = parts[0]; - if (entity !== "file" && entity !== "source") { - throw new Error("Invalid open-files ref. Expected open-files://file/<id>, open-files://file/<id>/revision/<revision_id>, or open-files://source/<id>/path/<path>."); - } - const id = assertNonEmpty(parts[1], "Invalid open-files ref. Missing id."); - if (entity === "file") { - if (parts.length === 2) - return { kind: "open-files", uri, entity, id }; - if (parts[2] === "revision" && parts[3] && parts.length === 4) { - return { kind: "open-files", uri, entity, id, revision_id: decodeURIComponent(parts[3]) }; - } - throw new Error("Invalid open-files file ref. Expected open-files://file/<id>/revision/<revision_id>."); - } - const pathIndex = parts.indexOf("path"); - const path = pathIndex >= 0 ? decodeURIComponent(parts.slice(pathIndex + 1).join("/")) : undefined; - return { kind: "open-files", uri, entity, id, path }; -} -function parseS3Ref(uri) { - const parsed = new URL(uri); - const bucket = assertNonEmpty(parsed.hostname, "Invalid s3 ref. Missing bucket."); - const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); - if (!key) - throw new Error("Invalid s3 ref. Missing object key."); - return { kind: "s3", uri, bucket, key }; -} -function parseFileRef(uri) { - return { kind: "file", uri, path: fileURLToPath(uri) }; -} -function parseWebRef(uri) { - const parsed = new URL(uri); - return { kind: "web", uri, url: parsed.toString() }; -} -function parseSourceRef(uri) { - if (uri.startsWith("open-files://")) - return parseOpenFilesRef(uri); - if (uri.startsWith("s3://")) - return parseS3Ref(uri); - if (uri.startsWith("file://")) - return parseFileRef(uri); - if (uri.startsWith("https://") || uri.startsWith("http://")) - return parseWebRef(uri); - throw new Error(`Unsupported source ref scheme: ${uri}`); -} -function catalogSourceUriForRef(uri, parsed = parseSourceRef(uri)) { - if (parsed.kind === "open-files" && parsed.entity === "file" && parsed.revision_id) { - return uri.replace(/\/revision\/[^/]+$/, ""); - } - return uri; +// src/app-wiki.ts +function stableId2(prefix, value) { + return `${prefix}_${createHash8("sha256").update(value).digest("hex").slice(0, 20)}`; } -function revisionIdForSourceRef(uri) { - const parsed = parseSourceRef(uri); - return parsed.kind === "open-files" && parsed.entity === "file" ? parsed.revision_id ?? null : null; +function slugify(value) { + const slug = value.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80); + return slug || "note"; } -function isSupportedSourceRef(uri) { +function parseJsonObject2(value) { + if (!value) + return {}; try { - parseSourceRef(uri); - return true; + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; } catch { - return false; + return {}; } } - -// src/safety.ts -import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto"; -import { relative as relative2, resolve as resolve2, sep as sep2 } from "path"; -function envEnabled(name) { - const value = process.env[name]; - return value === "1" || value === "true" || value === "yes"; -} -function resolveSafetyPolicy(config, workspace) { - const extended = config; - const configuredBuckets = new Set(extended.safety?.network?.allowed_s3_buckets ?? []); - if (config.storage.type === "s3" && config.storage.s3?.bucket) - configuredBuckets.add(config.storage.s3.bucket); - if (process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS) { - for (const bucket of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((entry) => entry.trim()).filter(Boolean)) { - configuredBuckets.add(bucket); - } - } - return { - mode: config.mode, - allowWriteRoots: [ - workspace.home, - workspace.artifactsDir, - workspace.cacheDir, - workspace.exportsDir, - workspace.indexesDir, - workspace.logsDir, - workspace.runsDir, - workspace.schemasDir, - workspace.wikiDir - ].map((entry) => resolve2(entry)), - readOnlySourceAccess: true, - network: { - webSearchEnabled: extended.safety?.network?.web_search_enabled ?? envEnabled("HASNA_KNOWLEDGE_WEB_SEARCH"), - s3ReadsEnabled: extended.safety?.network?.s3_reads_enabled ?? envEnabled("HASNA_KNOWLEDGE_ALLOW_S3_READS"), - allowedS3Buckets: [...configuredBuckets].sort() - }, - redaction: { - enabled: extended.safety?.redaction?.enabled ?? true - }, - approvals: { - generatedWritesRequireApproval: extended.safety?.approvals?.generated_writes_require_approval ?? true - } - }; +function estimateTokenCount2(text) { + const words = text.trim().split(/\s+/).filter(Boolean).length; + return Math.max(1, Math.ceil(words * 1.25)); } -function isInside(root, target) { - const rel = relative2(root, target); - return rel === "" || !rel.startsWith("..") && rel !== ".." && !rel.startsWith(`..${sep2}`); +function uniqueStrings(values) { + return Array.from(new Set((values ?? []).map((value) => value.trim()).filter(Boolean))); } -function assertWriteAllowed(targetPath, policy) { - const resolved = resolve2(targetPath); - if (!policy.allowWriteRoots.some((root) => isInside(root, resolved))) { - throw new Error(`Safety policy denied write outside .hasna/knowledge: ${targetPath}`); +function normalizeNotePath(input) { + const raw = input.path?.trim() || `wiki/notes/${slugify(input.title)}.md`; + const normalized = raw.replace(/\\/g, "/"); + if (!normalized.startsWith("wiki/notes/") || !normalized.endsWith(".md")) { + throw new Error("App wiki note paths must be relative wiki/notes/*.md artifact keys."); } + if (normalized.startsWith("/") || normalized.split("/").some((segment) => segment === ".." || segment === ".")) { + throw new Error(`Invalid app wiki note path: ${raw}`); + } + return normalized; } -function assertS3ReadAllowed(uri, policy) { - const parsed = new URL(uri); - const bucket = parsed.hostname; - if (!policy.network.s3ReadsEnabled) { - throw new Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1."); +function noteBody(input) { + const sections = [ + `# ${input.title}`, + "", + input.content.trim(), + "", + `Updated: ${input.now}` + ]; + if (input.tags.length > 0) { + sections.push("", "Tags:", ...input.tags.map((tag) => `- ${tag}`)); } - if (!policy.network.allowedS3Buckets.includes(bucket)) { - throw new Error(`Safety policy denied S3 bucket "${bucket}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`); + if (input.sourceRefs.length > 0) { + sections.push("", "Source refs:", ...input.sourceRefs.map((ref) => `- ${ref}`)); } + sections.push(""); + return sections.join(` +`); } -function assertWebSearchAllowed(policy) { - if (!policy.network.webSearchEnabled) { - throw new Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1."); - } +async function writeArtifact(store, entry) { + const written = await store.put(entry); + return { + key: written.key, + uri: written.uri, + kind: entry.key.startsWith("logs/") ? "log" : "wiki_page", + content_type: entry.content_type, + modified_at: written.modified_at, + ...hashArtifactBody(entry.body), + metadata: { + ...entry.metadata ?? {} + } + }; } -var REDACTION_PATTERNS = [ - { type: "private_key_block", severity: "high", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, replacement: "[REDACTED:private_key_block]" }, - { type: "secret_assignment", severity: "high", regex: /\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi, replacement: "[REDACTED:secret_assignment]" }, - { type: "openai_api_key", severity: "high", regex: /\bsk-[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:openai_api_key]" }, - { type: "anthropic_api_key", severity: "high", regex: new RegExp(`\\b${["sk", "ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`, "g"), replacement: "[REDACTED:anthropic_api_key]" }, - { type: "aws_access_key_id", severity: "high", regex: /\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g, replacement: "[REDACTED:aws_access_key_id]" } -]; -function redactSecrets(text, policy) { - if (policy && !policy.redaction.enabled) - return { text, findings: [] }; - let output = text; - const findings = []; - for (const pattern of REDACTION_PATTERNS) { - output = output.replace(pattern.regex, (match, ...args) => { - const offset = typeof args.at(-2) === "number" ? args.at(-2) : output.indexOf(match); - findings.push({ - type: pattern.type, - severity: pattern.severity, - start: Math.max(0, offset), - end: Math.max(0, offset + match.length) - }); - return pattern.replacement; - }); +async function appendLog(store, event, now) { + const year = String(now.getUTCFullYear()); + const month = String(now.getUTCMonth() + 1).padStart(2, "0"); + const day = String(now.getUTCDate()).padStart(2, "0"); + const key = `logs/${year}/${month}/${day}.jsonl`; + let existing = ""; + try { + existing = await store.getText(key); + } catch { + existing = ""; } - return { text: output, findings }; + return writeArtifact(store, { + key, + body: `${existing}${JSON.stringify(event)} +`, + content_type: "application/x-ndjson", + metadata: { + provenance: generatedArtifactProvenance({ + generated_from: String(event.event ?? "app_wiki_log"), + artifact_key: key + }) + } + }); } -function auditId(input) { - return `audit_${createHash4("sha256").update(`${input.event_type}\x00${input.action}\x00${input.target_uri ?? ""}\x00${input.created_at ?? ""}\x00${JSON.stringify(input.metadata ?? {})}\x00${randomUUID3()}`).digest("hex").slice(0, 24)}`; +function noteMetadata(input) { + return { + ...redactPrivateRefs(input.metadata ?? {}), + app_wiki: true, + note: true, + artifact_key: input.path, + tags: input.tags, + source_refs: input.sourceRefs, + provenance: input.provenance + }; } -function truncateAuditMetadata(value, depth = 0) { - if (depth > 6) - return "[Truncated:depth]"; - if (typeof value === "string") { - return value.length > 1000 ? `${value.slice(0, 1000)}...[Truncated:${value.length - 1000} chars]` : value; - } - if (typeof value === "number" || typeof value === "boolean" || value === null || value === undefined) - return value; - if (Array.isArray(value)) { - const entries = value.slice(0, 25).map((entry) => truncateAuditMetadata(entry, depth + 1)); - if (value.length > 25) - entries.push(`[Truncated:${value.length - 25} items]`); - return entries; - } - if (typeof value === "object") { - const output = {}; - const entries = Object.entries(value).slice(0, 50); - for (const [key, entry] of entries) - output[key] = truncateAuditMetadata(entry, depth + 1); - const total = Object.keys(value).length; - if (total > entries.length) - output.__truncated_keys = total - entries.length; - return output; - } - return String(value); +function noteRecord(row) { + const metadata = parseJsonObject2(row.metadata_json); + return { + id: row.id, + path: row.path, + title: row.title, + artifact_uri: row.artifact_uri, + content_hash: row.content_hash, + tags: Array.isArray(metadata.tags) ? metadata.tags.filter((tag) => typeof tag === "string") : [], + source_refs: Array.isArray(metadata.source_refs) ? metadata.source_refs.filter((ref) => typeof ref === "string") : [], + created_at: row.created_at, + updated_at: row.updated_at + }; } -function recordAuditEvent(db, input) { - const createdAt = input.created_at ?? new Date().toISOString(); - const metadata = truncateAuditMetadata(input.metadata ?? {}); - const id = auditId({ ...input, metadata, created_at: createdAt }); - db.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`, [ - id, - input.event_type, - input.action, - input.target_uri ?? null, - input.decision, - JSON.stringify(metadata), - createdAt - ]); - return id; +function sourceCitationRows(db, sourceRefs) { + return sourceRefs.map((sourceRef) => { + const row = db.query(`SELECT + s.uri AS source_uri, + c.id AS chunk_id, + c.text, + c.start_offset, + c.end_offset, + sr.revision, + sr.hash, + c.metadata_json + FROM sources s + LEFT JOIN source_revisions sr ON sr.source_id = s.id + LEFT JOIN chunks c ON c.source_revision_id = sr.id + WHERE s.uri = ? OR s.metadata_json LIKE ? + ORDER BY sr.created_at DESC, c.ordinal ASC + LIMIT 1`).get(sourceRef, `%${sourceRef}%`); + const metadata = parseJsonObject2(row?.metadata_json); + return { + source_ref: sourceRef, + source_uri: row?.source_uri ?? sourceRef, + chunk_id: row?.chunk_id ?? null, + quote: row?.text ? row.text.replace(/\s+/g, " ").slice(0, 240) : null, + start_offset: row?.start_offset ?? null, + end_offset: row?.end_offset ?? null, + metadata: { + source_ref: sourceRef, + revision: row?.revision ?? metadata.revision, + hash: row?.hash ?? metadata.hash + } + }; + }); } -function recordRedactionFindings(db, input) { - const createdAt = input.created_at ?? new Date().toISOString(); - for (const finding of input.findings) { - db.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`, [ - `redact_${randomUUID3()}`, - input.source_uri ?? null, - input.run_id ?? null, - finding.severity, - finding.type, - JSON.stringify({ ...input.metadata ?? {}, start: finding.start, end: finding.end }), - createdAt +function replaceNoteCitations(db, pageId, sourceRefs, now) { + db.run("DELETE FROM citations WHERE wiki_page_id = ?", [pageId]); + const citations = sourceCitationRows(db, sourceRefs); + for (const citation of citations) { + db.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + stableId2("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID4()}`), + pageId, + citation.chunk_id, + citation.source_uri, + citation.quote, + citation.start_offset, + citation.end_offset, + JSON.stringify(citation.metadata), + now ]); } - return input.findings.length; + return citations.length; } -function createApprovalGate(db, input) { - const now = input.created_at ?? new Date().toISOString(); - const id = `approval_${randomUUID3()}`; - db.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - id, - input.action, - input.target_uri ?? null, - "approved", - input.reason ?? null, - input.approved_by ?? "local-cli", - JSON.stringify(input.metadata ?? {}), - now, - now +function upsertNoteIndex(db, input) { + db.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(kind, name, shard_key) DO UPDATE SET + artifact_uri = excluded.artifact_uri, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at`, [ + stableId2("idx", `app-wiki-note\x00${input.path}`), + "app_wiki_note", + input.title, + input.artifactUri, + input.path, + JSON.stringify({ + artifact_key: input.path, + content_hash: input.contentHash, + tags: input.tags, + source_refs: input.sourceRefs + }), + input.now, + input.now ]); - return { id, status: "approved" }; -} -var COMMON_BARE_TOKEN_PATTERNS = [ - { type: "github_token", severity: "high", regex: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_token]" }, - { type: "github_pat_token", severity: "high", regex: /\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_pat_token]" }, - { type: "package_registry_token", severity: "high", regex: /\bnpm_[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:package_registry_token]" }, - { type: "context7_token", severity: "high", regex: /\bctx7sk[-][A-Za-z0-9_-]{10,}\b/g, replacement: "[REDACTED:context7_token]" }, - { type: "xai_api_key", severity: "high", regex: /\bxai[-][A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:xai_api_key]" }, - { type: "google_api_key", severity: "high", regex: /\bAIza[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED:google_api_key]" } -]; -REDACTION_PATTERNS.push(...COMMON_BARE_TOKEN_PATTERNS); - -// src/private-ref.ts -import { createHash as createHash5 } from "crypto"; -import { realpathSync } from "fs"; -import { homedir as homedir3, tmpdir } from "os"; -var PATH_TAIL = String.raw`[^\s"'<>),\]}]`; -var PATH_SEGMENT = String.raw`[^/\\\s"'<>]+`; -var FILE_URI_RE = /file:\/\/[^\s"'<>),\]}]+/gi; -var ABSOLUTE_HASNA_PATH_RE = /\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g; -var HASNA_PATH_RE = /(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi; -var PRIVATE_WORKSPACE_PATH_RE = new RegExp(String.raw`/(?:home|Users)/${PATH_SEGMENT}/(?:workspace|Workspace)/${PATH_TAIL}*`, "g"); -var LOCAL_PATH_PATTERNS = [ - new RegExp(String.raw`/(?:home|Users)/${PATH_SEGMENT}(?:/${PATH_TAIL}*)?`, "g"), - new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${PATH_TAIL}+`, "g"), - new RegExp(String.raw`(?:/private)?/tmp/${PATH_TAIL}+`, "g"), - new RegExp(String.raw`(?<![A-Za-z0-9])[A-Za-z]:[\\/]${PATH_TAIL}+`, "g"), - new RegExp(String.raw`\\\\${PATH_SEGMENT}\\${PATH_TAIL}+`, "g") -]; -var RAW_DB_OR_ENV_RE = /\b(?:knowledge\.db(?:[-.][A-Za-z0-9_-]+)?|db\.json(?:[-.][A-Za-z0-9_-]+)?|cloud\.env|migration-exports\/[^\s"'<>),\]}]+)\b/gi; -var DATABASE_URL_RE = /\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi; -var OPAQUE_EXPORT_KEYS = new Set(["content_base64"]); -function escapeRegExp(value) { - return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -function isUsableRoot(root) { - return root.length >= 4 && root !== "/" && !/^[A-Za-z]:[\\/]?$/.test(root); +function upsertNotePage(db, input) { + db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(path) DO UPDATE SET + title = excluded.title, + artifact_uri = excluded.artifact_uri, + content_hash = excluded.content_hash, + status = excluded.status, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at`, [ + input.pageId, + input.path, + input.title, + input.artifactUri, + input.contentHash, + "active", + JSON.stringify(input.metadata), + input.now, + input.now + ]); + const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(input.pageId); + for (const row of existing) + db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); + db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [input.pageId]); + const chunkId = stableId2("chk", `${input.pageId}\x00${input.contentHash}`); + db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + chunkId, + input.pageId, + "wiki", + 0, + input.body, + estimateTokenCount2(input.body), + 0, + input.body.length, + JSON.stringify({ + ...input.metadata, + artifact_uri: input.artifactUri, + content_hash: input.contentHash + }), + input.now + ]); + db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [ + chunkId, + input.body, + input.title, + input.artifactUri + ]); } -var hostRootCacheKey = null; -var hostRootCache = []; -function hostRootPatterns() { - const roots = new Set; - for (const root of [homedir3(), tmpdir()]) { - if (!root) - continue; - roots.add(root); - try { - roots.add(realpathSync(root)); - } catch {} +function assertAppWikiWriteAllowed(options) { + if (options.scope === "global" && options.allowGlobal !== true) { + throw new Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global."); } - const key = [...roots].sort().join("\x00"); - if (key === hostRootCacheKey) - return hostRootCache; - hostRootCacheKey = key; - hostRootCache = [...roots].filter(isUsableRoot).sort((a, b) => b.length - a.length).map((root) => new RegExp(`${escapeRegExp(root)}(?:[/\\\\]${PATH_TAIL}*)?`, "g")); - return hostRootCache; -} -function fingerprint(value) { - return createHash5("sha256").update(value).digest("hex").slice(0, 12); -} -function preview(value) { - return value.length <= 80 ? value : `${value.slice(0, 77)}...`; + if (options.workspace.home.includes("/.husna/") || options.workspace.home.endsWith("/.husna")) { + throw new Error(`Refusing app-wiki writes to legacy .husna path: ${options.workspace.home}`); + } + if (options.workspace.home.includes("/.hasna/apps/knowledge")) { + throw new Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${options.workspace.home}`); + } + if (options.safetyPolicy) + assertWriteAllowed(options.workspace.knowledgeDbPath, options.safetyPolicy); } -function includesPrivateKnowledgeArtifact(value) { - return /(?:^|\/)\.hasna(?:\/|$)/i.test(value) || /\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test(value) || /\bmigration-exports\//i.test(value); +async function initAppWikiScope(options) { + assertAppWikiWriteAllowed(options); + const migration = migrateKnowledgeDb(options.workspace.knowledgeDbPath); + const db = openKnowledgeDb(options.workspace.knowledgeDbPath); + try { + recordAuditEvent(db, { + event_type: "write", + action: "app_wiki_init", + target_uri: options.workspace.home, + decision: "allow", + metadata: { + scope: options.scope, + store_type: options.store.type, + app_path: ".hasna/knowledge" + }, + created_at: (options.now ?? new Date).toISOString() + }); + } finally { + db.close(); + } + return { + ok: true, + scope: options.scope, + workspace_home: options.workspace.home, + knowledge_db_path: options.workspace.knowledgeDbPath, + schema_version: migration.schema_version, + store_type: options.store.type, + global_write_allowed: options.scope === "global" && options.allowGlobal === true, + message: `Initialized app wiki scope at ${options.workspace.home}` + }; } -function addStringIssues(value, path, options, issues) { - for (const match of value.matchAll(FILE_URI_RE)) { - const uri = match[0]; - if (!options.allowFileSourceRefs || includesPrivateKnowledgeArtifact(uri)) { - issues.push({ - type: includesPrivateKnowledgeArtifact(uri) ? "private_file_uri" : "local_file_uri", - severity: "high", - path, - preview: preview(uri.replace(/^file:\/\/.*/, `[redacted:file-uri:${fingerprint(uri)}]`)) - }); - } +async function writeAppWikiNote(options) { + assertAppWikiWriteAllowed(options); + const nowDate = options.now ?? new Date; + const now = nowDate.toISOString(); + const tags = uniqueStrings(options.tags); + const sourceRefs = uniqueStrings(options.sourceRefs); + for (const sourceRef of sourceRefs) { + assertNoPrivateRefs(sourceRef, { allowFileSourceRefs: options.safetyPolicy?.readOnlySourceAccess === true }); } - for (const match of value.matchAll(HASNA_PATH_RE)) { - issues.push({ - type: "private_hasna_path", - severity: "high", + const path = normalizeNotePath(options); + const body = noteBody({ + title: options.title, + content: options.content, + tags, + sourceRefs, + now + }); + const provenance = generatedArtifactProvenance({ + generated_from: "app_wiki_note", + artifact_key: path, + source_refs: sourceRefs + }); + const artifact = await writeArtifact(options.store, { + key: path, + body, + content_type: "text/markdown", + metadata: { + generated_from: "app_wiki_note", + provenance, + scope: options.scope, + tags: tags.join(","), + source_refs: sourceRefs.join(",") + } + }); + const log = await appendLog(options.store, { + ts: now, + event: "app_wiki_note_written", + page_key: path, + source_refs: sourceRefs, + tags + }, nowDate); + migrateKnowledgeDb(options.workspace.knowledgeDbPath); + const db = openKnowledgeDb(options.workspace.knowledgeDbPath); + try { + const pageId = stableId2("wiki", path); + const metadata = noteMetadata({ path, - preview: `[redacted:.hasna:${fingerprint(match[0])}]` + tags, + sourceRefs, + provenance, + metadata: options.metadata }); - } - for (const match of value.matchAll(RAW_DB_OR_ENV_RE)) { - issues.push({ - type: match[0].toLowerCase() === "cloud.env" ? "workspace_env_file" : "raw_database_or_export_ref", - severity: "high", + recordStorageObjects(db, [artifact, log], nowDate); + upsertNotePage(db, { + pageId, path, - preview: `[redacted:${fingerprint(match[0])}]` + title: options.title, + artifactUri: artifact.uri, + contentHash: artifact.hash ?? "", + body, + metadata, + now }); - } - for (const match of value.matchAll(DATABASE_URL_RE)) { - issues.push({ - type: "database_url", - severity: "high", + const citationsWritten = replaceNoteCitations(db, pageId, sourceRefs, now); + upsertNoteIndex(db, { + title: options.title, path, - preview: `[redacted:database-url:${fingerprint(match[0])}]` + artifactUri: artifact.uri, + contentHash: artifact.hash ?? "", + tags, + sourceRefs, + now }); - } - if (!options.allowPrivateWorkspaceRefs) { - for (const match of value.matchAll(PRIVATE_WORKSPACE_PATH_RE)) { - issues.push({ - type: "private_workspace_path", - severity: "medium", + recordAuditEvent(db, { + event_type: "write", + action: "app_wiki_note_write", + target_uri: artifact.uri, + decision: "allow", + metadata: { + scope: options.scope, path, - preview: `[redacted:workspace:${fingerprint(match[0])}]` - }); - } + source_refs: sourceRefs, + tags + }, + created_at: now + }); + const row = db.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(pageId); + if (!row) + throw new Error(`Failed to write app wiki note: ${path}`); + return { + ok: true, + scope: options.scope, + workspace_home: options.workspace.home, + note: noteRecord(row), + artifact_uri: artifact.uri, + content_hash: artifact.hash ?? "", + citations_written: citationsWritten, + chunks_written: 1, + storage_objects_written: 2, + message: `Wrote app wiki note ${path}` + }; + } finally { + db.close(); } } -function lintPrivateRefs(value, options = {}, path = "$") { - const issues = []; - const visit = (entry, entryPath) => { - if (typeof entry === "string") { - addStringIssues(entry, entryPath, options, issues); - return; - } - if (!entry || typeof entry !== "object") - return; - if (Array.isArray(entry)) { - entry.forEach((item, index) => visit(item, `${entryPath}[${index}]`)); - return; - } - for (const [key, item] of Object.entries(entry)) { - visit(item, `${entryPath}.${key}`); - } - }; - visit(value, path); - return issues; -} -function assertNoPrivateRefs(value, options = {}) { - const issues = lintPrivateRefs(value, options); - if (issues.length === 0) - return; - const counts = new Map; - for (const issue of issues) - counts.set(issue.type, (counts.get(issue.type) ?? 0) + 1); - const summary = [...counts.entries()].map(([type, count2]) => `${type}:${count2}`).join(", "); - throw new Error(`Knowledge private-ref lint failed (${summary}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`); -} -function redactString(value) { - let text = redactSecrets(value).text.replace(DATABASE_URL_RE, (match) => `[REDACTED:database-url:${fingerprint(match)}]`).replace(FILE_URI_RE, (match) => `[REDACTED:local-file-uri:${fingerprint(match)}]`).replace(ABSOLUTE_HASNA_PATH_RE, (match) => `[REDACTED:local-hasna-path:${fingerprint(match)}]`).replace(PRIVATE_WORKSPACE_PATH_RE, (match) => `[REDACTED:private-workspace:${fingerprint(match)}]`); - for (const pattern of [...hostRootPatterns(), ...LOCAL_PATH_PATTERNS]) { - text = text.replace(pattern, (match) => `[REDACTED:local-path:${fingerprint(match)}]`); +function listAppWikiNotes(options) { + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + if (!options.dbPath) + return []; + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + try { + return db.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + FROM wiki_pages + WHERE status = 'active' + AND path LIKE 'wiki/notes/%' + AND metadata_json LIKE '%"app_wiki":true%' + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(limit).map(noteRecord); + } finally { + db.close(); } - return text.replace(HASNA_PATH_RE, (match) => `[REDACTED:hasna-path:${fingerprint(match)}]`).replace(RAW_DB_OR_ENV_RE, (match) => `[REDACTED:private-artifact:${fingerprint(match)}]`); } -function redactPrivateRefs(value) { - if (typeof value === "string") - return redactString(value); - if (!value || typeof value !== "object") - return value; - if (Array.isArray(value)) - return value.map((entry) => redactPrivateRefs(entry)); - const output = {}; - for (const [key, entry] of Object.entries(value)) { - output[key] = OPAQUE_EXPORT_KEYS.has(key) ? entry : redactPrivateRefs(entry); +async function getAppWikiNote(options) { + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + try { + const row = db.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + FROM wiki_pages + WHERE (id = ? OR path = ?) + AND path LIKE 'wiki/notes/%' + AND metadata_json LIKE '%"app_wiki":true%'`).get(options.id, options.id); + if (!row) + return null; + const citations = db.query(`SELECT id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at + FROM citations + WHERE wiki_page_id = ? + ORDER BY created_at ASC`).all(row.id).map((citation) => ({ + ...citation, + metadata: parseJsonObject2(citation.metadata_json), + metadata_json: undefined + })); + let content = null; + if (options.includeContent !== false) { + try { + content = await options.store.getText(row.path); + } catch { + content = null; + } + } + return { + ok: true, + note: noteRecord(row), + citations, + content + }; + } finally { + db.close(); } - return output; -} - -// src/manifest-ingest.ts -var DEFAULT_MAX_MANIFEST_INPUT_BYTES = 20 * 1024 * 1024; -var DEFAULT_MAX_MANIFEST_ITEMS = 1e4; -var DEFAULT_MANIFEST_PREVIEW_ITEMS = 10; -function stableId(prefix, value) { - return `${prefix}_${createHash6("sha256").update(value).digest("hex").slice(0, 20)}`; } -function asObject(value) { - return value && typeof value === "object" && !Array.isArray(value) ? value : undefined; -} -function asString(value) { - return typeof value === "string" && value.length > 0 ? value : undefined; -} -function asNumber(value) { - return typeof value === "number" && Number.isFinite(value) ? value : undefined; +async function ingestAppWikiSourceRef(options) { + assertAppWikiWriteAllowed(options); + assertNoPrivateRefs(options.sourceRef, { + allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") !== false + }); + return ingestSourceRef({ + dbPath: options.workspace.knowledgeDbPath, + sourceRef: options.sourceRef, + purpose: options.purpose ?? "knowledge_index", + config: options.config, + safetyPolicy: options.safetyPolicy + }); } -function buildSourceRefFromItem(item) { - const explicit = asString(item.source_ref) ?? asString(item.source_uri) ?? asString(item.uri); - if (explicit) - return explicit; - const fileId = asString(item.file_id); - if (fileId) { - const revision = asString(item.revision_id) ?? asString(item.revision); - const fileRef = `open-files://file/${encodeURIComponent(fileId)}`; - return revision ? `${fileRef}/revision/${encodeURIComponent(revision)}` : fileRef; + +// src/agent.ts +import { randomUUID as randomUUID6 } from "crypto"; + +// src/providers.ts +import { randomUUID as randomUUID5 } from "crypto"; +var DEFAULT_PROVIDER_SETTINGS = { + openai: { + api_key_env: "OPENAI_API_KEY", + default_model: "gpt-5.2" + }, + anthropic: { + api_key_env: "ANTHROPIC_API_KEY", + default_model: "claude-sonnet-4-6" + }, + deepseek: { + api_key_env: "DEEPSEEK_API_KEY", + default_model: "deepseek-chat" } - const sourceId = asString(item.source_id); - const path = asString(item.path); - if (sourceId && path) { - return `open-files://source/${encodeURIComponent(sourceId)}/path/${encodeURIComponent(path)}`; +}; +var PROVIDER_CAPABILITIES = { + openai: { + text_generation: true, + structured_output: true, + tool_usage: true, + tool_streaming: true, + image_input: true, + native_web_search: true, + reasoning: true, + embeddings: true + }, + anthropic: { + text_generation: true, + structured_output: true, + tool_usage: true, + tool_streaming: true, + image_input: true, + native_web_search: false, + reasoning: true, + embeddings: false + }, + deepseek: { + text_generation: true, + structured_output: true, + tool_usage: true, + tool_streaming: true, + image_input: false, + native_web_search: false, + reasoning: true, + embeddings: false } - throw new Error("Manifest item is missing source_ref, file_id, or source_id/path."); +}; +var BUILTIN_ALIASES = { + default: "openai:gpt-5.2", + fast: "openai:gpt-5-mini", + reasoning: "anthropic:claude-opus-4-6", + sonnet: "anthropic:claude-sonnet-4-6", + deepseek: "deepseek:deepseek-chat", + "deepseek-reasoning": "deepseek:deepseek-reasoner" +}; +function providerConfig(config) { + return config?.providers ?? {}; } -function baseSourceUri(sourceRef, parsed) { - if (parsed.kind === "open-files" && parsed.entity === "file" && parsed.revision_id) { - return sourceRef.replace(/\/revision\/[^/]+$/, ""); - } - return sourceRef; +function providerSettings(config, provider) { + const configured = providerConfig(config)[provider] ?? {}; + return { + ...DEFAULT_PROVIDER_SETTINGS[provider], + ...configured + }; } -function textFromItem(item) { - const direct = asString(item.extracted_text) ?? asString(item.text) ?? asString(item.content_text) ?? asString(item.markdown); - if (direct !== undefined) - return direct; - const content = item.content; - return typeof content === "string" ? content : null; +function modelAliases(config) { + const configured = providerConfig(config); + return { + ...BUILTIN_ALIASES, + ...configured.default_model ? { default: configured.default_model } : {}, + ...configured.aliases ?? {} + }; } -function extractedTextUriFromItem(item) { - const direct = asString(item.extracted_text_ref) ?? asString(item.extracted_text_uri) ?? asString(item.text_ref); - if (direct) - return direct; - const content = asObject(item.content); - return asString(content?.extracted_text_ref) ?? asString(content?.extracted_text_uri) ?? null; +function parseModelRef(modelRef) { + const [provider, ...rest] = modelRef.split(":"); + const model = rest.join(":"); + if (provider !== "openai" && provider !== "anthropic" && provider !== "deepseek") { + throw new Error(`Unsupported AI provider: ${provider}`); + } + if (!model) + throw new Error(`Invalid model ref: ${modelRef}. Expected provider:model.`); + return { provider, model }; } -function titleFromItem(item) { - const path = asString(item.path); - return asString(item.title) ?? asString(item.name) ?? (path ? basename2(path) : null); +function resolveModelRef(aliasOrRef, config) { + const aliases = modelAliases(config); + return aliases[aliasOrRef] ?? aliasOrRef; } -function hashFromItem(item) { - return asString(item.hash) ?? asString(item.checksum) ?? asString(item.sha256) ?? null; +function listModelRegistry(config) { + const aliases = modelAliases(config); + return Object.entries(aliases).map(([alias, modelRef]) => { + const parsed = parseModelRef(modelRef); + return { + alias, + model_ref: modelRef, + provider: parsed.provider, + model: parsed.model, + default: alias === "default", + capabilities: PROVIDER_CAPABILITIES[parsed.provider] + }; + }); } -var OMIT_MANIFEST_METADATA_KEYS = new Set([ - "text", - "content", - "content_text", - "extracted_text", - "markdown", - "raw", - "raw_text", - "raw_bytes", - "raw_content", - "raw_body", - "raw_file", - "source_raw", - "source_raw_bytes", - "source_bytes", - "source_content", - "source_body", - "file_bytes", - "file_content", - "content_bytes", - "content_base64", - "document_bytes", - "document_content", - "document_base64", - "binary", - "binary_content", - "binary_base64", - "bytes", - "body", - "blob", - "data", - "payload" -]); -function normalizeMetadataKey(key) { - return key.toLowerCase().replace(/[\s-]+/g, "_"); +function providerCredentialStatus(config, env = process.env) { + return Object.keys(DEFAULT_PROVIDER_SETTINGS).map((provider) => { + const settings = providerSettings(config, provider); + const configured = Boolean(env[settings.api_key_env]); + return { + provider, + api_key_env: settings.api_key_env, + configured, + source: configured ? "env" : "missing", + base_url: settings.base_url ?? null, + default_model: settings.default_model + }; + }); +} +function providerStatus(config, env = process.env) { + return { + default_model: resolveModelRef("default", config), + providers: providerCredentialStatus(config, env), + models: listModelRegistry(config) + }; } -function sanitizeManifestMetadataValue(value) { - if (Array.isArray(value)) - return value.map((entry) => sanitizeManifestMetadataValue(entry)); - const object = asObject(value); - if (!object) - return value; - const sanitized = {}; - for (const [key, nestedValue] of Object.entries(object)) { - if (OMIT_MANIFEST_METADATA_KEYS.has(normalizeMetadataKey(key))) +function assertProviderCredentials(provider, config, env = process.env) { + const status = providerCredentialStatus(config, env).find((entry) => entry.provider === provider); + if (!status) + throw new Error(`Unsupported AI provider: ${provider}`); + if (!status.configured) + throw new Error(`Missing ${status.api_key_env} for ${provider}. Set the env var to use this provider.`); + return status; +} +async function defaultFactory(provider) { + if (provider === "openai") { + const { createOpenAI } = await import("@ai-sdk/openai"); + return createOpenAI; + } + if (provider === "anthropic") { + const { createAnthropic } = await import("@ai-sdk/anthropic"); + return createAnthropic; + } + const { createDeepSeek } = await import("@ai-sdk/deepseek"); + return createDeepSeek; +} +async function createAiSdkProviderRegistry(options = {}) { + const { createProviderRegistry } = await import("ai"); + const env = options.env ?? process.env; + const providers = {}; + for (const provider of Object.keys(DEFAULT_PROVIDER_SETTINGS)) { + const settings = providerSettings(options.config, provider); + const apiKey = env[settings.api_key_env]; + if (!apiKey) continue; - sanitized[key] = sanitizeManifestMetadataValue(nestedValue); + const factory = options.factories?.[provider] ?? await defaultFactory(provider); + providers[provider] = factory({ apiKey, baseURL: settings.base_url }); } - return sanitized; + return createProviderRegistry(providers); } -function revisionFromItem(item, parsed, hash) { - const revision = asString(item.revision_id) ?? asString(item.revision) ?? asString(item.version_id) ?? (parsed.kind === "open-files" ? parsed.revision_id : undefined) ?? hash ?? asString(item.updated_at); - return revision ?? "current"; +async function languageModelFor(aliasOrRef, options = {}) { + const modelRef = resolveModelRef(aliasOrRef, options.config); + const parsed = parseModelRef(modelRef); + assertProviderCredentials(parsed.provider, options.config, options.env); + const registry = await createAiSdkProviderRegistry(options); + return registry.languageModel(modelRef); } -function metadataFromItem(item, normalized) { - const metadata = {}; - for (const [key, value] of Object.entries(item)) { - if (OMIT_MANIFEST_METADATA_KEYS.has(normalizeMetadataKey(key))) - continue; - metadata[key] = redactPrivateRefs(sanitizeManifestMetadataValue(value)); +function usageNumber(usage, keys) { + for (const key of keys) { + const value = usage[key]; + if (typeof value === "number" && Number.isFinite(value)) + return value; } - metadata.source_ref = normalized.sourceRef; - metadata.source_uri = normalized.sourceUri; - metadata.status = normalized.status; - return metadata; + return 0; } -function normalizeManifestItem(item, now, options = {}) { - const sourceRef = buildSourceRefFromItem(item); - assertNoPrivateRefs(sourceRef, { allowFileSourceRefs: options.allowFileSourceRefs === true }); - const parsed = parseSourceRef(sourceRef); - const sourceUri = baseSourceUri(sourceRef, parsed); - const hash = hashFromItem(item); - const status = asString(item.status) ?? "active"; +function normalizeAiSdkUsage(input) { + const usage = input.usage ?? {}; return { - raw: item, - sourceRef, - sourceUri, - kind: parsed.kind, - title: titleFromItem(item), - revision: revisionFromItem(item, parsed, hash), - hash, - extractedTextUri: extractedTextUriFromItem(item), - text: textFromItem(item), - metadata: metadataFromItem(item, { sourceRef, sourceUri, status }), - acl: item.permissions ?? item.acl ?? {}, - status, - updatedAt: asString(item.updated_at) ?? now + provider: input.provider, + model: input.model, + input_tokens: usageNumber(usage, ["inputTokens", "promptTokens", "input_tokens", "prompt_tokens"]), + output_tokens: usageNumber(usage, ["outputTokens", "completionTokens", "output_tokens", "completion_tokens"]), + cost_usd: input.costUsd ?? 0, + metadata: { + usage, + provider_metadata: input.providerMetadata ?? {} + } }; } -function parseManifestText(text) { - const trimmed = text.trim(); - if (!trimmed) - return []; - if (trimmed.startsWith("[")) { - const parsed = JSON.parse(trimmed); - if (!Array.isArray(parsed)) - throw new Error("Manifest array parse failed."); - return parsed.map((entry) => { - const item = asObject(entry); - if (!item) - throw new Error("Manifest array entries must be objects."); - return item; - }); +function recordProviderUsage(db, input) { + const id = `usage_${randomUUID5()}`; + db.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + id, + input.run_id ?? null, + input.provider, + input.model, + input.input_tokens, + input.output_tokens, + input.cost_usd, + JSON.stringify(input.metadata), + input.created_at ?? new Date().toISOString() + ]); + return id; +} + +// src/retrieval.ts +import { createHash as createHash10 } from "crypto"; + +// src/search.ts +import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs"; + +// src/embeddings.ts +import { createHash as createHash9 } from "crypto"; +var DEFAULT_EMBEDDING_MODEL_REF = "openai:text-embedding-3-small"; +var DEFAULT_EMBEDDING_DIMENSIONS = 1536; +function embeddingConfig(config) { + return config?.embeddings ?? {}; +} +function stableId3(prefix, value) { + return `${prefix}_${createHash9("sha256").update(value).digest("hex").slice(0, 20)}`; +} +function parseJsonObject3(value) { + if (!value) + return {}; + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; } - if (trimmed.startsWith("{")) { - try { - const parsed = JSON.parse(trimmed); - const object = asObject(parsed); - if (!object) - throw new Error("Manifest object parse failed."); - if (Array.isArray(object.items)) { - return object.items.map((entry) => { - const item = asObject(entry); - if (!item) - throw new Error("Manifest items entries must be objects."); - return item; - }); - } - if ("source_ref" in object || "source_uri" in object || "file_id" in object) - return [object]; - } catch (error) { - const lines = trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0); - if (lines.length <= 1) - throw error; - return lines.map((line) => { - const item = asObject(JSON.parse(line)); - if (!item) - throw new Error("Manifest JSONL entries must be objects."); - return item; - }); - } +} +function metadataString2(metadata, keys) { + for (const key of keys) { + const value = metadata[key]; + if (typeof value === "string" && value.length > 0) + return value; } - return trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => { - const item = asObject(JSON.parse(line)); - if (!item) - throw new Error("Manifest JSONL entries must be objects."); - return item; + return null; +} +function metadataNumber2(metadata, keys) { + for (const key of keys) { + const value = metadata[key]; + if (typeof value === "number" && Number.isFinite(value)) + return value; + } + return null; +} +function vectorNorm(vector) { + return Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0)); +} +function cosineSimilarity(a, b, bNorm = vectorNorm(b)) { + const aNorm = vectorNorm(a); + if (aNorm === 0 || bNorm === 0) + return 0; + const length = Math.min(a.length, b.length); + let dot = 0; + for (let i = 0;i < length; i += 1) + dot += a[i] * b[i]; + return dot / (aNorm * bNorm); +} +function deterministicVector(text, dimensions) { + const bytes = createHash9("sha256").update(text).digest(); + return Array.from({ length: dimensions }, (_, index) => { + const value = bytes[index % bytes.length] / 255; + return Number((value * 2 - 1).toFixed(6)); }); } -async function readS3Text(uri, config, safetyPolicy) { - const parsed = new URL(uri); - const bucket = parsed.hostname; - const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); - if (!bucket || !key) - throw new Error(`Invalid S3 manifest URI: ${uri}`); - if (safetyPolicy) - assertS3ReadAllowed(uri, safetyPolicy); - const [{ S3Client, GetObjectCommand }, { fromIni }] = await Promise.all([ - import("@aws-sdk/client-s3"), - import("@aws-sdk/credential-providers") - ]); - const s3Config = config?.storage.type === "s3" && config.storage.s3?.bucket === bucket ? config.storage.s3 : undefined; - const client = new S3Client({ - region: s3Config?.region, - credentials: s3Config?.profile ? fromIni({ profile: s3Config.profile }) : undefined, - maxAttempts: s3Config?.max_attempts +async function openAiEmbeddingModel(model, config, env = process.env) { + assertProviderCredentials("openai", config, env); + const settings = providerSettings(config, "openai"); + const { createOpenAI } = await import("@ai-sdk/openai"); + const openai = createOpenAI({ + apiKey: env[settings.api_key_env], + baseURL: settings.base_url }); - const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key })); - if (!response.Body) - return ""; - return await response.Body.transformToString(); + if (openai.embeddingModel) + return openai.embeddingModel(model); + if (openai.textEmbedding) + return openai.textEmbedding(model); + if (openai.textEmbeddingModel) + return openai.textEmbeddingModel(model); + throw new Error("OpenAI provider does not expose an embedding model factory."); } -async function readManifestInput(input, config, safetyPolicy, maxInputBytes = DEFAULT_MAX_MANIFEST_INPUT_BYTES) { - const text = input.startsWith("s3://") ? await readS3Text(input, config, safetyPolicy) : (() => { - if (!existsSync6(input)) - throw new Error(`Manifest not found: ${input}`); - return readFileSync7(input, "utf8"); - })(); - const bytes = Buffer.byteLength(text); - if (bytes > maxInputBytes) { - throw new Error(`Manifest input is too large: ${bytes} bytes exceeds ${maxInputBytes} byte limit.`); +function resolveEmbeddingModelRef(modelRef, config) { + if (!modelRef || modelRef === "default" || modelRef === "embedding") { + return embeddingConfig(config).default_model ?? DEFAULT_EMBEDDING_MODEL_REF; } - return text; + return modelRef; } -function chunkText(text, maxChars, overlapChars) { - const normalized = text.replace(/\r\n/g, ` -`); - if (!normalized.trim()) - return []; - const chunks = []; - let start = 0; - while (start < normalized.length) { - const hardEnd = Math.min(normalized.length, start + maxChars); - let end = hardEnd; - if (hardEnd < normalized.length) { - const paragraphBreak = normalized.lastIndexOf(` - -`, hardEnd); - const sentenceBreak = normalized.lastIndexOf(". ", hardEnd); - const candidate = Math.max(paragraphBreak, sentenceBreak); - if (candidate > start + Math.floor(maxChars * 0.5)) - end = candidate + (candidate === paragraphBreak ? 2 : 1); - } - const chunk = normalized.slice(start, end).trim(); - if (chunk) { - chunks.push({ - ordinal: chunks.length, - text: chunk, - startOffset: start, - endOffset: end - }); - } - if (end >= normalized.length) - break; - start = Math.max(0, end - overlapChars); +async function embedTexts(texts, options = {}) { + const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); + const parsed = parseModelRef(modelRef); + if (parsed.provider !== "openai") { + throw new Error(`Embedding provider ${parsed.provider} is not supported yet. Use openai:text-embedding-3-small.`); } - return chunks; -} -function estimateTokenCount(text) { - const words = text.trim().split(/\s+/).filter(Boolean).length; - return Math.max(1, Math.ceil(words * 1.25)); + const dimensions = options.dimensions ?? embeddingConfig(options.config).dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS; + if (options.fake) { + return { + provider: parsed.provider, + model: parsed.model, + dimensions, + vectors: texts.map((text) => deterministicVector(text, dimensions)), + usage: { input_tokens: texts.reduce((sum, text) => sum + Math.max(1, Math.ceil(text.split(/\s+/).filter(Boolean).length * 1.25)), 0) } + }; + } + const { embedMany } = await import("ai"); + const model = await openAiEmbeddingModel(parsed.model, options.config, options.env); + const result = await embedMany({ + model, + values: texts, + maxParallelCalls: options.maxParallelCalls ?? embeddingConfig(options.config).max_parallel_calls, + providerOptions: { + openai: { + dimensions + } + } + }); + const vectors = result.embeddings; + return { + provider: parsed.provider, + model: parsed.model, + dimensions: vectors[0]?.length ?? dimensions, + vectors, + usage: { input_tokens: result.usage?.tokens ?? 0 } + }; } -function deleteChunksForRevision(db, sourceRevisionId) { - const rows = db.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(sourceRevisionId); - for (const row of rows) { - db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); +function selectCandidateChunks(db, options) { + const baseQuery = `SELECT + c.id, + c.text, + c.token_count, + c.start_offset, + c.end_offset, + c.metadata_json, + c.source_revision_id, + sr.revision, + sr.hash, + s.uri AS source_uri, + s.kind AS source_kind + FROM chunks c + LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id + LEFT JOIN sources s ON s.id = sr.source_id + LEFT JOIN vector_index_entries v + ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? + WHERE v.id IS NULL`; + const suffix = ` + ORDER BY c.created_at ASC, c.ordinal ASC + LIMIT ?`; + if (options.sourceRevisionId) { + return db.query(`${baseQuery} AND c.source_revision_id = ?${suffix}`).all(options.provider, options.model, options.sourceRevisionId, options.limit); } - db.run("DELETE FROM chunks WHERE source_revision_id = ?", [sourceRevisionId]); - return rows.length; + return db.query(`${baseQuery}${suffix}`).all(options.provider, options.model, options.limit); } -function upsertSource(db, item, now) { - const sourceId = stableId("src", item.sourceUri); - db.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(uri) DO UPDATE SET - kind = excluded.kind, - title = excluded.title, - metadata_json = excluded.metadata_json, - acl_json = excluded.acl_json, - updated_at = excluded.updated_at`, [ - sourceId, - item.sourceUri, - item.kind, - item.title, - JSON.stringify(item.metadata), - JSON.stringify(item.acl ?? {}), - now, - item.updatedAt - ]); - const row = db.query("SELECT id FROM sources WHERE uri = ?").get(item.sourceUri); - if (!row) - throw new Error(`Failed to upsert source: ${item.sourceUri}`); - return row.id; +function provenanceForChunk(row) { + const metadata = parseJsonObject3(row.metadata_json); + const existing = metadata.provenance; + if (existing && typeof existing === "object" && !Array.isArray(existing)) + return existing; + return sourceProvenance({ + source_ref: metadataString2(metadata, ["source_ref"]), + source_uri: row.source_uri ?? metadataString2(metadata, ["source_uri"]), + source_kind: row.source_kind ?? metadataString2(metadata, ["source_kind"]), + source_revision_id: row.source_revision_id, + revision: row.revision ?? metadataString2(metadata, ["revision"]), + hash: row.hash ?? metadataString2(metadata, ["hash"]), + chunk_id: row.id, + start_offset: row.start_offset ?? metadataNumber2(metadata, ["start_offset"]), + end_offset: row.end_offset ?? metadataNumber2(metadata, ["end_offset"]), + status: metadataString2(metadata, ["status"]), + resolver: "open-files-read-only" + }); } -function upsertRevision(db, sourceId, item, now) { - const revisionId = stableId("rev", `${sourceId}\x00${item.revision}`); - db.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(source_id, revision) DO UPDATE SET - hash = excluded.hash, - extracted_text_uri = excluded.extracted_text_uri, - metadata_json = excluded.metadata_json`, [ - revisionId, - sourceId, - item.revision, - item.hash, - item.extractedTextUri, - JSON.stringify(item.metadata), - now - ]); - const row = db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(sourceId, item.revision); - if (!row) - throw new Error(`Failed to upsert source revision: ${item.sourceRef}`); - return row.id; +function upsertVectors(db, rows, embedding, now) { + const insertEmbedding = db.prepare(` + INSERT INTO chunk_embeddings (id, chunk_id, provider, model, dimensions, vector_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(chunk_id, provider, model) DO UPDATE SET + dimensions = excluded.dimensions, + vector_json = excluded.vector_json, + created_at = excluded.created_at + `); + const insertVector = db.prepare(` + INSERT INTO vector_index_entries ( + id, chunk_id, source_revision_id, provider, model, dimensions, vector_json, vector_norm, + source_uri, source_ref, revision, hash, start_offset, end_offset, token_count, status, + metadata_json, created_at, updated_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(chunk_id, provider, model) DO UPDATE SET + source_revision_id = excluded.source_revision_id, + dimensions = excluded.dimensions, + vector_json = excluded.vector_json, + vector_norm = excluded.vector_norm, + source_uri = excluded.source_uri, + source_ref = excluded.source_ref, + revision = excluded.revision, + hash = excluded.hash, + start_offset = excluded.start_offset, + end_offset = excluded.end_offset, + token_count = excluded.token_count, + status = excluded.status, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at + `); + const write = db.transaction(() => { + for (let index = 0;index < rows.length; index += 1) { + const row = rows[index]; + const vector = embedding.vectors[index]; + if (!vector) + continue; + const metadata = parseJsonObject3(row.metadata_json); + const provenance = provenanceForChunk(row); + const sourceRef = provenance.source_ref ?? metadataString2(metadata, ["source_ref"]); + const sourceUri = provenance.source_uri ?? row.source_uri ?? metadataString2(metadata, ["source_uri"]); + const revision = provenance.revision ?? row.revision ?? metadataString2(metadata, ["revision"]); + const hash = provenance.hash ?? row.hash ?? metadataString2(metadata, ["hash"]); + const status = provenance.status ?? metadataString2(metadata, ["status"]) ?? "active"; + const vectorJson = JSON.stringify(vector); + insertEmbedding.run(stableId3("emb", `${row.id}\x00${embedding.provider}\x00${embedding.model}`), row.id, embedding.provider, embedding.model, embedding.dimensions, vectorJson, now); + insertVector.run(stableId3("vec", `${row.id}\x00${embedding.provider}\x00${embedding.model}`), row.id, row.source_revision_id, embedding.provider, embedding.model, embedding.dimensions, vectorJson, vectorNorm(vector), sourceUri, sourceRef, revision, hash, provenance.start_offset, provenance.end_offset, row.token_count, status, JSON.stringify({ + ...metadata, + provenance, + embedded_at: now + }), now, now); + } + }); + write(); + return rows.length; } -function insertChunks(db, sourceRevisionId, item, now, maxChars, overlapChars, safetyPolicy) { - if (!item.text || item.status.toLowerCase() === "deleted") - return { chunksInserted: 0, redactions: 0 }; - const redacted = redactSecrets(item.text, safetyPolicy); - if (redacted.findings.length > 0) { - recordRedactionFindings(db, { - source_uri: item.sourceUri, - findings: redacted.findings, - metadata: { source_ref: item.sourceRef, revision: item.revision }, - created_at: now - }); - recordAuditEvent(db, { - event_type: "redaction", - action: "source_text_redact", - target_uri: item.sourceUri, - decision: "redacted", - metadata: { findings: redacted.findings.length, source_ref: item.sourceRef, revision: item.revision }, - created_at: now +async function indexKnowledgeEmbeddings(options) { + const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); + const parsed = parseModelRef(modelRef); + if (parsed.provider !== "openai") + throw new Error(`Embedding provider ${parsed.provider} is not supported yet.`); + const now = (options.now ?? new Date).toISOString(); + const limit = Math.max(1, Math.min(options.limit ?? 100, 1000)); + migrateKnowledgeDb(options.dbPath); + const readDb = openKnowledgeDb(options.dbPath); + let rows; + try { + rows = selectCandidateChunks(readDb, { + provider: parsed.provider, + model: parsed.model, + limit, + sourceRevisionId: options.sourceRevisionId }); + } finally { + readDb.close(); } - const chunks = chunkText(redacted.text, maxChars, overlapChars); - for (const chunk of chunks) { - const chunkId = stableId("chk", `${sourceRevisionId}\x00${chunk.ordinal}\x00${chunk.text}`); - const provenance = sourceProvenance({ - source_ref: item.sourceRef, - source_uri: item.sourceUri, - source_kind: item.kind, - source_revision_id: sourceRevisionId, - revision: item.revision, - hash: item.hash, - chunk_id: chunkId, - start_offset: chunk.startOffset, - end_offset: chunk.endOffset, - status: item.status, - resolver: "open-files-read-only" - }); - const metadata = withProvenance({ - source_ref: item.sourceRef, - source_uri: item.sourceUri, - source_kind: item.kind, - source_revision_id: sourceRevisionId, - revision: item.revision, - hash: item.hash, - status: item.status, - path: asString(item.raw.path) ?? null, - mime: asString(item.raw.mime) ?? asString(item.raw.content_type) ?? null, - size: asNumber(item.raw.size) ?? null - }, provenance); - db.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - chunkId, - sourceRevisionId, - "source", - chunk.ordinal, - chunk.text, - estimateTokenCount(chunk.text), - chunk.startOffset, - chunk.endOffset, - JSON.stringify(metadata), - now - ]); - db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [chunkId, chunk.text, item.title ?? "", item.sourceUri]); + if (rows.length === 0) { + return { + provider: parsed.provider, + model: parsed.model, + dimensions: options.dimensions ?? embeddingConfig(options.config).dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS, + chunks_seen: 0, + chunks_embedded: 0, + embeddings_upserted: 0, + vector_entries_upserted: 0, + usage: { input_tokens: 0 } + }; } - return { chunksInserted: chunks.length, redactions: redacted.findings.length }; -} -async function ingestOpenFilesManifest(options) { - const now = options.now ?? new Date; - if (options.safetyPolicy) - assertWriteAllowed(options.dbPath, options.safetyPolicy); - migrateKnowledgeDb(options.dbPath); - const text = await readManifestInput(options.input, options.config, options.safetyPolicy, options.maxInputBytes); - const items = parseManifestText(text); - const maxItems = options.maxItems ?? DEFAULT_MAX_MANIFEST_ITEMS; - if (items.length > maxItems) { - throw new Error(`Manifest contains too many items: ${items.length} exceeds ${maxItems} item limit.`); + const embedding = await embedTexts(rows.map((row) => row.text), options); + const writeDb = openKnowledgeDb(options.dbPath); + try { + const upserted = upsertVectors(writeDb, rows, embedding, now); + return { + provider: embedding.provider, + model: embedding.model, + dimensions: embedding.dimensions, + chunks_seen: rows.length, + chunks_embedded: rows.length, + embeddings_upserted: upserted, + vector_entries_upserted: upserted, + usage: embedding.usage + }; + } finally { + writeDb.close(); } - return ingestOpenFilesManifestItems({ - dbPath: options.dbPath, - items, - sourceLabel: options.input, - allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") === true, - safetyPolicy: options.safetyPolicy, - now, - maxChunkChars: options.maxChunkChars, - chunkOverlapChars: options.chunkOverlapChars, - maxItems: options.maxItems - }); } -async function ingestOpenFilesManifestItems(options) { - const now = (options.now ?? new Date).toISOString(); - const maxChunkChars = options.maxChunkChars ?? 4000; - const chunkOverlapChars = options.chunkOverlapChars ?? 200; - const maxItems = options.maxItems ?? DEFAULT_MAX_MANIFEST_ITEMS; - if (maxChunkChars < 500) - throw new Error("maxChunkChars must be at least 500."); - if (chunkOverlapChars < 0 || chunkOverlapChars >= maxChunkChars) - throw new Error("chunkOverlapChars must be less than maxChunkChars."); - if (options.items.length > maxItems) { - throw new Error(`Manifest contains too many items: ${options.items.length} exceeds ${maxItems} item limit.`); +function embeddingIndexStatus(dbPath) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const totalEmbeddings = db.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n ?? 0; + const totalVectorEntries = db.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n ?? 0; + const indexes = db.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at + FROM vector_index_entries + GROUP BY provider, model, dimensions + ORDER BY provider, model`).all(); + return { + total_embeddings: totalEmbeddings, + total_vector_entries: totalVectorEntries, + indexes + }; + } finally { + db.close(); } - if (options.safetyPolicy) - assertWriteAllowed(options.dbPath, options.safetyPolicy); +} +async function searchVectorIndex(options) { + const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); + const parsed = parseModelRef(modelRef); + const limit = Math.max(1, Math.min(options.limit ?? 10, 100)); + const embedded = await embedTexts([options.query], options); + const queryVector = embedded.vectors[0] ?? []; migrateKnowledgeDb(options.dbPath); const db = openKnowledgeDb(options.dbPath); try { - const result = db.transaction(() => { - const seenSources = new Set; - const seenRevisions = new Set; - let chunksInserted = 0; - let chunksDeleted = 0; - let redactions = 0; - let skipped = 0; - const preview2 = []; - recordAuditEvent(db, { - event_type: "source_read", - action: options.readAction ?? (options.sourceLabel.startsWith("s3://") ? "s3_manifest_read" : "local_manifest_read"), - target_uri: options.sourceLabel, - decision: "allow", - metadata: { items: options.items.length, read_only: true }, - created_at: now - }); - for (const raw of options.items) { - const item = normalizeManifestItem(raw, now, { allowFileSourceRefs: options.allowFileSourceRefs }); - if (preview2.length < DEFAULT_MANIFEST_PREVIEW_ITEMS) { - preview2.push({ - source_ref: item.sourceRef, - title: item.title, - status: item.status, - has_text: Boolean(item.text) - }); - } - const sourceId = upsertSource(db, item, now); - const revisionId = upsertRevision(db, sourceId, item, now); - seenSources.add(sourceId); - seenRevisions.add(revisionId); - if (item.text || item.status.toLowerCase() === "deleted") { - chunksDeleted += deleteChunksForRevision(db, revisionId); - } - const inserted = insertChunks(db, revisionId, item, now, maxChunkChars, chunkOverlapChars, options.safetyPolicy); - chunksInserted += inserted.chunksInserted; - redactions += inserted.redactions; - } - recordAuditEvent(db, { - event_type: "write", - action: "knowledge_manifest_ingest", - target_uri: options.dbPath, - decision: "allow", - metadata: { items: options.items.length, sources: seenSources.size, revisions: seenRevisions.size, chunks_inserted: chunksInserted, redactions }, - created_at: now - }); + const rows = db.query(`SELECT + v.chunk_id, + c.text, + v.vector_json, + v.vector_norm, + v.source_uri, + v.source_ref, + v.revision, + v.hash, + v.metadata_json + FROM vector_index_entries v + JOIN chunks c ON c.id = v.chunk_id + WHERE v.provider = ? AND v.model = ? AND v.status = 'active'`).all(parsed.provider, parsed.model); + const scored = rows.map((row) => { + const vector = JSON.parse(row.vector_json); + const metadata = parseJsonObject3(row.metadata_json); + const provenance = metadata.provenance && typeof metadata.provenance === "object" && !Array.isArray(metadata.provenance) ? metadata.provenance : null; return { - path: options.sourceLabel, - db_path: options.dbPath, - items_seen: options.items.length, - sources_upserted: seenSources.size, - revisions_upserted: seenRevisions.size, - chunks_inserted: chunksInserted, - chunks_deleted: chunksDeleted, - redactions, - skipped, - items_preview: preview2 + chunk_id: row.chunk_id, + score: cosineSimilarity(queryVector, vector, row.vector_norm), + text: row.text, + source_uri: row.source_uri, + source_ref: row.source_ref, + revision: row.revision, + hash: row.hash, + provenance }; - })(); - return result; + }).sort((a, b) => b.score - a.score).slice(0, limit); + return { + provider: parsed.provider, + model: parsed.model, + dimensions: embedded.dimensions, + query: options.query, + results: scored + }; } finally { db.close(); } } -// src/source-resolver.ts -function parseJsonObject(value) { +// src/search.ts +function parseJsonObject4(value) { if (!value) return {}; try { const parsed = JSON.parse(value); return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; - } -} -function metadataString(metadata, keys) { - for (const key of keys) { - const value = metadata[key]; - if (typeof value === "string" && value.length > 0) - return value; - } - return null; -} -function metadataNumber(metadata, keys) { - for (const key of keys) { - const value = metadata[key]; - if (typeof value === "number" && Number.isFinite(value)) - return value; - } - return null; -} -function assertPurposeAllowed(permissions, purpose) { - const mode2 = permissions.mode; - if (typeof mode2 === "string" && mode2 !== "read_only") { - throw new Error(`Source resolver denied ${purpose}. Permission mode is ${mode2}, expected read_only.`); - } - const denied = permissions.denied_purposes; - if (Array.isArray(denied) && denied.includes(purpose)) { - throw new Error(`Source resolver denied ${purpose}. Purpose is explicitly denied.`); - } - const allowed = permissions.allowed_purposes; - if (Array.isArray(allowed) && allowed.length > 0 && !allowed.includes(purpose)) { - throw new Error(`Source resolver denied ${purpose}. Allowed purposes: ${allowed.join(", ")}`); - } -} -function sourceRevisionRef(sourceUri, revision, fallback) { - if (!revision) - return fallback; - try { - const parsed = parseSourceRef(sourceUri); - if (parsed.kind === "open-files" && parsed.entity === "file") { - return `${sourceUri}/revision/${encodeURIComponent(revision.revision)}`; - } - } catch { - return fallback; - } - return fallback; -} -function selectSource(db, sourceUri, requestedRef) { - return db.query(`SELECT id, uri, kind, title, metadata_json, acl_json, updated_at - FROM sources - WHERE uri = ? OR uri = ? - ORDER BY CASE WHEN uri = ? THEN 0 ELSE 1 END - LIMIT 1`).get(sourceUri, requestedRef, sourceUri) ?? null; -} -function selectRevision(db, sourceId, revisionId) { - if (revisionId) { - return db.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at - FROM source_revisions - WHERE source_id = ? AND revision = ? - LIMIT 1`).get(sourceId, revisionId) ?? null; - } - return db.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at - FROM source_revisions - WHERE source_id = ? - ORDER BY created_at DESC, revision DESC - LIMIT 1`).get(sourceId) ?? null; -} -function countChunks(db, revisionId) { - if (!revisionId) - return 0; - const row = db.query("SELECT COUNT(*) AS n FROM chunks WHERE source_revision_id = ?").get(revisionId); - return row?.n ?? 0; -} -function selectChunks(db, revisionId, limit) { - if (!revisionId || limit <= 0) - return []; - return db.query(`SELECT id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json - FROM chunks - WHERE source_revision_id = ? - ORDER BY ordinal ASC - LIMIT ?`).all(revisionId, limit); -} -async function resolveOpenFilesSource(options) { - const purpose = options.purpose ?? "knowledge_answer"; - const limit = Math.max(0, Math.min(options.limit ?? 10, 100)); - const resolvedAt = (options.now ?? new Date).toISOString(); - const parsed = parseSourceRef(options.sourceRef); - const sourceUri = catalogSourceUriForRef(options.sourceRef, parsed); - const requestedRevision = revisionIdForSourceRef(options.sourceRef); - if (options.safetyPolicy) { - if (!options.safetyPolicy.readOnlySourceAccess) - throw new Error("Safety policy denied source resolution."); - assertWriteAllowed(options.dbPath, options.safetyPolicy); - } - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - try { - return db.transaction(() => { - const source = selectSource(db, sourceUri, options.sourceRef); - if (!source) { - recordAuditEvent(db, { - event_type: "source_read", - action: "open_files_resolve_missing", - target_uri: options.sourceRef, - decision: "allow", - metadata: { purpose, read_only: true, source_uri: sourceUri }, - created_at: resolvedAt - }); - return { - source_ref: options.sourceRef, - source_uri: sourceUri, - purpose, - read_only: true, - resolved: false, - resolver: { - name: "open-files-read-only", - mode: "local_catalog", - contract: "open-files-knowledge-source-v1" - }, - source: null, - revision: null, - content: { - mime: null, - size: null, - hash: null, - text_available: false, - chunks_total: 0, - chunks_returned: 0, - char_count_returned: 0, - extracted_text_ref: null, - bytes_available: false, - bytes_exposed: false - }, - chunks: [], - citations: [] - }; - } - const sourceMetadata = parseJsonObject(source.metadata_json); - const permissions = parseJsonObject(source.acl_json); - try { - assertPurposeAllowed(permissions, purpose); - } catch (error) { - recordAuditEvent(db, { - event_type: "source_read", - action: "open_files_resolve", - target_uri: options.sourceRef, - decision: "deny", - metadata: { - purpose, - read_only: true, - source_uri: source.uri, - error: error instanceof Error ? error.message : String(error) - }, - created_at: resolvedAt - }); - throw error; - } - const revision = selectRevision(db, source.id, requestedRevision); - const revisionMetadata = parseJsonObject(revision?.metadata_json); - const totalChunks = countChunks(db, revision?.id ?? null); - const rows = selectChunks(db, revision?.id ?? null, limit); - const effectiveSourceRef = sourceRevisionRef(source.uri, revision, options.sourceRef); - const chunks = rows.map((row) => { - const metadata = parseJsonObject(row.metadata_json); - const evidence = { - resolver: "open-files-read-only", - mode: "local_catalog", - purpose, - read_only: true, - source_ref: metadataString(metadata, ["source_ref"]) ?? effectiveSourceRef, - source_uri: source.uri, - source_revision_id: revision?.id ?? null, - revision: revision?.revision ?? null, - hash: revision?.hash ?? metadataString(metadata, ["hash"]), - chunk_id: row.id, - start_offset: row.start_offset, - end_offset: row.end_offset, - resolved_at: resolvedAt - }; - const provenance = sourceProvenance({ - source_ref: evidence.source_ref, - source_uri: evidence.source_uri, - source_kind: source.kind, - source_revision_id: evidence.source_revision_id, - revision: evidence.revision, - hash: evidence.hash, - chunk_id: row.id, - start_offset: row.start_offset, - end_offset: row.end_offset, - status: metadataString(metadata, ["status"]), - resolver: evidence.resolver - }); - return { - id: row.id, - kind: row.kind, - ordinal: row.ordinal, - text: row.text, - token_count: row.token_count, - start_offset: row.start_offset, - end_offset: row.end_offset, - metadata, - evidence, - provenance - }; - }); - const citations = chunks.map((chunk) => ({ - source_ref: chunk.evidence.source_ref, - source_uri: source.uri, - chunk_id: chunk.id, - quote: chunk.text.slice(0, 500), - start_offset: chunk.start_offset, - end_offset: chunk.end_offset, - evidence: chunk.evidence, - provenance: chunk.provenance - })); - recordAuditEvent(db, { - event_type: "source_read", - action: "open_files_resolve", - target_uri: options.sourceRef, - decision: "allow", - metadata: { - purpose, - read_only: true, - source_uri: source.uri, - revision: revision?.revision ?? null, - chunks_returned: chunks.length, - chunks_total: totalChunks - }, - created_at: resolvedAt - }); - const mime = metadataString(sourceMetadata, ["mime", "content_type"]) ?? metadataString(revisionMetadata, ["mime", "content_type"]); - const size = metadataNumber(sourceMetadata, ["size", "size_bytes"]) ?? metadataNumber(revisionMetadata, ["size", "size_bytes"]); - return { - source_ref: effectiveSourceRef, - source_uri: source.uri, - purpose, - read_only: true, - resolved: true, - resolver: { - name: "open-files-read-only", - mode: "local_catalog", - contract: "open-files-knowledge-source-v1" - }, - source: { - id: source.id, - uri: source.uri, - kind: source.kind, - title: source.title, - metadata: sourceMetadata, - permissions, - updated_at: source.updated_at - }, - revision: revision ? { - id: revision.id, - revision: revision.revision, - hash: revision.hash, - extracted_text_uri: revision.extracted_text_uri, - metadata: revisionMetadata, - created_at: revision.created_at, - reindex_required: revisionMetadata.reindex_required === true - } : null, - content: { - mime, - size, - hash: revision?.hash ?? metadataString(sourceMetadata, ["hash", "checksum", "sha256"]), - text_available: totalChunks > 0, - chunks_total: totalChunks, - chunks_returned: chunks.length, - char_count_returned: chunks.reduce((sum, chunk) => sum + chunk.text.length, 0), - extracted_text_ref: revision?.extracted_text_uri ?? metadataString(revisionMetadata, ["extracted_text_ref", "extracted_text_uri"]), - bytes_available: false, - bytes_exposed: false - }, - chunks, - citations - }; - })(); - } finally { - db.close(); + } catch { + return {}; } } - -// src/source-ingest.ts -function sha256Text(text) { - return `sha256:${createHash7("sha256").update(text).digest("hex")}`; +function metadataString3(metadata, keys) { + for (const key of keys) { + const value = metadata[key]; + if (typeof value === "string" && value.length > 0) + return value; + } + return null; } -function stripHtml(html) { - return html.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\s+\n/g, ` -`).replace(/\n\s+/g, ` -`).replace(/[ \t]{2,}/g, " ").trim(); +function metadataNumber3(metadata, keys) { + for (const key of keys) { + const value = metadata[key]; + if (typeof value === "number" && Number.isFinite(value)) + return value; + } + return null; } -async function readS3Text2(uri, config, safetyPolicy) { - const parsed = new URL(uri); - const bucket = parsed.hostname; - const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); - if (!bucket || !key) - throw new Error(`Invalid S3 source URI: ${uri}`); - if (safetyPolicy) - assertS3ReadAllowed(uri, safetyPolicy); - const [{ S3Client, GetObjectCommand }, { fromIni }] = await Promise.all([ - import("@aws-sdk/client-s3"), - import("@aws-sdk/credential-providers") - ]); - const s3Config = config?.storage.type === "s3" && config.storage.s3?.bucket === bucket ? config.storage.s3 : undefined; - const client = new S3Client({ - region: s3Config?.region, - credentials: s3Config?.profile ? fromIni({ profile: s3Config.profile }) : undefined, - maxAttempts: s3Config?.max_attempts - }); - const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key })); - if (!response.Body) - return ""; - return await response.Body.transformToString(); +function unique(values) { + return Array.from(new Set(values)); } -async function readWebText(uri, safetyPolicy) { - if (safetyPolicy) - assertWebSearchAllowed(safetyPolicy); - const response = await guardedFetch(uri, { - headers: { - accept: "text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5", - "user-agent": "@hasna/knowledge source-ingest" - } - }); - if (!response.ok) - throw new Error(`Web source read failed ${response.status}: ${uri}`); - const mime = response.headers.get("content-type"); - const body = await response.text(); - return { text: mime?.includes("html") ? stripHtml(body) : body, mime }; +function queryTerms(query2) { + const terms = query2.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []; + return unique(terms.filter((term) => term.length > 0)).slice(0, 16); } -function titleForRef(parsed) { - if (parsed.kind === "file") - return basename3(parsed.path); - if (parsed.kind === "s3") - return basename3(parsed.key); - if (parsed.kind === "web") - return basename3(new URL(parsed.url).pathname) || parsed.url; - return parsed.path ? basename3(parsed.path) : parsed.id; +function normalizeWords(raw) { + return raw.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []; } -async function readDirectSourceText(parsed, config, safetyPolicy) { - if (parsed.kind === "file") { - if (!existsSync7(parsed.path)) - throw new Error(`Source file not found: ${parsed.path}`); - const text = readFileSync8(parsed.path, "utf8"); - return { - text, - contentSource: "file", - title: titleForRef(parsed), - mime: "text/plain", - size: text.length, - hash: sha256Text(text), - revision: null, - extractedTextRef: null, - metadata: { path: parsed.path }, - permissions: { mode: "read_only" } - }; - } - if (parsed.kind === "s3") { - const text = await readS3Text2(parsed.uri, config, safetyPolicy); - return { - text, - contentSource: "s3", - title: titleForRef(parsed), - mime: "text/plain", - size: text.length, - hash: sha256Text(text), - revision: null, - extractedTextRef: null, - metadata: { bucket: parsed.bucket, key: parsed.key }, - permissions: { mode: "read_only" } - }; - } - if (parsed.kind === "web") { - const web = await readWebText(parsed.url, safetyPolicy); - return { - text: web.text, - contentSource: "web", - title: titleForRef(parsed), - mime: web.mime, - size: web.text.length, - hash: sha256Text(web.text), - revision: null, - extractedTextRef: null, - metadata: { url: parsed.url }, - permissions: { mode: "read_only" } - }; +function parseSearchQuery(query2) { + const tokens = []; + const segment = /"([^"]*)"|(\S+)/g; + let match; + let pendingNegate = false; + while ((match = segment.exec(query2)) !== null) { + if (match[1] !== undefined) { + const words2 = normalizeWords(match[1]); + if (words2.length > 0) { + tokens.push({ type: "phrase", value: words2.join(" "), negate: pendingNegate, prefix: false }); + } + pendingNegate = false; + continue; + } + let raw = match[2] ?? ""; + if (raw === "OR" || raw === "||" || raw === "|") { + tokens.push({ type: "or", value: "", negate: false, prefix: false }); + continue; + } + if (raw === "AND" || raw === "&&") + continue; + if (raw === "NOT") { + pendingNegate = true; + continue; + } + let negate = pendingNegate; + pendingNegate = false; + if (raw.startsWith("-") && raw.length > 1) { + negate = true; + raw = raw.slice(1); + } + let prefix = false; + if (raw.endsWith("*")) { + prefix = true; + raw = raw.slice(0, -1); + } + const words = normalizeWords(raw); + if (words.length === 0) + continue; + tokens.push({ + type: words.length > 1 ? "phrase" : "term", + value: words.join(" "), + negate, + prefix + }); } - throw new Error(`Direct source reading is not available for ${parsed.uri}`); + return tokens.slice(0, 24); } -async function readTextRef(uri, config, safetyPolicy) { - if (uri.startsWith("open-files://")) { - throw new Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://."); - } - const parsed = parseSourceRef(uri); - const direct = await readDirectSourceText(parsed, config, safetyPolicy); - return { text: direct.text, contentSource: "extracted_text_ref" }; +function tokenToFragment(token) { + if (token.type === "phrase") + return `"${token.value}"`; + return `"${token.value}"*`; } -async function readOpenFilesSourceText(options) { - const resolved = await resolveOpenFilesSource({ - dbPath: options.dbPath, - sourceRef: options.sourceRef, - purpose: options.purpose ?? "knowledge_index", - limit: 100, - safetyPolicy: options.safetyPolicy, - now: options.now +function buildFtsMatch(query2) { + const tokens = parseSearchQuery(query2); + const positives = tokens.filter((t) => t.type !== "or" && !t.negate); + if (positives.length === 0) + return { and: null, or: null }; + const compose = (defaultOp) => { + let expr = ""; + let pendingOr = false; + const negations = []; + for (const token of tokens) { + if (token.type === "or") { + pendingOr = true; + continue; + } + const fragment = tokenToFragment(token); + if (token.negate) { + negations.push(fragment); + continue; + } + if (expr.length === 0) + expr = fragment; + else + expr = pendingOr ? `${expr} OR ${fragment}` : `${expr} ${defaultOp} ${fragment}`; + pendingOr = false; + } + for (const negation of negations) + expr = `(${expr}) NOT ${negation}`; + return expr.length > 0 ? expr : null; + }; + const and = compose("AND"); + const or = compose("OR"); + return { and, or: or !== and ? or : null }; +} +function escapeLikeTerm(term) { + return term.replace(/[\\%_]/g, (char) => `\\${char}`); +} +function likeParams(terms, fieldsPerTerm) { + return terms.flatMap((term) => Array.from({ length: fieldsPerTerm }, () => `%${escapeLikeTerm(term)}%`)); +} +function scoreFromRank(rank, index) { + const rankScore = Number.isFinite(rank) ? 1 / (1 + Math.abs(rank)) : 0; + const orderScore = 1 / (1 + index); + return roundScore(Math.max(rankScore, orderScore)); +} +function catalogScore(haystack, terms) { + if (terms.length === 0) + return 0; + const matched = terms.filter((term) => haystack.includes(term)).length; + if (matched === 0) + return 0; + return roundScore(Math.min(0.85, 0.35 + matched / terms.length * 0.5)); +} +function semanticScore(score) { + return roundScore(Math.max(0, Math.min(1, (score + 1) / 2))); +} +function roundScore(score) { + return Number(score.toFixed(6)); +} +function combinedScore(scores, citation) { + const keyword = scores.keyword ?? 0; + const semantic = scores.semantic ?? 0; + const catalog = scores.catalog ?? 0; + const citationBoost = citation?.chunk_id ? 0.05 : 0; + return roundScore(Math.min(1, keyword * 0.55 + semantic * 0.4 + catalog * 0.35 + citationBoost)); +} +function existingProvenance(metadata) { + const provenance = metadata.provenance; + return provenance && typeof provenance === "object" && !Array.isArray(provenance) ? provenance : null; +} +function provenanceForChunk2(row) { + const metadata = parseJsonObject4(row.chunk_metadata_json); + const existing = existingProvenance(metadata); + if (existing) + return existing; + if (!row.source_revision_id && !row.source_uri) + return null; + return sourceProvenance({ + source_ref: metadataString3(metadata, ["source_ref"]), + source_uri: row.source_uri ?? metadataString3(metadata, ["source_uri"]), + source_kind: row.source_kind ?? metadataString3(metadata, ["source_kind"]), + source_revision_id: row.source_revision_id, + revision: row.revision ?? metadataString3(metadata, ["revision"]), + hash: row.hash ?? metadataString3(metadata, ["hash"]), + chunk_id: row.chunk_id, + start_offset: row.start_offset ?? metadataNumber3(metadata, ["start_offset"]), + end_offset: row.end_offset ?? metadataNumber3(metadata, ["end_offset"]), + status: metadataString3(metadata, ["status"]), + resolver: "open-files-read-only" }); - if (!resolved.resolved) { - throw new Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API."); - } - if (resolved.revision?.extracted_text_uri && !resolved.content.text_available) { - const textRef = await readTextRef(resolved.revision.extracted_text_uri, options.config, options.safetyPolicy); - return { - text: textRef.text, - contentSource: textRef.contentSource, - title: resolved.source?.title ?? null, - mime: resolved.content.mime, - size: textRef.text.length, - hash: resolved.revision.hash ?? sha256Text(textRef.text), - revision: resolved.revision.revision, - extractedTextRef: resolved.revision.extracted_text_uri, - metadata: resolved.source?.metadata ?? {}, - permissions: resolved.source?.permissions ?? { mode: "read_only" } - }; +} +function selectFtsChunks(db, ftsQuery, limit) { + if (!ftsQuery) + return []; + try { + return runFtsChunkQuery(db, ftsQuery, limit); + } catch { + return []; } - if (resolved.chunks.length === 0) { - throw new Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first."); +} +function runFtsChunkQuery(db, ftsQuery, limit) { + return db.query(`SELECT + chunks_fts.chunk_id, + c.kind AS chunk_kind, + c.wiki_page_id, + c.text, + c.token_count, + c.start_offset, + c.end_offset, + c.metadata_json AS chunk_metadata_json, + c.source_revision_id, + sr.revision, + sr.hash, + s.uri AS source_uri, + s.kind AS source_kind, + s.title AS source_title, + wp.path AS wiki_path, + wp.title AS wiki_title, + wp.artifact_uri AS wiki_artifact_uri, + wp.content_hash AS wiki_content_hash, + wp.status AS wiki_status, + wp.metadata_json AS wiki_metadata_json, + bm25(chunks_fts, 0.0, 1.0, 5.0, 3.0) AS rank + FROM chunks_fts + JOIN chunks c ON c.id = chunks_fts.chunk_id + LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id + LEFT JOIN sources s ON s.id = sr.source_id + LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id + WHERE chunks_fts MATCH ? + ORDER BY rank ASC + LIMIT ?`).all(ftsQuery, limit); +} +function catalogWhere(fields, terms) { + if (terms.length === 0) + return "1 = 0"; + const clauses = terms.map(() => `(${fields.map((field) => `lower(COALESCE(${field}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`); + return clauses.join(" OR "); +} +function selectWikiPages(db, terms, limit) { + const fields = ["path", "title", "artifact_uri", "metadata_json"]; + return db.query(`SELECT id, path, title, artifact_uri, content_hash, status, metadata_json + FROM wiki_pages + WHERE status = 'active' AND (${catalogWhere(fields, terms)}) + ORDER BY updated_at DESC + LIMIT ?`).all(...likeParams(terms, fields.length), limit); +} +function selectKnowledgeIndexes(db, terms, limit) { + const fields = ["kind", "name", "shard_key", "artifact_uri", "metadata_json"]; + return db.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json + FROM knowledge_indexes + WHERE ${catalogWhere(fields, terms)} + ORDER BY updated_at DESC + LIMIT ?`).all(...likeParams(terms, fields.length), limit); +} +function readLegacyItems(path) { + if (!path || !existsSync8(path)) + return []; + try { + const parsed = JSON.parse(readFileSync10(path, "utf8")); + if (!parsed || !Array.isArray(parsed.items)) + return []; + return parsed.items.filter((item) => { + return Boolean(item && typeof item === "object" && typeof item.id === "string" && typeof item.title === "string" && typeof item.content === "string"); + }); + } catch { + return []; } - const text = resolved.chunks.map((chunk) => chunk.text).join(` - -`); - return { - text, - contentSource: "catalog_chunks", - title: resolved.source?.title ?? null, - mime: resolved.content.mime, - size: text.length, - hash: resolved.revision?.hash ?? sha256Text(text), - revision: resolved.revision?.revision ?? null, - extractedTextRef: resolved.revision?.extracted_text_uri ?? null, - metadata: resolved.source?.metadata ?? {}, - permissions: resolved.source?.permissions ?? { mode: "read_only" } +} +function legacyItemHaystack(item) { + return [ + item.id, + item.short_id, + item.title, + item.content, + item.url, + ...item.tags ?? [] + ].filter((value) => typeof value === "string" && value.length > 0).join(" ").toLowerCase(); +} +function selectItems(items, terms, limit) { + if (terms.length === 0) + return []; + return items.filter((item) => item.archived !== true).map((item) => ({ item, haystack: legacyItemHaystack(item) })).filter(({ haystack }) => terms.some((term) => haystack.includes(term))).map(({ item, haystack }) => ({ item, score: catalogScore(haystack, terms) })).sort((a, b) => b.score - a.score || a.item.id.localeCompare(b.item.id)).slice(0, limit); +} +function selectLegacyItems(path, terms, limit) { + return selectItems(readLegacyItems(path), terms, limit); +} +function chunkResult(row, keywordScore) { + const metadata = parseJsonObject4(row.chunk_metadata_json); + const provenance = provenanceForChunk2(row); + const sourceRef = metadataString3(metadata, ["source_ref"]); + const sourceUri = row.source_uri ?? metadataString3(metadata, ["source_uri"]); + const isWiki = Boolean(row.wiki_page_id); + const result = { + kind: isWiki ? "wiki_chunk" : "source_chunk", + id: row.chunk_id, + title: isWiki ? row.wiki_title : row.source_title, + text: row.text, + score: 0, + scores: { keyword: keywordScore }, + source: sourceUri || sourceRef ? { + uri: sourceUri, + ref: sourceRef, + kind: row.source_kind ?? metadataString3(metadata, ["source_kind"]), + revision: row.revision ?? metadataString3(metadata, ["revision"]), + hash: row.hash ?? metadataString3(metadata, ["hash"]) + } : null, + citation: { + chunk_id: row.chunk_id, + start_offset: row.start_offset, + end_offset: row.end_offset + }, + artifact: isWiki ? { + uri: row.wiki_artifact_uri, + path: row.wiki_path, + hash: row.wiki_content_hash, + shard_key: row.wiki_path + } : null, + provenance, + reasons: ["keyword_match"] + }; + result.score = combinedScore(result.scores, result.citation); + return result; +} +function legacyItemResult(item, keywordScore) { + const uri = `knowledge://item/${encodeURIComponent(item.id)}`; + const result = { + kind: "legacy_item", + id: item.id, + title: item.title, + text: item.content, + score: 0, + scores: { keyword: keywordScore }, + source: { + uri, + ref: uri, + kind: "legacy_item", + revision: null, + hash: null + }, + citation: null, + artifact: null, + provenance: null, + reasons: ["legacy_note_match", "keyword_match"] + }; + result.score = combinedScore(result.scores, result.citation); + return result; +} +function wikiPageResult(row, terms) { + const metadata = parseJsonObject4(row.metadata_json); + const score = catalogScore(`${row.path} ${row.title} ${row.artifact_uri ?? ""} ${row.metadata_json}`.toLowerCase(), terms); + const result = { + kind: "wiki_page", + id: row.id, + title: row.title, + text: null, + score: 0, + scores: { catalog: score }, + source: null, + citation: null, + artifact: { + uri: row.artifact_uri, + path: row.path, + hash: row.content_hash, + shard_key: row.path + }, + provenance: existingProvenance(metadata), + reasons: ["wiki_catalog_match"] + }; + result.score = combinedScore(result.scores, result.citation); + return result; +} +function indexResult(row, terms) { + const metadata = parseJsonObject4(row.metadata_json); + const score = catalogScore(`${row.kind} ${row.name} ${row.shard_key ?? ""} ${row.artifact_uri ?? ""} ${row.metadata_json}`.toLowerCase(), terms); + const result = { + kind: "knowledge_index", + id: row.id, + title: row.name, + text: null, + score: 0, + scores: { catalog: score }, + source: null, + citation: null, + artifact: { + uri: row.artifact_uri, + path: metadataString3(metadata, ["artifact_key"]), + hash: metadataString3(metadata, ["content_hash"]), + shard_key: row.shard_key + }, + provenance: existingProvenance(metadata), + reasons: ["index_catalog_match"] + }; + result.score = combinedScore(result.scores, result.citation); + return result; +} +function mergeResult(results, entry) { + const key = `${entry.kind}:${entry.id}`; + const existing = results.get(key); + if (!existing) { + results.set(key, entry); + return; + } + existing.scores = { + keyword: Math.max(existing.scores.keyword ?? 0, entry.scores.keyword ?? 0) || undefined, + semantic: Math.max(existing.scores.semantic ?? 0, entry.scores.semantic ?? 0) || undefined, + catalog: Math.max(existing.scores.catalog ?? 0, entry.scores.catalog ?? 0) || undefined }; + existing.reasons = unique([...existing.reasons, ...entry.reasons]); + existing.text = existing.text ?? entry.text; + existing.title = existing.title ?? entry.title; + existing.source = existing.source ?? entry.source; + existing.citation = existing.citation ?? entry.citation; + existing.artifact = existing.artifact ?? entry.artifact; + existing.provenance = existing.provenance ?? entry.provenance; + existing.score = combinedScore(existing.scores, existing.citation); } -function manifestItemForSource(sourceRef, parsed, resolved, purpose) { - const hash = resolved.hash ?? sha256Text(resolved.text); - const metadata = { - ...redactPrivateRefs(resolved.metadata), - source_ref: sourceRef, - content_source: resolved.contentSource, - read_only: true - }; - const item = { - source_ref: sourceRef, - name: resolved.title ?? titleForRef(parsed), - mime: resolved.mime ?? "text/plain", - size: resolved.size ?? resolved.text.length, - hash, - revision: resolved.revision ?? hash, - status: "active", - updated_at: new Date().toISOString(), - permissions: { - mode: "read_only", - allowed_purposes: [purpose], - ...resolved.permissions - }, - metadata, - extracted_text_ref: resolved.extractedTextRef, - extracted_text: resolved.text +function sortResults(results) { + const kindOrder = { + source_chunk: 0, + wiki_chunk: 1, + legacy_item: 2, + wiki_page: 3, + knowledge_index: 4 }; - if (parsed.kind === "open-files") { - if (parsed.entity === "file") - item.file_id = parsed.id; - if (parsed.entity === "source") { - item.source_id = parsed.id; - item.path = parsed.path; + return results.sort((a, b) => { + if (b.score !== a.score) + return b.score - a.score; + return kindOrder[a.kind] - kindOrder[b.kind] || a.id.localeCompare(b.id); + }); +} +async function hybridSearch(options) { + const query2 = options.query.trim(); + if (!query2) + throw new Error("Search query is required."); + const limit = Math.max(1, Math.min(options.limit ?? 10, 100)); + const offset = Math.max(0, Math.floor(options.offset ?? 0)); + const window = offset + limit; + const terms = queryTerms(query2); + const ftsMatch = buildFtsMatch(query2); + const semanticEnabled = options.semantic === true || options.fake === true || Boolean(options.modelRef); + const warnings = []; + let semanticProvider = null; + let semanticModel = null; + let semanticDimensions = null; + let keywordCount = 0; + let catalogCount = 0; + let semanticCount = 0; + const merged = new Map; + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + try { + const ftsDepth = Math.max(window * 3, 20); + let ftsRows = selectFtsChunks(db, ftsMatch.and, ftsDepth); + if (ftsRows.length === 0 && ftsMatch.or) { + ftsRows = selectFtsChunks(db, ftsMatch.or, ftsDepth); } + keywordCount = ftsRows.length; + ftsRows.forEach((row, index) => mergeResult(merged, chunkResult(row, scoreFromRank(row.rank, index)))); + const wikiRows = selectWikiPages(db, terms, Math.max(window, 10)); + const indexRows = selectKnowledgeIndexes(db, terms, Math.max(window, 10)); + const legacyRows = selectLegacyItems(options.legacyStorePath, terms, Math.max(window, 10)); + catalogCount = wikiRows.length + indexRows.length; + keywordCount += legacyRows.length; + legacyRows.forEach(({ item, score }) => mergeResult(merged, legacyItemResult(item, score))); + wikiRows.forEach((row) => mergeResult(merged, wikiPageResult(row, terms))); + indexRows.forEach((row) => mergeResult(merged, indexResult(row, terms))); + } finally { + db.close(); } - if (parsed.kind === "file") - item.path = parsed.path; - if (parsed.kind === "s3") - item.path = parsed.key; - if (parsed.kind === "web") - item.url = parsed.url; - return item; + if (semanticEnabled) { + try { + const semantic = await searchVectorIndex({ + dbPath: options.dbPath, + query: query2, + limit: Math.max(window * 3, 20), + config: options.config, + env: options.env, + modelRef: options.modelRef, + dimensions: options.dimensions, + fake: options.fake, + batchSize: options.batchSize, + maxParallelCalls: options.maxParallelCalls + }); + semanticProvider = semantic.provider; + semanticModel = semantic.model; + semanticDimensions = semantic.dimensions; + semanticCount = semantic.results.length; + for (const row of semantic.results) { + const result = { + kind: "source_chunk", + id: row.chunk_id, + title: null, + text: row.text, + score: 0, + scores: { semantic: semanticScore(row.score) }, + source: { + uri: row.source_uri, + ref: row.source_ref, + kind: row.provenance?.source_kind ?? null, + revision: row.revision, + hash: row.hash + }, + citation: { + chunk_id: row.chunk_id, + start_offset: row.provenance?.start_offset ?? null, + end_offset: row.provenance?.end_offset ?? null + }, + artifact: null, + provenance: row.provenance, + reasons: ["semantic_match"] + }; + result.score = combinedScore(result.scores, result.citation); + mergeResult(merged, result); + } + } catch (error) { + warnings.push(`semantic_search_failed: ${error instanceof Error ? error.message : String(error)}`); + } + } + const ranked = sortResults(Array.from(merged.values())); + const results = ranked.slice(offset, offset + limit); + return { + query: query2, + limit, + offset, + mode: { + keyword: true, + catalog: true, + semantic: semanticEnabled + }, + semantic_provider: semanticProvider, + semantic_model: semanticModel, + semantic_dimensions: semanticDimensions, + counts: { + keyword_results: keywordCount, + catalog_results: catalogCount, + semantic_results: semanticCount, + merged_results: results.length + }, + warnings, + results + }; } -async function ingestSourceRef(options) { - const purpose = options.purpose ?? "knowledge_index"; - assertNoPrivateRefs(options.sourceRef, { - allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") !== false - }); - const parsed = parseSourceRef(options.sourceRef); - const resolved = parsed.kind === "open-files" ? await readOpenFilesSourceText(options) : await readDirectSourceText(parsed, options.config, options.safetyPolicy); - const item = manifestItemForSource(options.sourceRef, parsed, resolved, purpose); - const result = await ingestOpenFilesManifestItems({ - dbPath: options.dbPath, - items: [item], - sourceLabel: options.sourceRef, - readAction: "source_ref_ingest_read", - allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") !== false, - safetyPolicy: options.safetyPolicy, - now: options.now - }); +async function hybridSearchLegacyStore(options) { + return hybridSearchItems(readLegacyItems(options.legacyStorePath), options, ["knowledge_db_missing"]); +} +async function hybridSearchItems(items, options, baseWarnings = []) { + const query2 = options.query.trim(); + if (!query2) + throw new Error("Search query is required."); + const limit = Math.max(1, Math.min(options.limit ?? 10, 100)); + const offset = Math.max(0, Math.floor(options.offset ?? 0)); + const terms = queryTerms(query2); + const semanticEnabled = options.semantic === true || options.fake === true || Boolean(options.modelRef); + const merged = new Map; + const itemRows = selectItems(items, terms, Math.max(offset + limit, 10)); + itemRows.forEach(({ item, score }) => mergeResult(merged, legacyItemResult(item, score))); + const warnings = [...baseWarnings]; + if (semanticEnabled) + warnings.push("semantic_search_requires_local_catalog"); + const results = sortResults(Array.from(merged.values())).slice(offset, offset + limit); return { - ...result, - source_ref: options.sourceRef, - content_source: resolved.contentSource, - read_only: true, - hash: String(item.hash) + query: query2, + limit, + offset, + mode: { + keyword: true, + catalog: true, + semantic: semanticEnabled + }, + semantic_provider: null, + semantic_model: null, + semantic_dimensions: null, + counts: { + keyword_results: itemRows.length, + catalog_results: 0, + semantic_results: 0, + merged_results: results.length + }, + warnings, + results }; } -// src/app-wiki.ts -function stableId2(prefix, value) { - return `${prefix}_${createHash8("sha256").update(value).digest("hex").slice(0, 20)}`; +// src/retrieval.ts +function stableId4(prefix, value) { + return `${prefix}_${createHash10("sha256").update(value).digest("hex").slice(0, 20)}`; } -function slugify(value) { - const slug = value.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80); - return slug || "note"; +function normalizeQuery(query2) { + return query2.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase(); } -function parseJsonObject2(value) { - if (!value) - return {}; - try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; - } +function queryTerms2(query2) { + return Array.from(new Set(normalizeQuery(query2).match(/[\p{L}\p{N}_]+/gu) ?? [])).slice(0, 16); } -function estimateTokenCount2(text) { - const words = text.trim().split(/\s+/).filter(Boolean).length; - return Math.max(1, Math.ceil(words * 1.25)); +function textForResult(result) { + return [result.title, result.text].filter(Boolean).join(" ").toLowerCase(); } -function uniqueStrings(values) { - return Array.from(new Set((values ?? []).map((value) => value.trim()).filter(Boolean))); +function exactScore(result, terms) { + if (terms.length === 0) + return 0; + const text = textForResult(result); + const matched = terms.filter((term) => text.includes(term)).length; + return Number((matched / terms.length).toFixed(6)); } -function normalizeNotePath(input) { - const raw = input.path?.trim() || `wiki/notes/${slugify(input.title)}.md`; - const normalized = raw.replace(/\\/g, "/"); - if (!normalized.startsWith("wiki/notes/") || !normalized.endsWith(".md")) { - throw new Error("App wiki note paths must be relative wiki/notes/*.md artifact keys."); - } - if (normalized.startsWith("/") || normalized.split("/").some((segment) => segment === ".." || segment === ".")) { - throw new Error(`Invalid app wiki note path: ${raw}`); - } - return normalized; +function hasReadOnlyProvenance(provenance) { + if (!provenance) + return true; + if ("read_only" in provenance) + return provenance.read_only === true; + if ("read_only_sources" in provenance) + return provenance.read_only_sources === true; + return true; } -function noteBody(input) { - const sections = [ - `# ${input.title}`, - "", - input.content.trim(), - "", - `Updated: ${input.now}` - ]; - if (input.tags.length > 0) { - sections.push("", "Tags:", ...input.tags.map((tag) => `- ${tag}`)); - } - if (input.sourceRefs.length > 0) { - sections.push("", "Source refs:", ...input.sourceRefs.map((ref) => `- ${ref}`)); - } - sections.push(""); - return sections.join(` -`); +function isStale(provenance) { + if (!provenance) + return false; + if ("stale" in provenance && provenance.stale) + return true; + if ("status" in provenance) + return isStaleStatus(provenance.status); + return false; } -async function writeArtifact(store, entry) { - const written = await store.put(entry); +function freshnessScore(result) { + if (isStale(result.provenance)) + return 0; + if (result.source?.hash || result.source?.revision) + return 1; + if (result.artifact?.hash) + return 0.85; + if (result.provenance && "source_refs" in result.provenance && result.provenance.source_refs.length > 0) + return 0.75; + return 0.55; +} +function citationScore(result) { + if (result.citation?.chunk_id && (result.source?.uri || result.artifact?.uri)) + return 1; + if (result.provenance && "citation_required" in result.provenance && result.provenance.citation_required) + return 0.75; + if (result.artifact?.uri) + return 0.65; + return 0.35; +} +function authorityScore(result) { + if (result.kind === "wiki_chunk") + return 0.85; + if (result.kind === "source_chunk") + return 0.8; + if (result.kind === "legacy_item") + return 0.6; + if (result.kind === "wiki_page") + return 0.65; + return 0.55; +} +function rerank(result, terms) { + const scores = { + base_score: result.score, + exact_score: exactScore(result, terms), + citation_score: citationScore(result), + freshness_score: freshnessScore(result), + authority_score: authorityScore(result) + }; + const final = Math.min(1, scores.base_score * 0.65 + scores.exact_score * 0.1 + scores.citation_score * 0.1 + scores.freshness_score * 0.1 + scores.authority_score * 0.05); + const reasons = new Set(result.reasons); + if (scores.exact_score > 0.5) + reasons.add("exact_term"); + if (scores.citation_score >= 0.75) + reasons.add("cited_source"); + if (scores.freshness_score >= 0.85) + reasons.add("fresh_source"); return { - key: written.key, - uri: written.uri, - kind: entry.key.startsWith("logs/") ? "log" : "wiki_page", - content_type: entry.content_type, - modified_at: written.modified_at, - ...hashArtifactBody(entry.body), - metadata: { - ...entry.metadata ?? {} + ...result, + score: Number(final.toFixed(6)), + reasons: Array.from(reasons), + rerank: { + ...scores, + final_score: Number(final.toFixed(6)) } }; } -async function appendLog(store, event, now) { - const year = String(now.getUTCFullYear()); - const month = String(now.getUTCMonth() + 1).padStart(2, "0"); - const day = String(now.getUTCDate()).padStart(2, "0"); - const key = `logs/${year}/${month}/${day}.jsonl`; - let existing = ""; +function quoteFor(result, maxChars) { + const source = result.text ?? result.title; + if (!source) + return null; + const normalized = source.replace(/\s+/g, " ").trim(); + return normalized.length <= maxChars ? normalized : `${normalized.slice(0, Math.max(0, maxChars - 1)).trim()}...`; +} +function citationFor(result) { + const id = stableId4("cite", `${result.kind}\x00${result.id}\x00${result.source?.uri ?? ""}\x00${result.artifact?.uri ?? ""}`); + return { + id, + result_id: result.id, + kind: result.kind, + source_uri: result.source?.uri ?? null, + source_ref: result.source?.ref ?? null, + artifact_uri: result.artifact?.uri ?? null, + artifact_path: result.artifact?.path ?? null, + revision: result.source?.revision ?? null, + hash: result.source?.hash ?? result.artifact?.hash ?? null, + chunk_id: result.citation?.chunk_id ?? null, + start_offset: result.citation?.start_offset ?? null, + end_offset: result.citation?.end_offset ?? null, + quote: quoteFor(result, 500), + provenance: result.provenance + }; +} +function excerptFor(result, citation, contextChars) { + const text = quoteFor(result, contextChars); + if (!text) + return null; + return { + id: stableId4("excerpt", `${result.kind}\x00${result.id}`), + result_id: result.id, + citation_id: citation.id, + kind: result.kind, + text, + score: result.score + }; +} +function placeholders(values) { + return values.map(() => "?").join(", "); +} +function loadGraphEvidence(dbPath, results) { + const chunkIds = results.map((result) => result.citation?.chunk_id).filter((id) => Boolean(id)); + const wikiPageIds = results.filter((result) => result.kind === "wiki_page").map((result) => result.id); + const citations = []; + const backlinks = []; + if (chunkIds.length === 0 && wikiPageIds.length === 0) + return { citations, backlinks }; + const db = openKnowledgeDb(dbPath); try { - existing = await store.getText(key); - } catch { - existing = ""; + if (chunkIds.length > 0) { + citations.push(...db.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset + FROM citations + WHERE chunk_id IN (${placeholders(chunkIds)}) + ORDER BY created_at DESC + LIMIT 50`).all(...chunkIds)); + } + if (wikiPageIds.length > 0) { + citations.push(...db.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset + FROM citations + WHERE wiki_page_id IN (${placeholders(wikiPageIds)}) + ORDER BY created_at DESC + LIMIT 50`).all(...wikiPageIds)); + backlinks.push(...db.query(`SELECT from_page_id, to_page_id, label + FROM wiki_backlinks + WHERE from_page_id IN (${placeholders(wikiPageIds)}) OR to_page_id IN (${placeholders(wikiPageIds)}) + LIMIT 50`).all(...wikiPageIds, ...wikiPageIds)); + } + } finally { + db.close(); } - return writeArtifact(store, { - key, - body: `${existing}${JSON.stringify(event)} -`, - content_type: "application/x-ndjson", - metadata: { - provenance: generatedArtifactProvenance({ - generated_from: String(event.event ?? "app_wiki_log"), - artifact_key: key - }) + return { citations, backlinks }; +} +function retrieveKnowledgeContextFromSearch(search, options = {}) { + const contextChars = Math.max(200, Math.min(options.contextChars ?? 1200, 4000)); + const terms = queryTerms2(search.query); + const warnings = [...search.warnings]; + const permissionNotes = new Set; + const freshnessNotes = new Set; + const filtered = search.results.filter((result) => { + if (!hasReadOnlyProvenance(result.provenance)) { + warnings.push(`permission_filtered: ${result.kind}:${result.id}`); + permissionNotes.add("Dropped a result because provenance was not read-only."); + return false; + } + if (isStale(result.provenance)) { + warnings.push(`stale_filtered: ${result.kind}:${result.id}`); + freshnessNotes.add("Dropped a stale result whose source status requires reindexing."); + return false; + } + return true; + }); + const results = filtered.map((result) => rerank(result, terms)).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, search.limit); + const citations = results.map(citationFor); + const excerpts = results.map((result, index) => excerptFor(result, citations[index], contextChars)).filter((entry) => Boolean(entry)); + for (const result of results) { + if (result.provenance && "read_only" in result.provenance && result.provenance.read_only) { + permissionNotes.add("All source-backed excerpts are read-only and citation-required."); + } + if (result.rerank.freshness_score >= 0.85) { + freshnessNotes.add("Fresh source revision/hash or artifact hash is present for top context."); + } + } + return { + query: search.query, + normalized_query: normalizeQuery(search.query), + created_at: new Date().toISOString(), + mode: search.mode, + warnings, + search_counts: search.counts, + results, + citations, + excerpts, + graph: options.dbPath ? loadGraphEvidence(options.dbPath, results) : { citations: [], backlinks: [] }, + notes: { + permissions: Array.from(permissionNotes), + freshness: Array.from(freshnessNotes) } + }; +} +async function retrieveKnowledgeContext(options) { + const search = await hybridSearch(options); + return retrieveKnowledgeContextFromSearch(search, { + dbPath: options.dbPath, + contextChars: options.contextChars }); } -function noteMetadata(input) { - return { - ...redactPrivateRefs(input.metadata ?? {}), - app_wiki: true, - note: true, - artifact_key: input.path, - tags: input.tags, - source_refs: input.sourceRefs, - provenance: input.provenance - }; +async function retrieveKnowledgeContextFromItems(items, options) { + const search = await hybridSearchItems(items, options); + return retrieveKnowledgeContextFromSearch(search, { contextChars: options.contextChars }); } -function noteRecord(row) { - const metadata = parseJsonObject2(row.metadata_json); - return { - id: row.id, - path: row.path, - title: row.title, - artifact_uri: row.artifact_uri, - content_hash: row.content_hash, - tags: Array.isArray(metadata.tags) ? metadata.tags.filter((tag) => typeof tag === "string") : [], - source_refs: Array.isArray(metadata.source_refs) ? metadata.source_refs.filter((ref) => typeof ref === "string") : [], - created_at: row.created_at, - updated_at: row.updated_at - }; + +// src/agent.ts +function estimateTokens(text) { + const words = text.trim().split(/\s+/).filter(Boolean).length; + return Math.max(1, Math.ceil(words * 1.25)); } -function sourceCitationRows(db, sourceRefs) { - return sourceRefs.map((sourceRef) => { - const row = db.query(`SELECT - s.uri AS source_uri, - c.id AS chunk_id, - c.text, - c.start_offset, - c.end_offset, - sr.revision, - sr.hash, - c.metadata_json - FROM sources s - LEFT JOIN source_revisions sr ON sr.source_id = s.id - LEFT JOIN chunks c ON c.source_revision_id = sr.id - WHERE s.uri = ? OR s.metadata_json LIKE ? - ORDER BY sr.created_at DESC, c.ordinal ASC - LIMIT 1`).get(sourceRef, `%${sourceRef}%`); - const metadata = parseJsonObject2(row?.metadata_json); - return { - source_ref: sourceRef, - source_uri: row?.source_uri ?? sourceRef, - chunk_id: row?.chunk_id ?? null, - quote: row?.text ? row.text.replace(/\s+/g, " ").slice(0, 240) : null, - start_offset: row?.start_offset ?? null, - end_offset: row?.end_offset ?? null, - metadata: { - source_ref: sourceRef, - revision: row?.revision ?? metadata.revision, - hash: row?.hash ?? metadata.hash - } - }; - }); +function citationLabel(index) { + return `C${index + 1}`; } -function replaceNoteCitations(db, pageId, sourceRefs, now) { - db.run("DELETE FROM citations WHERE wiki_page_id = ?", [pageId]); - const citations = sourceCitationRows(db, sourceRefs); - for (const citation of citations) { - db.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - stableId2("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID4()}`), - pageId, - citation.chunk_id, - citation.source_uri, - citation.quote, - citation.start_offset, - citation.end_offset, - JSON.stringify(citation.metadata), - now - ]); +function localAnswer(prompt, context) { + if (context.excerpts.length === 0) { + return `No indexed knowledge matched the prompt: ${prompt}`; } - return citations.length; + const lines = [ + `Found ${context.excerpts.length} relevant knowledge excerpt(s) for: ${prompt}`, + "", + ...context.excerpts.slice(0, 5).map((excerpt, index) => { + const citation = context.citations.find((entry) => entry.id === excerpt.citation_id); + const ref = citation?.source_ref ?? citation?.source_uri ?? citation?.artifact_path ?? citation?.artifact_uri ?? "unknown source"; + return `[${citationLabel(index)}] ${excerpt.text} (${ref})`; + }) + ]; + return lines.join(` +`); } -function upsertNoteIndex(db, input) { - db.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(kind, name, shard_key) DO UPDATE SET - artifact_uri = excluded.artifact_uri, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`, [ - stableId2("idx", `app-wiki-note\x00${input.path}`), - "app_wiki_note", - input.title, - input.artifactUri, - input.path, - JSON.stringify({ - artifact_key: input.path, - content_hash: input.contentHash, - tags: input.tags, - source_refs: input.sourceRefs - }), - input.now, - input.now - ]); +function promptForModel(prompt, context) { + const citations = context.citations.map((citation, index) => ({ + id: citationLabel(index), + source_ref: citation.source_ref, + source_uri: citation.source_uri, + artifact_path: citation.artifact_path, + revision: citation.revision, + hash: citation.hash, + quote: citation.quote + })); + const excerpts = context.excerpts.map((excerpt, index) => ({ + id: citationLabel(index), + kind: excerpt.kind, + text: excerpt.text, + score: excerpt.score + })); + return [ + `Prompt: ${prompt}`, + "", + "Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.", + "", + `Context excerpts: +${JSON.stringify(excerpts, null, 2)}`, + "", + `Citations: +${JSON.stringify(citations, null, 2)}` + ].join(` +`); } -function upsertNotePage(db, input) { - db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(path) DO UPDATE SET - title = excluded.title, - artifact_uri = excluded.artifact_uri, - content_hash = excluded.content_hash, - status = excluded.status, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`, [ - input.pageId, - input.path, - input.title, - input.artifactUri, - input.contentHash, - "active", - JSON.stringify(input.metadata), - input.now, - input.now - ]); - const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(input.pageId); - for (const row of existing) - db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); - db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [input.pageId]); - const chunkId = stableId2("chk", `${input.pageId}\x00${input.contentHash}`); - db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - chunkId, - input.pageId, - "wiki", - 0, - input.body, - estimateTokenCount2(input.body), - 0, - input.body.length, - JSON.stringify({ - ...input.metadata, - artifact_uri: input.artifactUri, - content_hash: input.contentHash - }), - input.now - ]); - db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [ - chunkId, - input.body, - input.title, - input.artifactUri - ]); +function proposedUpdates(prompt, context) { + if (context.citations.length === 0) + return []; + return [{ + kind: "answer_note", + title: prompt.length > 80 ? `${prompt.slice(0, 77)}...` : prompt, + citations: context.citations.map((citation) => citation.id), + requires_approval: true + }]; } -function assertAppWikiWriteAllowed(options) { - if (options.scope === "global" && options.allowGlobal !== true) { - throw new Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global."); - } - if (options.workspace.home.includes("/.husna/") || options.workspace.home.endsWith("/.husna")) { - throw new Error(`Refusing app-wiki writes to legacy .husna path: ${options.workspace.home}`); - } - if (options.workspace.home.includes("/.hasna/apps/knowledge")) { - throw new Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${options.workspace.home}`); +function insertRun(dbPath, input) { + const db = openKnowledgeDb(dbPath); + try { + db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + input.runId, + "knowledge-prompt", + input.prompt, + input.status, + input.provider, + input.model, + JSON.stringify(input.metadata), + input.now, + input.now + ]); + } finally { + db.close(); } - if (options.safetyPolicy) - assertWriteAllowed(options.workspace.knowledgeDbPath, options.safetyPolicy); } -async function initAppWikiScope(options) { - assertAppWikiWriteAllowed(options); - const migration = migrateKnowledgeDb(options.workspace.knowledgeDbPath); - const db = openKnowledgeDb(options.workspace.knowledgeDbPath); +function addRunEvent(dbPath, input) { + const db = openKnowledgeDb(dbPath); try { - recordAuditEvent(db, { - event_type: "write", - action: "app_wiki_init", - target_uri: options.workspace.home, - decision: "allow", - metadata: { - scope: options.scope, - store_type: options.store.type, - app_path: ".hasna/knowledge" - }, - created_at: (options.now ?? new Date).toISOString() - }); + db.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, [ + `evt_${randomUUID6()}`, + input.runId, + input.level, + input.event, + JSON.stringify(input.metadata), + input.now + ]); } finally { db.close(); } - return { - ok: true, - scope: options.scope, - workspace_home: options.workspace.home, - knowledge_db_path: options.workspace.knowledgeDbPath, - schema_version: migration.schema_version, - store_type: options.store.type, - global_write_allowed: options.scope === "global" && options.allowGlobal === true, - message: `Initialized app wiki scope at ${options.workspace.home}` - }; } -async function writeAppWikiNote(options) { - assertAppWikiWriteAllowed(options); - const nowDate = options.now ?? new Date; - const now = nowDate.toISOString(); - const tags = uniqueStrings(options.tags); - const sourceRefs = uniqueStrings(options.sourceRefs); - for (const sourceRef of sourceRefs) { - assertNoPrivateRefs(sourceRef, { allowFileSourceRefs: options.safetyPolicy?.readOnlySourceAccess === true }); - } - const path = normalizeNotePath(options); - const body = noteBody({ - title: options.title, - content: options.content, - tags, - sourceRefs, - now - }); - const provenance = generatedArtifactProvenance({ - generated_from: "app_wiki_note", - artifact_key: path, - source_refs: sourceRefs - }); - const artifact = await writeArtifact(options.store, { - key: path, - body, - content_type: "text/markdown", - metadata: { - generated_from: "app_wiki_note", - provenance, - scope: options.scope, - tags: tags.join(","), - source_refs: sourceRefs.join(",") - } - }); - const log = await appendLog(options.store, { - ts: now, - event: "app_wiki_note_written", - page_key: path, - source_refs: sourceRefs, - tags - }, nowDate); - migrateKnowledgeDb(options.workspace.knowledgeDbPath); - const db = openKnowledgeDb(options.workspace.knowledgeDbPath); +function updateRun(dbPath, input) { + const db = openKnowledgeDb(dbPath); try { - const pageId = stableId2("wiki", path); - const metadata = noteMetadata({ - path, - tags, - sourceRefs, - provenance, - metadata: options.metadata - }); - recordStorageObjects(db, [artifact, log], nowDate); - upsertNotePage(db, { - pageId, - path, - title: options.title, - artifactUri: artifact.uri, - contentHash: artifact.hash ?? "", - body, - metadata, - now - }); - const citationsWritten = replaceNoteCitations(db, pageId, sourceRefs, now); - upsertNoteIndex(db, { - title: options.title, - path, - artifactUri: artifact.uri, - contentHash: artifact.hash ?? "", - tags, - sourceRefs, - now - }); - recordAuditEvent(db, { - event_type: "write", - action: "app_wiki_note_write", - target_uri: artifact.uri, - decision: "allow", - metadata: { - scope: options.scope, - path, - source_refs: sourceRefs, - tags - }, - created_at: now - }); - const row = db.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(pageId); - if (!row) - throw new Error(`Failed to write app wiki note: ${path}`); - return { - ok: true, - scope: options.scope, - workspace_home: options.workspace.home, - note: noteRecord(row), - artifact_uri: artifact.uri, - content_hash: artifact.hash ?? "", - citations_written: citationsWritten, - chunks_written: 1, - storage_objects_written: 2, - message: `Wrote app wiki note ${path}` - }; + db.run(`UPDATE runs + SET status = ?, provider = ?, model = ?, metadata_json = ?, updated_at = ? + WHERE id = ?`, [ + input.status, + input.provider, + input.model, + JSON.stringify(input.metadata), + input.now, + input.runId + ]); } finally { db.close(); } } -function listAppWikiNotes(options) { - const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); - if (!options.dbPath) - return []; - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); +function recordUsage(dbPath, runId, usage, provider, model, now, metadata = {}) { + const db = openKnowledgeDb(dbPath); try { - return db.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at - FROM wiki_pages - WHERE status = 'active' - AND path LIKE 'wiki/notes/%' - AND metadata_json LIKE '%"app_wiki":true%' - ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(limit).map(noteRecord); + recordProviderUsage(db, { + run_id: runId, + provider, + model, + input_tokens: usage.input_tokens, + output_tokens: usage.output_tokens, + cost_usd: usage.cost_usd, + metadata, + created_at: now + }); } finally { db.close(); } } -async function getAppWikiNote(options) { +async function runKnowledgePrompt(options) { + const prompt = options.prompt.trim(); + if (!prompt) + throw new Error("Knowledge prompt is required."); + const now = (options.now ?? new Date).toISOString(); + const runId = `run_${randomUUID6()}`; + const modelRef = resolveModelRef(options.modelRef ?? "default", options.config); + const parsed = parseModelRef(modelRef); migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - try { - const row = db.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at - FROM wiki_pages - WHERE (id = ? OR path = ?) - AND path LIKE 'wiki/notes/%' - AND metadata_json LIKE '%"app_wiki":true%'`).get(options.id, options.id); - if (!row) - return null; - const citations = db.query(`SELECT id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at - FROM citations - WHERE wiki_page_id = ? - ORDER BY created_at ASC`).all(row.id).map((citation) => ({ - ...citation, - metadata: parseJsonObject2(citation.metadata_json), - metadata_json: undefined - })); - let content = null; - if (options.includeContent !== false) { - try { - content = await options.store.getText(row.path); - } catch { - content = null; + insertRun(options.dbPath, { + runId, + prompt, + status: options.generate ? "running" : "dry_run", + provider: options.generate ? parsed.provider : "local", + model: options.generate ? parsed.model : "context-draft", + metadata: { + semantic: options.semantic === true || options.fake === true || Boolean(options.modelRef), + approve_write: options.approveWrite === true, + generated: options.generate === true + }, + now + }); + const { prompt: _prompt, generate: _generate, approveWrite: _approveWrite, now: _now, ...retrievalOptions } = options; + const context = await retrieveKnowledgeContext({ + ...retrievalOptions, + query: prompt + }); + addRunEvent(options.dbPath, { + runId, + level: "info", + event: "context_retrieved", + metadata: { + results: context.results.length, + citations: context.citations.length, + warnings: context.warnings + }, + now + }); + let answer = localAnswer(prompt, context); + let generated = false; + let provider = "local"; + let model = "context-draft"; + let usage = { + input_tokens: estimateTokens(prompt) + context.excerpts.reduce((sum, excerpt) => sum + estimateTokens(excerpt.text), 0), + output_tokens: estimateTokens(answer), + cost_usd: 0 + }; + const warnings = [...context.warnings]; + if (options.generate) { + try { + if (options.fake) { + generated = true; + provider = parsed.provider; + model = parsed.model; + answer = `Fake generated answer for: ${prompt} + +${answer}`; + } else { + const { generateText } = await import("ai"); + const languageModel = await languageModelFor(modelRef, { + config: options.config, + env: options.env + }); + const result = await generateText({ + model: languageModel, + system: "You answer company knowledge-base prompts using only provided context and citation ids.", + prompt: promptForModel(prompt, context) + }); + generated = true; + provider = parsed.provider; + model = parsed.model; + answer = result.text; + const normalized = normalizeAiSdkUsage({ + provider, + model, + usage: result.usage, + providerMetadata: result.providerMetadata + }); + usage = { + input_tokens: normalized.input_tokens, + output_tokens: normalized.output_tokens, + cost_usd: normalized.cost_usd + }; } + } catch (error) { + addRunEvent(options.dbPath, { + runId, + level: "error", + event: "answer_generation_failed", + metadata: { message: error instanceof Error ? error.message : String(error) }, + now + }); + updateRun(options.dbPath, { + runId, + status: "failed", + provider: parsed.provider, + model: parsed.model, + metadata: { + generated: false, + error: error instanceof Error ? error.message : String(error) + }, + now + }); + throw error; } - return { - ok: true, - note: noteRecord(row), - citations, - content - }; - } finally { - db.close(); } -} -async function ingestAppWikiSourceRef(options) { - assertAppWikiWriteAllowed(options); - assertNoPrivateRefs(options.sourceRef, { - allowFileSourceRefs: options.config?.sources.allowed_schemes.includes("file") !== false + const updates = proposedUpdates(prompt, context); + const writePolicy = { + approved: options.approveWrite === true, + durable_writes_performed: false, + reason: options.approveWrite ? "Approval flag recorded; durable wiki writing is deferred to the wiki compile task." : "Dry-run mode: proposed wiki updates require approval before durable writes." + }; + addRunEvent(options.dbPath, { + runId, + level: "info", + event: generated ? "answer_generated" : "answer_drafted", + metadata: { + provider, + model, + proposed_updates: updates.length, + durable_writes_performed: false + }, + now }); - return ingestSourceRef({ - dbPath: options.workspace.knowledgeDbPath, - sourceRef: options.sourceRef, - purpose: options.purpose ?? "knowledge_index", - config: options.config, - safetyPolicy: options.safetyPolicy + recordUsage(options.dbPath, runId, usage, provider, model, now, { + generated, + citations: context.citations.length + }); + updateRun(options.dbPath, { + runId, + status: generated ? "completed" : "dry_run", + provider, + model, + metadata: { + generated, + citations: context.citations.length, + proposed_updates: updates.length, + approve_write: options.approveWrite === true + }, + now }); -} - -// src/agent.ts -import { randomUUID as randomUUID6 } from "crypto"; - -// src/providers.ts -import { randomUUID as randomUUID5 } from "crypto"; -var DEFAULT_PROVIDER_SETTINGS = { - openai: { - api_key_env: "OPENAI_API_KEY", - default_model: "gpt-5.2" - }, - anthropic: { - api_key_env: "ANTHROPIC_API_KEY", - default_model: "claude-sonnet-4-6" - }, - deepseek: { - api_key_env: "DEEPSEEK_API_KEY", - default_model: "deepseek-chat" - } -}; -var PROVIDER_CAPABILITIES = { - openai: { - text_generation: true, - structured_output: true, - tool_usage: true, - tool_streaming: true, - image_input: true, - native_web_search: true, - reasoning: true, - embeddings: true - }, - anthropic: { - text_generation: true, - structured_output: true, - tool_usage: true, - tool_streaming: true, - image_input: true, - native_web_search: false, - reasoning: true, - embeddings: false - }, - deepseek: { - text_generation: true, - structured_output: true, - tool_usage: true, - tool_streaming: true, - image_input: false, - native_web_search: false, - reasoning: true, - embeddings: false - } -}; -var BUILTIN_ALIASES = { - default: "openai:gpt-5.2", - fast: "openai:gpt-5-mini", - reasoning: "anthropic:claude-opus-4-6", - sonnet: "anthropic:claude-sonnet-4-6", - deepseek: "deepseek:deepseek-chat", - "deepseek-reasoning": "deepseek:deepseek-reasoner" -}; -function providerConfig(config) { - return config?.providers ?? {}; -} -function providerSettings(config, provider) { - const configured = providerConfig(config)[provider] ?? {}; return { - ...DEFAULT_PROVIDER_SETTINGS[provider], - ...configured + run_id: runId, + prompt, + generated, + provider, + model, + answer, + context, + citations: context.citations, + proposed_wiki_updates: updates, + write_policy: writePolicy, + usage, + warnings }; } -function modelAliases(config) { - const configured = providerConfig(config); - return { - ...BUILTIN_ALIASES, - ...configured.default_model ? { default: configured.default_model } : {}, - ...configured.aliases ?? {} +async function runKnowledgePromptOverItems(items, options) { + const prompt = options.prompt.trim(); + if (!prompt) + throw new Error("Knowledge prompt is required."); + const runId = `run_${randomUUID6()}`; + const modelRef = resolveModelRef(options.modelRef ?? "default", options.config); + const parsed = parseModelRef(modelRef); + const { prompt: _p, generate: _g, approveWrite: _a, now: _n, ...retrievalOptions } = options; + const context = await retrieveKnowledgeContextFromItems(items, { + ...retrievalOptions, + query: prompt + }); + let answer = localAnswer(prompt, context); + let generated = false; + let provider = "local"; + let model = "context-draft"; + let usage = { + input_tokens: estimateTokens(prompt) + context.excerpts.reduce((sum, excerpt) => sum + estimateTokens(excerpt.text), 0), + output_tokens: estimateTokens(answer), + cost_usd: 0 }; -} -function parseModelRef(modelRef) { - const [provider, ...rest] = modelRef.split(":"); - const model = rest.join(":"); - if (provider !== "openai" && provider !== "anthropic" && provider !== "deepseek") { - throw new Error(`Unsupported AI provider: ${provider}`); + const warnings = [...context.warnings]; + if (options.generate) { + if (options.fake) { + generated = true; + provider = parsed.provider; + model = parsed.model; + answer = `Fake generated answer for: ${prompt} + +${answer}`; + } else { + const { generateText } = await import("ai"); + const languageModel = await languageModelFor(modelRef, { + config: options.config, + env: options.env + }); + const result = await generateText({ + model: languageModel, + system: "You answer company knowledge-base prompts using only provided context and citation ids.", + prompt: promptForModel(prompt, context) + }); + generated = true; + provider = parsed.provider; + model = parsed.model; + answer = result.text; + const normalized = normalizeAiSdkUsage({ + provider, + model, + usage: result.usage, + providerMetadata: result.providerMetadata + }); + usage = { + input_tokens: normalized.input_tokens, + output_tokens: normalized.output_tokens, + cost_usd: normalized.cost_usd + }; + } } - if (!model) - throw new Error(`Invalid model ref: ${modelRef}. Expected provider:model.`); - return { provider, model }; -} -function resolveModelRef(aliasOrRef, config) { - const aliases = modelAliases(config); - return aliases[aliasOrRef] ?? aliasOrRef; -} -function listModelRegistry(config) { - const aliases = modelAliases(config); - return Object.entries(aliases).map(([alias, modelRef]) => { - const parsed = parseModelRef(modelRef); - return { - alias, - model_ref: modelRef, - provider: parsed.provider, - model: parsed.model, - default: alias === "default", - capabilities: PROVIDER_CAPABILITIES[parsed.provider] - }; - }); -} -function providerCredentialStatus(config, env = process.env) { - return Object.keys(DEFAULT_PROVIDER_SETTINGS).map((provider) => { - const settings = providerSettings(config, provider); - const configured = Boolean(env[settings.api_key_env]); - return { - provider, - api_key_env: settings.api_key_env, - configured, - source: configured ? "env" : "missing", - base_url: settings.base_url ?? null, - default_model: settings.default_model - }; - }); -} -function providerStatus(config, env = process.env) { + const updates = proposedUpdates(prompt, context); + const writePolicy = { + approved: options.approveWrite === true, + durable_writes_performed: false, + reason: options.approveWrite ? "Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode." : "Dry-run mode: proposed wiki updates require approval before durable writes." + }; return { - default_model: resolveModelRef("default", config), - providers: providerCredentialStatus(config, env), - models: listModelRegistry(config) + run_id: runId, + prompt, + generated, + provider, + model, + answer, + context, + citations: context.citations, + proposed_wiki_updates: updates, + write_policy: writePolicy, + usage, + warnings }; } -function assertProviderCredentials(provider, config, env = process.env) { - const status = providerCredentialStatus(config, env).find((entry) => entry.provider === provider); - if (!status) - throw new Error(`Unsupported AI provider: ${provider}`); - if (!status.configured) - throw new Error(`Missing ${status.api_key_env} for ${provider}. Set the env var to use this provider.`); - return status; -} -async function defaultFactory(provider) { - if (provider === "openai") { - const { createOpenAI } = await import("@ai-sdk/openai"); - return createOpenAI; - } - if (provider === "anthropic") { - const { createAnthropic } = await import("@ai-sdk/anthropic"); - return createAnthropic; - } - const { createDeepSeek } = await import("@ai-sdk/deepseek"); - return createDeepSeek; -} -async function createAiSdkProviderRegistry(options = {}) { - const { createProviderRegistry } = await import("ai"); - const env = options.env ?? process.env; - const providers = {}; - for (const provider of Object.keys(DEFAULT_PROVIDER_SETTINGS)) { - const settings = providerSettings(options.config, provider); - const apiKey = env[settings.api_key_env]; - if (!apiKey) - continue; - const factory = options.factories?.[provider] ?? await defaultFactory(provider); - providers[provider] = factory({ apiKey, baseURL: settings.base_url }); - } - return createProviderRegistry(providers); -} -async function languageModelFor(aliasOrRef, options = {}) { - const modelRef = resolveModelRef(aliasOrRef, options.config); - const parsed = parseModelRef(modelRef); - assertProviderCredentials(parsed.provider, options.config, options.env); - const registry = await createAiSdkProviderRegistry(options); - return registry.languageModel(modelRef); -} -function usageNumber(usage, keys) { - for (const key of keys) { - const value = usage[key]; - if (typeof value === "number" && Number.isFinite(value)) - return value; - } - return 0; + +// src/context-pack.ts +import { createHash as createHash11 } from "crypto"; +var DEFAULT_MAX_TOKENS = 1200; +var DEFAULT_MAX_ITEMS = 6; +var MAX_MAX_TOKENS = 12000; +var MAX_MAX_ITEMS = 50; +var MIN_MAX_TOKENS = 800; +function stableId5(prefix, value, size = 16) { + return `${prefix}_${createHash11("sha256").update(value).digest("hex").slice(0, size)}`; } -function normalizeAiSdkUsage(input) { - const usage = input.usage ?? {}; - return { - provider: input.provider, - model: input.model, - input_tokens: usageNumber(usage, ["inputTokens", "promptTokens", "input_tokens", "prompt_tokens"]), - output_tokens: usageNumber(usage, ["outputTokens", "completionTokens", "output_tokens", "completion_tokens"]), - cost_usd: input.costUsd ?? 0, - metadata: { - usage, - provider_metadata: input.providerMetadata ?? {} - } - }; +function normalizeText(value) { + return value.normalize("NFKC").trim().replace(/\s+/g, " "); } -function recordProviderUsage(db, input) { - const id = `usage_${randomUUID5()}`; - db.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - id, - input.run_id ?? null, - input.provider, - input.model, - input.input_tokens, - input.output_tokens, - input.cost_usd, - JSON.stringify(input.metadata), - input.created_at ?? new Date().toISOString() - ]); - return id; +function normalizedSearchText(value) { + return normalizeText(value).toLowerCase(); } - -// src/retrieval.ts -import { createHash as createHash10 } from "crypto"; - -// src/search.ts -import { existsSync as existsSync8, readFileSync as readFileSync9 } from "fs"; - -// src/embeddings.ts -import { createHash as createHash9 } from "crypto"; -var DEFAULT_EMBEDDING_MODEL_REF = "openai:text-embedding-3-small"; -var DEFAULT_EMBEDDING_DIMENSIONS = 1536; -function embeddingConfig(config) { - return config?.embeddings ?? {}; +function termsFor(value) { + return Array.from(new Set(normalizedSearchText(value).match(/[\p{L}\p{N}_]+/gu) ?? [])).slice(0, 24); } -function stableId3(prefix, value) { - return `${prefix}_${createHash9("sha256").update(value).digest("hex").slice(0, 20)}`; +function truncateText(value, maxChars) { + const normalized = normalizeText(value); + if (normalized.length <= maxChars) + return normalized; + const ellipsis = "..."; + if (maxChars <= ellipsis.length) + return normalized.slice(0, Math.max(0, maxChars)); + return `${normalized.slice(0, maxChars - ellipsis.length).trim()}${ellipsis}`; } -function parseJsonObject3(value) { +function parseJsonObject5(value) { if (!value) return {}; try { @@ -39591,17173 +23654,17512 @@ function parseJsonObject3(value) { return {}; } } -function metadataString2(metadata, keys) { +function isSecretishKey(key) { + return /(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test(key); +} +function metadataKeys(metadata) { + return Object.keys(metadata).filter((key) => !isSecretishKey(key)).sort().slice(0, 12); +} +function rawMetadataRef(metadata, keys) { for (const key of keys) { + if (isSecretishKey(key)) + continue; const value = metadata[key]; - if (typeof value === "string" && value.length > 0) - return value; + if (typeof value === "string" && value.trim()) + return value.trim(); } return null; } -function metadataNumber2(metadata, keys) { - for (const key of keys) { - const value = metadata[key]; - if (typeof value === "number" && Number.isFinite(value)) - return value; +function safeRef(value, policy) { + if (!value) + return null; + const redacted = redactSecrets(value, policy).text; + try { + const parsed = new URL(redacted); + const secretParams = ["token", "access_token", "api_key", "apikey", "key", "secret", "password", "signature", "sig"]; + for (const param of secretParams) + parsed.searchParams.delete(param); + for (const [key] of parsed.searchParams) { + if (isSecretishKey(key)) + parsed.searchParams.delete(key); + } + return parsed.toString(); + } catch { + return redacted; } - return null; } -function vectorNorm(vector) { - return Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0)); +function metadataRef(metadata, keys, policy) { + return safeRef(rawMetadataRef(metadata, keys), policy); } -function cosineSimilarity(a, b, bNorm = vectorNorm(b)) { - const aNorm = vectorNorm(a); - if (aNorm === 0 || bNorm === 0) +function summarizeMetadata(metadata) { + const parts = []; + for (const key of metadataKeys(metadata).slice(0, 6)) { + const value = metadata[key]; + if (typeof value === "string" && value.trim()) + parts.push(`${key}=${truncateText(value, 80)}`); + else if (typeof value === "number" || typeof value === "boolean") + parts.push(`${key}=${String(value)}`); + else if (value && typeof value === "object") + parts.push(`${key}={...}`); + } + return parts.join("; "); +} +function estimateTokensForText(text) { + if (!text.trim()) return 0; - const length = Math.min(a.length, b.length); - let dot = 0; - for (let i = 0;i < length; i += 1) - dot += a[i] * b[i]; - return dot / (aNorm * bNorm); + return Math.max(1, Math.ceil(text.length / 4)); } -function deterministicVector(text, dimensions) { - const bytes = createHash9("sha256").update(text).digest(); - return Array.from({ length: dimensions }, (_, index) => { - const value = bytes[index % bytes.length] / 255; - return Number((value * 2 - 1).toFixed(6)); - }); +function estimateTokensForValue(value) { + return estimateTokensForText(JSON.stringify(value)); +} +function coerceMaxTokens(value) { + if (!Number.isFinite(value ?? NaN)) + return DEFAULT_MAX_TOKENS; + const floor = Math.floor(value); + if (floor < MIN_MAX_TOKENS) + throw new Error(`--max-tokens must be at least ${MIN_MAX_TOKENS} for the stable context-pack schema.`); + return Math.min(floor, MAX_MAX_TOKENS); +} +function coerceMaxItems(value, limit) { + const raw = Number.isFinite(value ?? NaN) ? value : limit; + if (!Number.isFinite(raw ?? NaN)) + return DEFAULT_MAX_ITEMS; + return Math.max(1, Math.min(Math.floor(raw), MAX_MAX_ITEMS)); +} +function parseSince(value, now) { + if (!value) + return { cutoff: null, warning: null }; + const trimmed = value.trim(); + const duration = /^(\d+)\s*([mhdw])$/i.exec(trimmed); + if (duration) { + const amount = Number(duration[1]); + const unit = duration[2].toLowerCase(); + const multiplier = unit === "m" ? 60000 : unit === "h" ? 3600000 : unit === "d" ? 86400000 : 604800000; + return { cutoff: new Date(now.getTime() - amount * multiplier).toISOString(), warning: null }; + } + const parsed = new Date(trimmed); + if (!Number.isNaN(parsed.getTime())) + return { cutoff: parsed.toISOString(), warning: null }; + return { cutoff: null, warning: `invalid_since_ignored: ${trimmed}` }; +} +function redactPreview(text, policy, maxChars) { + const redacted = redactSecrets(text, policy); + return { + text: truncateText(redacted.text, maxChars), + redactions: redacted.findings.length + }; +} +function scoreAgainstTopic(text, terms) { + if (terms.length === 0) + return 0.5; + const haystack = normalizedSearchText(text); + const matched = terms.filter((term) => haystack.includes(term)).length; + return Number((matched / terms.length).toFixed(6)); } -async function openAiEmbeddingModel(model, config, env = process.env) { - assertProviderCredentials("openai", config, env); - const settings = providerSettings(config, "openai"); - const { createOpenAI } = await import("@ai-sdk/openai"); - const openai = createOpenAI({ - apiKey: env[settings.api_key_env], - baseURL: settings.base_url - }); - if (openai.embeddingModel) - return openai.embeddingModel(model); - if (openai.textEmbedding) - return openai.textEmbedding(model); - if (openai.textEmbeddingModel) - return openai.textEmbeddingModel(model); - throw new Error("OpenAI provider does not expose an embedding model factory."); +function baseSafetyReminders(source) { + return [ + "This pack is read-only and performs no durable writes.", + "Use citation ids and refs instead of pasting raw artifacts into prompts.", + "Resolve source or artifact refs explicitly only when raw content is needed and allowed.", + "Run generated knowledge writes through approval-gated commands before applying.", + source === "loops" || source === "runs" ? "Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded." : "Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata." + ]; } -function resolveEmbeddingModelRef(modelRef, config) { - if (!modelRef || modelRef === "default" || modelRef === "embedding") { - return embeddingConfig(config).default_model ?? DEFAULT_EMBEDDING_MODEL_REF; - } - return modelRef; +function citationFromRetrieval(index, citation, policy) { + const sourceRef = safeRef(citation.source_ref, policy); + const sourceUri = safeRef(citation.source_uri, policy); + const artifactUri = safeRef(citation.artifact_uri, policy); + const artifactPath = safeRef(citation.artifact_path, policy); + const ref = sourceRef ?? sourceUri ?? artifactPath ?? artifactUri ?? citation.id; + const quote = citation.quote ? redactPreview(citation.quote, policy, index < 3 ? 220 : 140) : null; + return { + citation: { + id: stableId5("cite", `${citation.id}\x00${ref}`, 12), + kind: citation.artifact_uri || citation.artifact_path ? "artifact" : "source", + ref, + source_ref: sourceRef, + source_uri: sourceUri, + artifact_uri: artifactUri, + artifact_path: artifactPath, + run_id: null, + run_event_id: null, + revision: citation.revision ?? null, + hash: citation.hash ?? null, + chunk_id: citation.chunk_id ?? null, + offsets: { + start: citation.start_offset ?? null, + end: citation.end_offset ?? null + }, + quote_preview: quote?.text ?? null + }, + redactions: quote?.redactions ?? 0 + }; } -async function embedTexts(texts, options = {}) { - const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); - const parsed = parseModelRef(modelRef); - if (parsed.provider !== "openai") { - throw new Error(`Embedding provider ${parsed.provider} is not supported yet. Use openai:text-embedding-3-small.`); - } - const dimensions = options.dimensions ?? embeddingConfig(options.config).dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS; - if (options.fake) { +async function buildSearchDraft(options, maxItems) { + const query2 = (options.query ?? options.topic ?? "").trim(); + if (!query2) + throw new Error("Context pack query is required for search source."); + const { + config, + dbPath, + limit, + semantic, + modelRef, + dimensions, + fake, + env, + batchSize, + maxParallelCalls, + legacyStorePath + } = options; + const context = await retrieveKnowledgeContext({ + dbPath, + config, + legacyStorePath, + query: query2, + limit: Math.max(maxItems, limit ?? maxItems), + semantic, + modelRef, + dimensions, + fake, + env, + batchSize, + maxParallelCalls, + contextChars: Math.min(options.contextChars ?? 700, 1200) + }); + const citationMap = new Map; + let redactions = 0; + context.citations.forEach((citation, index) => { + const item = citationFromRetrieval(index, citation, options.safetyPolicy); + redactions += item.redactions; + citationMap.set(citation.id, item.citation); + }); + const evidence = context.excerpts.slice(0, Math.max(maxItems * 2, maxItems)).map((excerpt) => { + const result = context.results.find((entry) => entry.id === excerpt.result_id); + const citation = excerpt.citation_id ? citationMap.get(excerpt.citation_id) : null; + const redacted = redactPreview(excerpt.text, options.safetyPolicy, 520); + redactions += redacted.redactions; + const title = result?.title ?? citation?.ref ?? excerpt.kind; return { - provider: parsed.provider, - model: parsed.model, - dimensions, - vectors: texts.map((text) => deterministicVector(text, dimensions)), - usage: { input_tokens: texts.reduce((sum, text) => sum + Math.max(1, Math.ceil(text.split(/\s+/).filter(Boolean).length * 1.25)), 0) } - }; - } - const { embedMany } = await import("ai"); - const model = await openAiEmbeddingModel(parsed.model, options.config, options.env); - const result = await embedMany({ - model, - values: texts, - maxParallelCalls: options.maxParallelCalls ?? embeddingConfig(options.config).max_parallel_calls, - providerOptions: { - openai: { - dimensions + id: stableId5("ev", `${excerpt.kind}\x00${excerpt.result_id}\x00${excerpt.citation_id ?? ""}`, 14), + kind: excerpt.kind, + title: truncateText(title, 100), + text_preview: redacted.text, + score: Number(excerpt.score.toFixed(6)), + citation_ids: citation ? [citation.id] : [], + provenance: { + source: "search", + record_ref: `${excerpt.kind}:${excerpt.result_id}`, + created_at: context.created_at, + updated_at: null, + metadata_keys: [] } - } + }; }); - const vectors = result.embeddings; + const usedCitationIds = new Set(evidence.flatMap((entry) => entry.citation_ids)); + const citations = Array.from(citationMap.values()).filter((citation) => usedCitationIds.has(citation.id)); return { - provider: parsed.provider, - model: parsed.model, - dimensions: vectors[0]?.length ?? dimensions, - vectors, - usage: { input_tokens: result.usage?.tokens ?? 0 } + citations, + evidence, + duplicateCandidates: [], + redactions, + warnings: context.warnings, + available: context.excerpts.length }; } -function selectCandidateChunks(db, options) { - const baseQuery = `SELECT - c.id, - c.text, - c.token_count, - c.start_offset, - c.end_offset, - c.metadata_json, - c.source_revision_id, - sr.revision, - sr.hash, - s.uri AS source_uri, - s.kind AS source_kind - FROM chunks c - LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id - LEFT JOIN sources s ON s.id = sr.source_id - LEFT JOIN vector_index_entries v - ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? - WHERE v.id IS NULL`; - const suffix = ` - ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`; - if (options.sourceRevisionId) { - return db.query(`${baseQuery} AND c.source_revision_id = ?${suffix}`).all(options.provider, options.model, options.sourceRevisionId, options.limit); +function loadRunRows(db, cutoff, limit) { + if (cutoff) { + return db.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at + FROM runs + WHERE updated_at >= ? OR created_at >= ? + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(cutoff, cutoff, limit); } - return db.query(`${baseQuery}${suffix}`).all(options.provider, options.model, options.limit); + return db.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at + FROM runs + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(limit); } -function provenanceForChunk(row) { - const metadata = parseJsonObject3(row.metadata_json); - const existing = metadata.provenance; - if (existing && typeof existing === "object" && !Array.isArray(existing)) - return existing; - return sourceProvenance({ - source_ref: metadataString2(metadata, ["source_ref"]), - source_uri: row.source_uri ?? metadataString2(metadata, ["source_uri"]), - source_kind: row.source_kind ?? metadataString2(metadata, ["source_kind"]), - source_revision_id: row.source_revision_id, - revision: row.revision ?? metadataString2(metadata, ["revision"]), - hash: row.hash ?? metadataString2(metadata, ["hash"]), - chunk_id: row.id, - start_offset: row.start_offset ?? metadataNumber2(metadata, ["start_offset"]), - end_offset: row.end_offset ?? metadataNumber2(metadata, ["end_offset"]), - status: metadataString2(metadata, ["status"]), - resolver: "open-files-read-only" - }); +function loadRunEvents(db, runIds, limit) { + if (runIds.length === 0) + return []; + const placeholders2 = runIds.map(() => "?").join(", "); + return db.query(`SELECT id, run_id, level, event, metadata_json, created_at + FROM run_events + WHERE run_id IN (${placeholders2}) + ORDER BY created_at DESC + LIMIT ?`).all(...runIds, limit); } -function upsertVectors(db, rows, embedding, now) { - const insertEmbedding = db.prepare(` - INSERT INTO chunk_embeddings (id, chunk_id, provider, model, dimensions, vector_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(chunk_id, provider, model) DO UPDATE SET - dimensions = excluded.dimensions, - vector_json = excluded.vector_json, - created_at = excluded.created_at - `); - const insertVector = db.prepare(` - INSERT INTO vector_index_entries ( - id, chunk_id, source_revision_id, provider, model, dimensions, vector_json, vector_norm, - source_uri, source_ref, revision, hash, start_offset, end_offset, token_count, status, - metadata_json, created_at, updated_at - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(chunk_id, provider, model) DO UPDATE SET - source_revision_id = excluded.source_revision_id, - dimensions = excluded.dimensions, - vector_json = excluded.vector_json, - vector_norm = excluded.vector_norm, - source_uri = excluded.source_uri, - source_ref = excluded.source_ref, - revision = excluded.revision, - hash = excluded.hash, - start_offset = excluded.start_offset, - end_offset = excluded.end_offset, - token_count = excluded.token_count, - status = excluded.status, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at - `); - const write = db.transaction(() => { - for (let index = 0;index < rows.length; index += 1) { - const row = rows[index]; - const vector = embedding.vectors[index]; - if (!vector) - continue; - const metadata = parseJsonObject3(row.metadata_json); - const provenance = provenanceForChunk(row); - const sourceRef = provenance.source_ref ?? metadataString2(metadata, ["source_ref"]); - const sourceUri = provenance.source_uri ?? row.source_uri ?? metadataString2(metadata, ["source_uri"]); - const revision = provenance.revision ?? row.revision ?? metadataString2(metadata, ["revision"]); - const hash = provenance.hash ?? row.hash ?? metadataString2(metadata, ["hash"]); - const status = provenance.status ?? metadataString2(metadata, ["status"]) ?? "active"; - const vectorJson = JSON.stringify(vector); - insertEmbedding.run(stableId3("emb", `${row.id}\x00${embedding.provider}\x00${embedding.model}`), row.id, embedding.provider, embedding.model, embedding.dimensions, vectorJson, now); - insertVector.run(stableId3("vec", `${row.id}\x00${embedding.provider}\x00${embedding.model}`), row.id, row.source_revision_id, embedding.provider, embedding.model, embedding.dimensions, vectorJson, vectorNorm(vector), sourceUri, sourceRef, revision, hash, provenance.start_offset, provenance.end_offset, row.token_count, status, JSON.stringify({ - ...metadata, - provenance, - embedded_at: now - }), now, now); - } - }); - write(); - return rows.length; +function rowMentionsLoop(row, events) { + const text = `${row.type} ${row.metadata_json} ${events.map((event) => `${event.event} ${event.metadata_json}`).join(" ")}`.toLowerCase(); + return text.includes("loop"); } -async function indexKnowledgeEmbeddings(options) { - const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); - const parsed = parseModelRef(modelRef); - if (parsed.provider !== "openai") - throw new Error(`Embedding provider ${parsed.provider} is not supported yet.`); - const now = (options.now ?? new Date).toISOString(); - const limit = Math.max(1, Math.min(options.limit ?? 100, 1000)); - migrateKnowledgeDb(options.dbPath); - const readDb = openKnowledgeDb(options.dbPath); - let rows; - try { - rows = selectCandidateChunks(readDb, { - provider: parsed.provider, - model: parsed.model, - limit, - sourceRevisionId: options.sourceRevisionId - }); - } finally { - readDb.close(); - } - if (rows.length === 0) { - return { - provider: parsed.provider, - model: parsed.model, - dimensions: options.dimensions ?? embeddingConfig(options.config).dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS, - chunks_seen: 0, - chunks_embedded: 0, - embeddings_upserted: 0, - vector_entries_upserted: 0, - usage: { input_tokens: 0 } - }; - } - const embedding = await embedTexts(rows.map((row) => row.text), options); - const writeDb = openKnowledgeDb(options.dbPath); - try { - const upserted = upsertVectors(writeDb, rows, embedding, now); - return { - provider: embedding.provider, - model: embedding.model, - dimensions: embedding.dimensions, - chunks_seen: rows.length, - chunks_embedded: rows.length, - embeddings_upserted: upserted, - vector_entries_upserted: upserted, - usage: embedding.usage - }; - } finally { - writeDb.close(); - } +function citationForRun(row, metadata, policy) { + const sourceRef = metadataRef(metadata, ["source_ref", "source_uri", "evidence_uri", "receipt_uri"], policy); + const artifactUri = metadataRef(metadata, ["artifact_uri"], policy); + const artifactPath = metadataRef(metadata, ["artifact_path", "artifact_key"], policy); + const ref = sourceRef ?? artifactUri ?? artifactPath ?? `knowledge://project/runs/${row.id}`; + const quote = row.prompt ? redactPreview(row.prompt, policy, 180).text : null; + return { + id: stableId5("cite", `run\x00${row.id}\x00${ref}`, 12), + kind: artifactUri || artifactPath ? "artifact" : "run", + ref, + source_ref: sourceRef?.startsWith("open-files://") ? sourceRef : null, + source_uri: sourceRef && !sourceRef.startsWith("open-files://") ? sourceRef : null, + artifact_uri: artifactUri, + artifact_path: artifactPath, + run_id: row.id, + run_event_id: null, + revision: metadataRef(metadata, ["revision"], policy), + hash: metadataRef(metadata, ["hash", "content_hash"], policy), + chunk_id: null, + offsets: { start: null, end: null }, + quote_preview: quote + }; } -function embeddingIndexStatus(dbPath) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - try { - const totalEmbeddings = db.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n ?? 0; - const totalVectorEntries = db.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n ?? 0; - const indexes = db.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at - FROM vector_index_entries - GROUP BY provider, model, dimensions - ORDER BY provider, model`).all(); - return { - total_embeddings: totalEmbeddings, - total_vector_entries: totalVectorEntries, - indexes - }; - } finally { - db.close(); +function citationForEvent(row, metadata, policy) { + const sourceRef = metadataRef(metadata, ["source_ref", "source_uri", "evidence_uri", "receipt_uri"], policy); + const artifactUri = metadataRef(metadata, ["artifact_uri"], policy); + const artifactPath = metadataRef(metadata, ["artifact_path", "artifact_key"], policy); + const ref = sourceRef ?? artifactUri ?? artifactPath ?? `knowledge://project/runs/${row.run_id}`; + const quote = redactPreview(row.event, policy, 160).text; + return { + id: stableId5("cite", `event\x00${row.id}\x00${ref}`, 12), + kind: artifactUri || artifactPath ? "artifact" : "run_event", + ref, + source_ref: sourceRef?.startsWith("open-files://") ? sourceRef : null, + source_uri: sourceRef && !sourceRef.startsWith("open-files://") ? sourceRef : null, + artifact_uri: artifactUri, + artifact_path: artifactPath, + run_id: row.run_id, + run_event_id: row.id, + revision: metadataRef(metadata, ["revision"], policy), + hash: metadataRef(metadata, ["hash", "content_hash"], policy), + chunk_id: null, + offsets: { start: null, end: null }, + quote_preview: quote + }; +} +function duplicateCandidatesFor(evidence) { + const groups = new Map; + for (const entry of evidence) { + const key = normalizedSearchText(`${entry.title} ${entry.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g, "").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g, "").replace(/[^a-z0-9 ]+/g, "").replace(/\b(?:run|event|completed|dry_run|pending)\b/g, "").replace(/\s+/g, " ").trim().slice(0, 220); + if (!key) + continue; + groups.set(key, [...groups.get(key) ?? [], entry.id]); } + return Array.from(groups.entries()).filter(([, ids]) => ids.length > 1).map(([key, ids]) => ({ + id: stableId5("dup", key, 12), + reason: "normalized_text_match", + evidence_ids: ids, + confidence: ids.length > 2 ? "high" : "medium" + })); } -async function searchVectorIndex(options) { - const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); - const parsed = parseModelRef(modelRef); - const limit = Math.max(1, Math.min(options.limit ?? 10, 100)); - const embedded = await embedTexts([options.query], options); - const queryVector = embedded.vectors[0] ?? []; +async function buildRunDraft(options, maxItems, now) { + const source = options.source === "loops" ? "loops" : "runs"; + const topic = (options.topic ?? options.query ?? "").trim(); + const topicTerms = termsFor(topic); + const since = parseSince(options.since, now); + const warnings = since.warning ? [since.warning] : []; migrateKnowledgeDb(options.dbPath); const db = openKnowledgeDb(options.dbPath); try { - const rows = db.query(`SELECT - v.chunk_id, - c.text, - v.vector_json, - v.vector_norm, - v.source_uri, - v.source_ref, - v.revision, - v.hash, - v.metadata_json - FROM vector_index_entries v - JOIN chunks c ON c.id = v.chunk_id - WHERE v.provider = ? AND v.model = ? AND v.status = 'active'`).all(parsed.provider, parsed.model); - const scored = rows.map((row) => { - const vector = JSON.parse(row.vector_json); - const metadata = parseJsonObject3(row.metadata_json); - const provenance = metadata.provenance && typeof metadata.provenance === "object" && !Array.isArray(metadata.provenance) ? metadata.provenance : null; - return { - chunk_id: row.chunk_id, - score: cosineSimilarity(queryVector, vector, row.vector_norm), - text: row.text, - source_uri: row.source_uri, - source_ref: row.source_ref, - revision: row.revision, - hash: row.hash, - provenance - }; - }).sort((a, b) => b.score - a.score).slice(0, limit); - return { - provider: parsed.provider, - model: parsed.model, - dimensions: embedded.dimensions, - query: options.query, - results: scored + const runRows = loadRunRows(db, since.cutoff, Math.max(maxItems * 8, 40)); + const allEvents = loadRunEvents(db, runRows.map((row) => row.id), Math.max(maxItems * 12, 80)); + const eventsByRun = new Map; + for (const event of allEvents) + eventsByRun.set(event.run_id, [...eventsByRun.get(event.run_id) ?? [], event]); + const filteredRuns = source === "loops" ? runRows.filter((row) => rowMentionsLoop(row, eventsByRun.get(row.id) ?? [])) : runRows; + const scoredRuns = filteredRuns.map((row) => { + const metadata = parseJsonObject5(row.metadata_json); + const text = `${row.type} ${row.status} ${row.prompt ?? ""} ${summarizeMetadata(metadata)} ${(eventsByRun.get(row.id) ?? []).map((event) => `${event.event} ${event.metadata_json}`).join(" ")}`; + return { row, metadata, score: scoreAgainstTopic(text, topicTerms), text }; + }).filter((entry) => topicTerms.length === 0 || entry.score > 0).sort((a, b) => b.score - a.score || b.row.updated_at.localeCompare(a.row.updated_at) || a.row.id.localeCompare(b.row.id)); + const citations = []; + const evidence = []; + let redactions = 0; + for (const entry of scoredRuns.slice(0, Math.max(maxItems * 2, maxItems))) { + const citation = citationForRun(entry.row, entry.metadata, options.safetyPolicy); + citations.push(citation); + const metadataSummary = summarizeMetadata(entry.metadata); + const previewInput = [entry.row.prompt, metadataSummary].filter(Boolean).join(" | ") || `${entry.row.type} ${entry.row.status}`; + const preview2 = redactPreview(previewInput, options.safetyPolicy, 420); + redactions += preview2.redactions; + evidence.push({ + id: `run:${entry.row.id}`, + kind: entry.row.type, + title: truncateText(`${entry.row.type}: ${entry.row.status}`, 100), + text_preview: preview2.text, + score: entry.score, + citation_ids: [citation.id], + provenance: { + source, + record_ref: `knowledge://project/runs/${entry.row.id}`, + created_at: entry.row.created_at, + updated_at: entry.row.updated_at, + metadata_keys: metadataKeys(entry.metadata) + } + }); + const eventRows = (eventsByRun.get(entry.row.id) ?? []).map((event) => { + const metadata = parseJsonObject5(event.metadata_json); + const text = `${event.event} ${summarizeMetadata(metadata)} ${event.metadata_json}`; + return { event, metadata, score: scoreAgainstTopic(text, topicTerms), text }; + }).filter((eventEntry) => topicTerms.length === 0 || eventEntry.score > 0).sort((a, b) => b.score - a.score || b.event.created_at.localeCompare(a.event.created_at) || a.event.id.localeCompare(b.event.id)).slice(0, 2); + for (const eventEntry of eventRows) { + const eventCitation = citationForEvent(eventEntry.event, eventEntry.metadata, options.safetyPolicy); + citations.push(eventCitation); + const preview3 = redactPreview(`${eventEntry.event}: ${summarizeMetadata(eventEntry.metadata)}`, options.safetyPolicy, 320); + redactions += preview3.redactions; + evidence.push({ + id: `event:${eventEntry.event.id}`, + kind: `run_event:${eventEntry.event.level}`, + title: truncateText(eventEntry.event.event, 100), + text_preview: preview3.text, + score: eventEntry.score, + citation_ids: [eventCitation.id], + provenance: { + source, + record_ref: `knowledge://project/runs/${eventEntry.event.run_id}`, + created_at: eventEntry.event.created_at, + updated_at: null, + metadata_keys: metadataKeys(eventEntry.metadata) + } + }); + } + } + return { + citations, + evidence, + duplicateCandidates: options.dedupe ? duplicateCandidatesFor(evidence) : [], + redactions, + warnings, + available: scoredRuns.length }; } finally { db.close(); } } - -// src/search.ts -function parseJsonObject4(value) { - if (!value) - return {}; - try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; - } -} -function metadataString3(metadata, keys) { - for (const key of keys) { - const value = metadata[key]; - if (typeof value === "string" && value.length > 0) - return value; - } - return null; -} -function metadataNumber3(metadata, keys) { - for (const key of keys) { - const value = metadata[key]; - if (typeof value === "number" && Number.isFinite(value)) - return value; - } - return null; -} -function unique(values) { - return Array.from(new Set(values)); +function outlineFor(input) { + const title = input.purpose === "proposal" ? `Proposal context: ${truncateText(input.query || "loop evidence", 80)}` : `Knowledge context: ${truncateText(input.query, 80)}`; + const evidenceIds = input.evidence.slice(0, 8).map((entry) => entry.id); + const duplicateIds = input.duplicates.slice(0, 5).map((entry) => entry.id); + const bullets = input.evidence.slice(0, 5).map((entry) => `${entry.id}: ${entry.title}`); + if (input.evidence.length === 0) + bullets.push("No matching bounded evidence was found."); + return { + title, + bullets, + evidence_ids: evidenceIds, + duplicate_candidate_ids: duplicateIds, + next_actions: input.source === "loops" ? [ + "Review duplicate_candidates before drafting a new proposal.", + "Use cited run refs for provenance; inspect a run only when more detail is needed.", + "Keep proposal writes approval-gated and idempotent." + ] : [ + "Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.", + "Inspect cited refs only if the bounded preview is insufficient.", + "Use knowledge build/file-answer only with explicit approval for durable writes." + ] + }; } -function queryTerms(query2) { - const terms = query2.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []; - return unique(terms.filter((term) => term.length > 0)).slice(0, 16); +function pruneCitations(pack) { + const used = new Set(pack.evidence.flatMap((entry) => entry.citation_ids)); + pack.citations = pack.citations.filter((citation) => used.has(citation.id)); } -function normalizeWords(raw) { - return raw.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []; +function syncOutline(pack) { + pack.outline.evidence_ids = pack.evidence.slice(0, 8).map((entry) => entry.id); + pack.outline.bullets = pack.evidence.length > 0 ? pack.evidence.slice(0, 5).map((entry) => `${entry.id}: ${entry.title}`) : ["No matching bounded evidence was found."]; + pack.outline.duplicate_candidate_ids = pack.duplicate_candidates.slice(0, 5).map((entry) => entry.id); } -function parseSearchQuery(query2) { - const tokens = []; - const segment = /"([^"]*)"|(\S+)/g; - let match; - let pendingNegate = false; - while ((match = segment.exec(query2)) !== null) { - if (match[1] !== undefined) { - const words2 = normalizeWords(match[1]); - if (words2.length > 0) { - tokens.push({ type: "phrase", value: words2.join(" "), negate: pendingNegate, prefix: false }); - } - pendingNegate = false; +function fitPackToBudget(pack) { + const maxTokens = pack.budgets.max_tokens; + const warnings = new Set(pack.warnings); + while (estimateTokensForValue(pack) > maxTokens) { + const longest = pack.evidence.map((entry, index) => ({ entry, index })).filter(({ entry }) => entry.text_preview.length > 180).sort((a, b) => b.entry.text_preview.length - a.entry.text_preview.length)[0]; + if (longest) { + longest.entry.text_preview = truncateText(longest.entry.text_preview, 180); + warnings.add("text_preview_truncated_for_token_budget"); continue; } - let raw = match[2] ?? ""; - if (raw === "OR" || raw === "||" || raw === "|") { - tokens.push({ type: "or", value: "", negate: false, prefix: false }); + const longCitation = pack.citations.filter((citation) => (citation.quote_preview?.length ?? 0) > 120).sort((a, b) => (b.quote_preview?.length ?? 0) - (a.quote_preview?.length ?? 0))[0]; + if (longCitation?.quote_preview) { + longCitation.quote_preview = truncateText(longCitation.quote_preview, 120); + warnings.add("citation_quote_truncated_for_token_budget"); continue; } - if (raw === "AND" || raw === "&&") - continue; - if (raw === "NOT") { - pendingNegate = true; + if (pack.evidence.length > 0) { + pack.evidence.pop(); + pack.budgets.items_truncated += 1; + pack.duplicate_candidates = pack.duplicate_candidates.map((candidate) => ({ + ...candidate, + evidence_ids: candidate.evidence_ids.filter((id) => pack.evidence.some((entry) => entry.id === id)) + })).filter((candidate) => candidate.evidence_ids.length > 1); + syncOutline(pack); + warnings.add("evidence_truncated_for_token_budget"); + pruneCitations(pack); continue; } - let negate = pendingNegate; - pendingNegate = false; - if (raw.startsWith("-") && raw.length > 1) { - negate = true; - raw = raw.slice(1); - } - let prefix = false; - if (raw.endsWith("*")) { - prefix = true; - raw = raw.slice(0, -1); - } - const words = normalizeWords(raw); - if (words.length === 0) + if (pack.outline.next_actions.length > 1) { + pack.outline.next_actions.pop(); + warnings.add("outline_truncated_for_token_budget"); continue; - tokens.push({ - type: words.length > 1 ? "phrase" : "term", - value: words.join(" "), - negate, - prefix - }); + } + warnings.add("token_budget_floor_exceeded"); + break; } - return tokens.slice(0, 24); -} -function tokenToFragment(token) { - if (token.type === "phrase") - return `"${token.value}"`; - return `"${token.value}"*`; + pack.warnings = Array.from(warnings).sort(); + pack.budgets.items_included = pack.evidence.length; + syncOutline(pack); + pack.budgets.estimated_tokens = estimateTokensForValue(pack); + pack.budgets.token_budget_exceeded = pack.budgets.estimated_tokens > maxTokens; + if (pack.budgets.token_budget_exceeded) { + throw new Error(`Unable to build context pack within ${maxTokens} token budget; increase --max-tokens.`); + } + pack.message = `${pack.evidence.length} bounded evidence item(s), estimated ${pack.budgets.estimated_tokens}/${maxTokens} token(s)`; + return pack; } -function buildFtsMatch(query2) { - const tokens = parseSearchQuery(query2); - const positives = tokens.filter((t) => t.type !== "or" && !t.negate); - if (positives.length === 0) - return { and: null, or: null }; - const compose = (defaultOp) => { - let expr = ""; - let pendingOr = false; - const negations = []; - for (const token of tokens) { - if (token.type === "or") { - pendingOr = true; - continue; - } - const fragment = tokenToFragment(token); - if (token.negate) { - negations.push(fragment); - continue; - } - if (expr.length === 0) - expr = fragment; - else - expr = pendingOr ? `${expr} OR ${fragment}` : `${expr} ${defaultOp} ${fragment}`; - pendingOr = false; - } - for (const negation of negations) - expr = `(${expr}) NOT ${negation}`; - return expr.length > 0 ? expr : null; +async function buildKnowledgeAgentContextPack(options) { + const now = options.now ?? new Date; + const source = options.source ?? "search"; + const purpose = options.purpose ?? (source === "loops" || source === "runs" ? "proposal" : "agent_context"); + const maxTokens = coerceMaxTokens(options.maxTokens); + const maxItems = coerceMaxItems(options.maxItems, options.limit); + const query2 = normalizeText(options.query ?? options.topic ?? ""); + if (purpose === "proposal" && source !== "search" && !query2) { + throw new Error("Proposal context requires --topic <text> or a positional topic."); + } + if (source !== "search") + migrateKnowledgeDb(options.dbPath); + const sinceForKey = parseSince(options.since, now).cutoff ?? options.since ?? ""; + const draft = source === "search" ? await buildSearchDraft(options, maxItems) : await buildRunDraft(options, maxItems, now); + const sortedEvidence = draft.evidence.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, maxItems); + const sortedCitations = draft.citations.filter((citation, index, rows) => rows.findIndex((entry) => entry.id === citation.id) === index).sort((a, b) => a.id.localeCompare(b.id)); + const duplicateCandidates = options.dedupe ? duplicateCandidatesFor(sortedEvidence) : draft.duplicateCandidates.filter((candidate) => candidate.evidence_ids.every((id) => sortedEvidence.some((entry) => entry.id === id))); + const outline = outlineFor({ + source, + purpose, + query: query2, + evidence: sortedEvidence, + duplicates: duplicateCandidates + }); + const pack = { + ok: true, + format: "knowledge-agent-context-pack", + version: 1, + created_at: now.toISOString(), + source, + purpose, + query: query2, + topic: options.topic ?? null, + since: options.since ?? null, + dry_run: true, + idempotency_key: stableId5("ctx", [ + source, + purpose, + query2, + sinceForKey, + options.dedupe === true ? "dedupe" : "no-dedupe", + options.semantic === true ? "semantic" : "keyword", + options.modelRef ?? "", + options.limit ?? "", + maxTokens, + maxItems, + sortedEvidence.map((entry) => entry.id).join(","), + sortedCitations.map((entry) => entry.id).join(",") + ].join("\x00"), 20), + budgets: { + max_tokens: maxTokens, + estimated_tokens: 0, + max_items: maxItems, + items_included: sortedEvidence.length, + items_available: draft.available, + items_truncated: Math.max(0, draft.available - sortedEvidence.length), + token_budget_exceeded: false + }, + safety: { + raw_artifact_content_included: false, + durable_writes_performed: false, + redactions: draft.redactions, + reminders: baseSafetyReminders(source) + }, + citations: sortedCitations, + evidence: sortedEvidence, + duplicate_candidates: duplicateCandidates, + outline, + warnings: draft.warnings, + message: `${sortedEvidence.length} bounded evidence item(s), estimated under ${maxTokens} token(s)` }; - const and = compose("AND"); - const or = compose("OR"); - return { and, or: or !== and ? or : null }; + pruneCitations(pack); + return fitPackToBudget(pack); } -function escapeLikeTerm(term) { - return term.replace(/[\\%_]/g, (char) => `\\${char}`); + +// src/conflict-agent.ts +import { randomUUID as randomUUID8 } from "crypto"; + +// src/sync.ts +import { createHash as createHash12, randomUUID as randomUUID7 } from "crypto"; +import { existsSync as existsSync9, readFileSync as readFileSync11 } from "fs"; +import { hostname } from "os"; +import { fileURLToPath as fileURLToPath2 } from "url"; +import { extname, relative as relative3, resolve as resolve3, sep as sep3 } from "path"; +var KNOWLEDGE_SYNC_TABLES = [ + "sources", + "wiki_pages", + "source_revisions", + "chunks", + "chunk_embeddings", + "wiki_backlinks", + "citations", + "knowledge_indexes", + "runs", + "run_events", + "provider_usage", + "redaction_findings", + "storage_objects", + "audit_events", + "approval_gates", + "vector_index_entries", + "reindex_queue", + "knowledge_machines", + "knowledge_sync_snapshots", + "knowledge_sync_changes", + "knowledge_sync_conflicts", + "knowledge_sync_table_clocks", + "knowledge_sync_imports" +]; +var KNOWLEDGE_SYNC_PROTOCOL_VERSION = 2; +var KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION = 1; +var PRIMARY_KEYS = { + sources: ["id"], + wiki_pages: ["id"], + source_revisions: ["id"], + chunks: ["id"], + chunk_embeddings: ["id"], + wiki_backlinks: ["from_page_id", "to_page_id"], + citations: ["id"], + knowledge_indexes: ["id"], + runs: ["id"], + run_events: ["id"], + provider_usage: ["id"], + redaction_findings: ["id"], + storage_objects: ["id"], + audit_events: ["id"], + approval_gates: ["id"], + vector_index_entries: ["id"], + reindex_queue: ["id"], + knowledge_machines: ["machine_id"], + knowledge_sync_snapshots: ["id"], + knowledge_sync_changes: ["id"], + knowledge_sync_conflicts: ["id"], + knowledge_sync_table_clocks: ["table_name", "machine_id"], + knowledge_sync_imports: ["bundle_id"] +}; +var TABLE_SYNC_EXCLUDES = new Set([ + "storage_objects", + "knowledge_sync_changes", + "knowledge_sync_table_clocks", + "knowledge_sync_imports" +]); +function nowIso(now = new Date) { + return now.toISOString(); } -function likeParams(terms, fieldsPerTerm) { - return terms.flatMap((term) => Array.from({ length: fieldsPerTerm }, () => `%${escapeLikeTerm(term)}%`)); +function makeSyncId(prefix) { + return `${prefix}_${Date.now().toString(36)}_${randomUUID7().slice(0, 8)}`; } -function scoreFromRank(rank, index) { - const rankScore = Number.isFinite(rank) ? 1 / (1 + Math.abs(rank)) : 0; - const orderScore = 1 / (1 + index); - return roundScore(Math.max(rankScore, orderScore)); +function defaultSyncMachineId(input) { + const explicit = input?.trim(); + if (explicit) + return explicit; + return process.env.HASNA_MACHINE_ID ?? process.env.OPEN_MACHINES_MACHINE_ID ?? process.env.MACHINE_ID ?? hostname(); } -function catalogScore(haystack, terms) { - if (terms.length === 0) - return 0; - const matched = terms.filter((term) => haystack.includes(term)).length; - if (matched === 0) - return 0; - return roundScore(Math.min(0.85, 0.35 + matched / terms.length * 0.5)); +function stableJson(value) { + if (Array.isArray(value)) + return `[${value.map(stableJson).join(",")}]`; + if (value && typeof value === "object") { + const record = value; + return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`; + } + return JSON.stringify(value); } -function semanticScore(score) { - return roundScore(Math.max(0, Math.min(1, (score + 1) / 2))); +function sha256(value) { + return `sha256:${createHash12("sha256").update(value).digest("hex")}`; } -function roundScore(score) { - return Number(score.toFixed(6)); +function count2(db, table) { + const row = db.query(`SELECT COUNT(*) AS n FROM ${table}`).get(); + return row?.n ?? 0; } -function combinedScore(scores, citation) { - const keyword = scores.keyword ?? 0; - const semantic = scores.semantic ?? 0; - const catalog = scores.catalog ?? 0; - const citationBoost = citation?.chunk_id ? 0.05 : 0; - return roundScore(Math.min(1, keyword * 0.55 + semantic * 0.4 + catalog * 0.35 + citationBoost)); +function parseJson(value, fallback) { + try { + return JSON.parse(value); + } catch { + return fallback; + } } -function existingProvenance(metadata) { - const provenance = metadata.provenance; - return provenance && typeof provenance === "object" && !Array.isArray(provenance) ? provenance : null; +function quoteIdent(identifier) { + return `"${identifier.replace(/"/g, '""')}"`; } -function provenanceForChunk2(row) { - const metadata = parseJsonObject4(row.chunk_metadata_json); - const existing = existingProvenance(metadata); - if (existing) - return existing; - if (!row.source_revision_id && !row.source_uri) +function coerceForSqlite(value) { + if (value === undefined || value === null) return null; - return sourceProvenance({ - source_ref: metadataString3(metadata, ["source_ref"]), - source_uri: row.source_uri ?? metadataString3(metadata, ["source_uri"]), - source_kind: row.source_kind ?? metadataString3(metadata, ["source_kind"]), - source_revision_id: row.source_revision_id, - revision: row.revision ?? metadataString3(metadata, ["revision"]), - hash: row.hash ?? metadataString3(metadata, ["hash"]), - chunk_id: row.chunk_id, - start_offset: row.start_offset ?? metadataNumber3(metadata, ["start_offset"]), - end_offset: row.end_offset ?? metadataNumber3(metadata, ["end_offset"]), - status: metadataString3(metadata, ["status"]), - resolver: "open-files-read-only" - }); + if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") + return value; + if (value instanceof Date) + return value.toISOString(); + if (Buffer.isBuffer(value) || value instanceof Uint8Array) + return value; + if (typeof value === "object") + return JSON.stringify(value); + return String(value); } -function selectFtsChunks(db, ftsQuery, limit) { - if (!ftsQuery) - return []; - try { - return runFtsChunkQuery(db, ftsQuery, limit); - } catch { - return []; - } +function filterExistingTables(db, tables) { + return tables.filter((table) => tableExists2(db, table)); } -function runFtsChunkQuery(db, ftsQuery, limit) { - return db.query(`SELECT - chunks_fts.chunk_id, - c.kind AS chunk_kind, - c.wiki_page_id, - c.text, - c.token_count, - c.start_offset, - c.end_offset, - c.metadata_json AS chunk_metadata_json, - c.source_revision_id, - sr.revision, - sr.hash, - s.uri AS source_uri, - s.kind AS source_kind, - s.title AS source_title, - wp.path AS wiki_path, - wp.title AS wiki_title, - wp.artifact_uri AS wiki_artifact_uri, - wp.content_hash AS wiki_content_hash, - wp.status AS wiki_status, - wp.metadata_json AS wiki_metadata_json, - bm25(chunks_fts, 0.0, 1.0, 5.0, 3.0) AS rank - FROM chunks_fts - JOIN chunks c ON c.id = chunks_fts.chunk_id - LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id - LEFT JOIN sources s ON s.id = sr.source_id - LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id - WHERE chunks_fts MATCH ? - ORDER BY rank ASC - LIMIT ?`).all(ftsQuery, limit); +function tableExists2(db, table) { + const row = db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table); + return Boolean(row); } -function catalogWhere(fields, terms) { - if (terms.length === 0) - return "1 = 0"; - const clauses = terms.map(() => `(${fields.map((field) => `lower(COALESCE(${field}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`); - return clauses.join(" OR "); +function localColumns(db, table) { + const rows = db.query(`PRAGMA table_info(${quoteIdent(table)})`).all(); + return new Set(rows.map((row) => row.name)); +} +function filterLocalColumns(db, table, columns) { + const allowed = localColumns(db, table); + return columns.filter((column) => allowed.has(column)); +} +function resolveSyncTables(tables) { + if (!tables || tables.length === 0) + return [...KNOWLEDGE_SYNC_TABLES]; + const allowed = new Set(KNOWLEDGE_SYNC_TABLES); + const requested = tables.map((table) => table.trim()).filter(Boolean); + const invalid = requested.filter((table) => !allowed.has(table)); + if (invalid.length > 0) + throw new Error(`Unknown knowledge sync table(s): ${invalid.join(", ")}`); + return requested; +} +function rowKey(table, row) { + const primaryKeys = PRIMARY_KEYS[table]; + return primaryKeys.map((key) => `${key}=${JSON.stringify(row[key] ?? null)}`).join("&"); +} +var RAW_PAYLOAD_METADATA_KEYS = new Set([ + "raw", + "raw_bytes", + "raw_content", + "content_base64", + "source_bytes", + "source_content", + "body_bytes" +]); +function sanitizeConflictEvidenceValue(value, depth = 0) { + if (depth > 8) + return "[truncated-depth]"; + if (typeof value === "string") + return value.length > 4000 ? `${value.slice(0, 4000)}...[truncated]` : value; + if (value === null || typeof value !== "object") + return value; + if (Array.isArray(value)) + return value.slice(0, 50).map((entry) => sanitizeConflictEvidenceValue(entry, depth + 1)); + const output = {}; + for (const [key, entry] of Object.entries(value)) { + if (RAW_PAYLOAD_METADATA_KEYS.has(key.toLowerCase())) + continue; + output[key] = sanitizeConflictEvidenceValue(entry, depth + 1); + } + return output; +} +function sanitizeConflictEvidenceRow(row) { + if (!row) + return null; + return sanitizeConflictEvidenceValue(row); } -function selectWikiPages(db, terms, limit) { - const fields = ["path", "title", "artifact_uri", "metadata_json"]; - return db.query(`SELECT id, path, title, artifact_uri, content_hash, status, metadata_json - FROM wiki_pages - WHERE status = 'active' AND (${catalogWhere(fields, terms)}) - ORDER BY updated_at DESC - LIMIT ?`).all(...likeParams(terms, fields.length), limit); +function hashValue(value) { + return sha256(stableJson(value)); } -function selectKnowledgeIndexes(db, terms, limit) { - const fields = ["kind", "name", "shard_key", "artifact_uri", "metadata_json"]; - return db.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json - FROM knowledge_indexes - WHERE ${catalogWhere(fields, terms)} - ORDER BY updated_at DESC - LIMIT ?`).all(...likeParams(terms, fields.length), limit); +function normalizeRowForHash(row, artifactUriToKey) { + const normalized = {}; + for (const [key, value] of Object.entries(row)) { + if (key === "artifact_uri" && typeof value === "string" && artifactUriToKey.has(value)) { + normalized[key] = `artifact:${artifactUriToKey.get(value)}`; + } else { + normalized[key] = value; + } + } + return normalized; } -function readLegacyItems(path) { - if (!path || !existsSync8(path)) - return []; - try { - const parsed = JSON.parse(readFileSync9(path, "utf8")); - if (!parsed || !Array.isArray(parsed.items)) - return []; - return parsed.items.filter((item) => { - return Boolean(item && typeof item === "object" && typeof item.id === "string" && typeof item.title === "string" && typeof item.content === "string"); - }); - } catch { +function rowHash(row, artifactUriToKey = new Map) { + return hashValue(normalizeRowForHash(row, artifactUriToKey)); +} +function tableRows(db, table) { + if (!tableExists2(db, table)) return []; - } + return db.query(`SELECT * FROM ${quoteIdent(table)} ORDER BY rowid ASC`).all(); } -function legacyItemHaystack(item) { - return [ - item.id, - item.short_id, - item.title, - item.content, - item.url, - ...item.tags ?? [] - ].filter((value) => typeof value === "string" && value.length > 0).join(" ").toLowerCase(); +function tableContentHash(table, rows, artifactUriToKey = new Map) { + return hashValue(rows.map((row) => ({ + key: rowKey(table, row), + hash: rowHash(row, artifactUriToKey) + })).sort((a, b) => a.key.localeCompare(b.key))); } -function selectItems(items, terms, limit) { - if (terms.length === 0) +function tableClock(db, table, machineId) { + return db.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get(table, machineId) ?? null; +} +function listTableClocks(db) { + if (!tableExists2(db, "knowledge_sync_table_clocks")) return []; - return items.filter((item) => item.archived !== true).map((item) => ({ item, haystack: legacyItemHaystack(item) })).filter(({ haystack }) => terms.some((term) => haystack.includes(term))).map(({ item, haystack }) => ({ item, score: catalogScore(haystack, terms) })).sort((a, b) => b.score - a.score || a.item.id.localeCompare(b.item.id)).slice(0, limit); + return db.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all(); } -function selectLegacyItems(path, terms, limit) { - return selectItems(readLegacyItems(path), terms, limit); +function updateTableClock(db, input) { + const now = input.now ?? nowIso(); + const existing = tableClock(db, input.table, input.machineId); + const createdAt = existing?.created_at ?? now; + db.query(` + INSERT INTO knowledge_sync_table_clocks ( + table_name, machine_id, logical_clock, high_water_hash, high_water_bundle_id, + origin_machine_id, updated_by_machine_id, last_applied_at, metadata_json, + created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(table_name, machine_id) DO UPDATE SET + logical_clock = excluded.logical_clock, + high_water_hash = excluded.high_water_hash, + high_water_bundle_id = excluded.high_water_bundle_id, + origin_machine_id = excluded.origin_machine_id, + updated_by_machine_id = excluded.updated_by_machine_id, + last_applied_at = excluded.last_applied_at, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at + `).run(input.table, input.machineId, input.logicalClock, input.highWaterHash, input.highWaterBundleId ?? null, input.originMachineId ?? input.machineId, input.updatedByMachineId ?? input.machineId, input.lastAppliedAt ?? now, JSON.stringify(input.metadata ?? {}), createdAt, now); + const row = tableClock(db, input.table, input.machineId); + if (!row) + throw new Error(`Failed to record sync clock for ${input.table}:${input.machineId}`); + return row; } -function chunkResult(row, keywordScore) { - const metadata = parseJsonObject4(row.chunk_metadata_json); - const provenance = provenanceForChunk2(row); - const sourceRef = metadataString3(metadata, ["source_ref"]); - const sourceUri = row.source_uri ?? metadataString3(metadata, ["source_uri"]); - const isWiki = Boolean(row.wiki_page_id); - const result = { - kind: isWiki ? "wiki_chunk" : "source_chunk", - id: row.chunk_id, - title: isWiki ? row.wiki_title : row.source_title, - text: row.text, - score: 0, - scores: { keyword: keywordScore }, - source: sourceUri || sourceRef ? { - uri: sourceUri, - ref: sourceRef, - kind: row.source_kind ?? metadataString3(metadata, ["source_kind"]), - revision: row.revision ?? metadataString3(metadata, ["revision"]), - hash: row.hash ?? metadataString3(metadata, ["hash"]) - } : null, - citation: { - chunk_id: row.chunk_id, - start_offset: row.start_offset, - end_offset: row.end_offset +function prepareExportTableClock(db, input) { + const existing = tableClock(db, input.table, input.machineId); + const logicalClock = existing?.high_water_hash === input.highWaterHash ? existing.logical_clock : (existing?.logical_clock ?? 0) + 1; + const row = input.record ? updateTableClock(db, { + table: input.table, + machineId: input.machineId, + logicalClock, + highWaterHash: input.highWaterHash, + highWaterBundleId: null, + originMachineId: existing?.origin_machine_id ?? input.machineId, + updatedByMachineId: input.machineId, + lastAppliedAt: input.now, + metadata: { + source: "export", + row_count: input.rowCount }, - artifact: isWiki ? { - uri: row.wiki_artifact_uri, - path: row.wiki_path, - hash: row.wiki_content_hash, - shard_key: row.wiki_path - } : null, - provenance, - reasons: ["keyword_match"] + now: input.now + }) : { + table_name: input.table, + machine_id: input.machineId, + logical_clock: logicalClock, + high_water_hash: input.highWaterHash, + high_water_bundle_id: existing?.high_water_bundle_id ?? null, + origin_machine_id: existing?.origin_machine_id ?? input.machineId, + updated_by_machine_id: input.machineId, + last_applied_at: input.now, + metadata_json: "{}", + created_at: existing?.created_at ?? input.now, + updated_at: input.now }; - result.score = combinedScore(result.scores, result.citation); - return result; -} -function legacyItemResult(item, keywordScore) { - const uri = `knowledge://item/${encodeURIComponent(item.id)}`; - const result = { - kind: "legacy_item", - id: item.id, - title: item.title, - text: item.content, - score: 0, - scores: { keyword: keywordScore }, - source: { - uri, - ref: uri, - kind: "legacy_item", - revision: null, - hash: null - }, - citation: null, - artifact: null, - provenance: null, - reasons: ["legacy_note_match", "keyword_match"] + return { + table: input.table, + machine_id: input.machineId, + logical_clock: row.logical_clock, + high_water_hash: input.highWaterHash, + high_water_bundle_id: row.high_water_bundle_id, + row_count: input.rowCount, + updated_at: row.updated_at }; - result.score = combinedScore(result.scores, result.citation); - return result; } -function wikiPageResult(row, terms) { - const metadata = parseJsonObject4(row.metadata_json); - const score = catalogScore(`${row.path} ${row.title} ${row.artifact_uri ?? ""} ${row.metadata_json}`.toLowerCase(), terms); - const result = { - kind: "wiki_page", - id: row.id, - title: row.title, - text: null, - score: 0, - scores: { catalog: score }, - source: null, - citation: null, - artifact: { - uri: row.artifact_uri, - path: row.path, - hash: row.content_hash, - shard_key: row.path +function finalizeExportTableClock(db, clock, bundleId, record, now) { + clock.high_water_bundle_id = bundleId; + if (!record) + return; + updateTableClock(db, { + table: clock.table, + machineId: clock.machine_id, + logicalClock: clock.logical_clock, + highWaterHash: clock.high_water_hash, + highWaterBundleId: bundleId, + originMachineId: clock.machine_id, + updatedByMachineId: clock.machine_id, + lastAppliedAt: now, + metadata: { + source: "export", + row_count: clock.row_count }, - provenance: existingProvenance(metadata), - reasons: ["wiki_catalog_match"] - }; - result.score = combinedScore(result.scores, result.citation); - return result; + now + }); } -function indexResult(row, terms) { - const metadata = parseJsonObject4(row.metadata_json); - const score = catalogScore(`${row.kind} ${row.name} ${row.shard_key ?? ""} ${row.artifact_uri ?? ""} ${row.metadata_json}`.toLowerCase(), terms); - const result = { - kind: "knowledge_index", - id: row.id, - title: row.name, - text: null, - score: 0, - scores: { catalog: score }, - source: null, - citation: null, - artifact: { - uri: row.artifact_uri, - path: metadataString3(metadata, ["artifact_key"]), - hash: metadataString3(metadata, ["content_hash"]), - shard_key: row.shard_key - }, - provenance: existingProvenance(metadata), - reasons: ["index_catalog_match"] - }; - result.score = combinedScore(result.scores, result.citation); - return result; +function bundleTableClock(bundle, table) { + return bundle.table_clocks?.find((clock) => clock.table === table) ?? null; } -function mergeResult(results, entry) { - const key = `${entry.kind}:${entry.id}`; - const existing = results.get(key); - if (!existing) { - results.set(key, entry); - return; - } - existing.scores = { - keyword: Math.max(existing.scores.keyword ?? 0, entry.scores.keyword ?? 0) || undefined, - semantic: Math.max(existing.scores.semantic ?? 0, entry.scores.semantic ?? 0) || undefined, - catalog: Math.max(existing.scores.catalog ?? 0, entry.scores.catalog ?? 0) || undefined - }; - existing.reasons = unique([...existing.reasons, ...entry.reasons]); - existing.text = existing.text ?? entry.text; - existing.title = existing.title ?? entry.title; - existing.source = existing.source ?? entry.source; - existing.citation = existing.citation ?? entry.citation; - existing.artifact = existing.artifact ?? entry.artifact; - existing.provenance = existing.provenance ?? entry.provenance; - existing.score = combinedScore(existing.scores, existing.citation); +function staleIncomingClock(existing, incoming) { + if (!existing || !incoming) + return false; + return incoming.logical_clock < existing.logical_clock; } -function sortResults(results) { - const kindOrder = { - source_chunk: 0, - wiki_chunk: 1, - legacy_item: 2, - wiki_page: 3, - knowledge_index: 4 - }; - return results.sort((a, b) => { - if (b.score !== a.score) - return b.score - a.score; - return kindOrder[a.kind] - kindOrder[b.kind] || a.id.localeCompare(b.id); +function upsertSqliteRows(db, table, rows) { + if (rows.length === 0) + return 0; + const columns = filterLocalColumns(db, table, Object.keys(rows[0])); + if (columns.length === 0) + return 0; + const primaryKeys = PRIMARY_KEYS[table]; + const columnList = columns.map(quoteIdent).join(", "); + const placeholders2 = columns.map(() => "?").join(", "); + const keyList = primaryKeys.map(quoteIdent).join(", "); + const updateColumns = columns.filter((column) => !primaryKeys.includes(column)); + const fallbackKey = primaryKeys[0]; + const setClause = updateColumns.length > 0 ? updateColumns.map((column) => `${quoteIdent(column)} = excluded.${quoteIdent(column)}`).join(", ") : `${quoteIdent(fallbackKey)} = excluded.${quoteIdent(fallbackKey)}`; + const statement = db.query(`INSERT INTO ${quoteIdent(table)} (${columnList}) VALUES (${placeholders2}) + ON CONFLICT (${keyList}) DO UPDATE SET ${setClause}`); + const insert = db.transaction((batch) => { + for (const row of batch) + statement.run(...columns.map((column) => coerceForSqlite(row[column]))); }); + insert(rows); + return rows.length; } -async function hybridSearch(options) { - const query2 = options.query.trim(); - if (!query2) - throw new Error("Search query is required."); - const limit = Math.max(1, Math.min(options.limit ?? 10, 100)); - const offset = Math.max(0, Math.floor(options.offset ?? 0)); - const window = offset + limit; - const terms = queryTerms(query2); - const ftsMatch = buildFtsMatch(query2); - const semanticEnabled = options.semantic === true || options.fake === true || Boolean(options.modelRef); - const warnings = []; - let semanticProvider = null; - let semanticModel = null; - let semanticDimensions = null; - let keywordCount = 0; - let catalogCount = 0; - let semanticCount = 0; - const merged = new Map; - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - try { - const ftsDepth = Math.max(window * 3, 20); - let ftsRows = selectFtsChunks(db, ftsMatch.and, ftsDepth); - if (ftsRows.length === 0 && ftsMatch.or) { - ftsRows = selectFtsChunks(db, ftsMatch.or, ftsDepth); +function parseRowKeyValues(table, key) { + const primaryKeys = PRIMARY_KEYS[table]; + const values = []; + let rest = key; + for (let index = 0;index < primaryKeys.length; index += 1) { + const primaryKey = primaryKeys[index]; + const prefix = `${primaryKey}=`; + if (!rest.startsWith(prefix)) + return null; + const remaining = rest.slice(prefix.length); + const nextPrimaryKey = primaryKeys[index + 1]; + const marker = nextPrimaryKey ? `&${nextPrimaryKey}=` : null; + const markerIndex = marker ? remaining.indexOf(marker) : -1; + const encoded = markerIndex >= 0 ? remaining.slice(0, markerIndex) : remaining; + try { + values.push(JSON.parse(encoded)); + } catch { + return null; } - keywordCount = ftsRows.length; - ftsRows.forEach((row, index) => mergeResult(merged, chunkResult(row, scoreFromRank(row.rank, index)))); - const wikiRows = selectWikiPages(db, terms, Math.max(window, 10)); - const indexRows = selectKnowledgeIndexes(db, terms, Math.max(window, 10)); - const legacyRows = selectLegacyItems(options.legacyStorePath, terms, Math.max(window, 10)); - catalogCount = wikiRows.length + indexRows.length; - keywordCount += legacyRows.length; - legacyRows.forEach(({ item, score }) => mergeResult(merged, legacyItemResult(item, score))); - wikiRows.forEach((row) => mergeResult(merged, wikiPageResult(row, terms))); - indexRows.forEach((row) => mergeResult(merged, indexResult(row, terms))); - } finally { - db.close(); + rest = markerIndex >= 0 && marker ? remaining.slice(markerIndex + 1) : ""; } - if (semanticEnabled) { - try { - const semantic = await searchVectorIndex({ - dbPath: options.dbPath, - query: query2, - limit: Math.max(window * 3, 20), - config: options.config, - env: options.env, - modelRef: options.modelRef, - dimensions: options.dimensions, - fake: options.fake, - batchSize: options.batchSize, - maxParallelCalls: options.maxParallelCalls - }); - semanticProvider = semantic.provider; - semanticModel = semantic.model; - semanticDimensions = semantic.dimensions; - semanticCount = semantic.results.length; - for (const row of semantic.results) { - const result = { - kind: "source_chunk", - id: row.chunk_id, - title: null, - text: row.text, - score: 0, - scores: { semantic: semanticScore(row.score) }, - source: { - uri: row.source_uri, - ref: row.source_ref, - kind: row.provenance?.source_kind ?? null, - revision: row.revision, - hash: row.hash - }, - citation: { - chunk_id: row.chunk_id, - start_offset: row.provenance?.start_offset ?? null, - end_offset: row.provenance?.end_offset ?? null - }, - artifact: null, - provenance: row.provenance, - reasons: ["semantic_match"] - }; - result.score = combinedScore(result.scores, result.citation); - mergeResult(merged, result); - } - } catch (error) { - warnings.push(`semantic_search_failed: ${error instanceof Error ? error.message : String(error)}`); + return rest.length === 0 ? values : null; +} +function primaryKeyWhereClause(table) { + return PRIMARY_KEYS[table].map((key) => `${quoteIdent(key)} = ?`).join(" AND "); +} +function latestImportedRowHashes(db, table, sourceMachineId) { + if (!tableExists2(db, "knowledge_sync_changes")) + return new Map; + const rows = db.query(`SELECT entity_id, next_hash + FROM knowledge_sync_changes + WHERE origin_machine_id = ? AND entity_kind = ? + ORDER BY created_at ASC, id ASC`).all(sourceMachineId, table); + const latest = new Map; + for (const row of rows) + latest.set(row.entity_id, row.next_hash); + return latest; +} +function removeChunkDerivedRows(db, chunkId) { + if (tableExists2(db, "chunks_fts")) + db.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(chunkId); + if (tableExists2(db, "chunk_embeddings")) + db.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run(chunkId); + if (tableExists2(db, "vector_index_entries")) + db.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run(chunkId); + if (tableExists2(db, "citations")) + db.query("DELETE FROM citations WHERE chunk_id = ?").run(chunkId); +} +function deleteSqliteRowByKey(db, table, key) { + const values = parseRowKeyValues(table, key); + if (!values) + return false; + const where = primaryKeyWhereClause(table); + const existing = db.query(`SELECT * FROM ${quoteIdent(table)} WHERE ${where} LIMIT 1`).get(...values); + if (!existing) + return false; + if (table === "chunks" && typeof existing.id === "string") + removeChunkDerivedRows(db, existing.id); + db.query(`DELETE FROM ${quoteIdent(table)} WHERE ${where}`).run(...values); + return true; +} +function refreshChunkFtsRows(db, rows) { + if (!tableExists2(db, "chunks_fts")) + return; + for (const row of rows) { + const chunkId = typeof row.id === "string" ? row.id : null; + const text = typeof row.text === "string" ? row.text : null; + if (!chunkId || text === null) + continue; + let title = ""; + let sourceUri = ""; + const sourceRevisionId = typeof row.source_revision_id === "string" ? row.source_revision_id : null; + if (sourceRevisionId) { + const source = db.query(`SELECT s.title, s.uri + FROM source_revisions sr + JOIN sources s ON s.id = sr.source_id + WHERE sr.id = ? + LIMIT 1`).get(sourceRevisionId); + title = source?.title ?? ""; + sourceUri = source?.uri ?? ""; + } + if (!sourceUri && typeof row.metadata_json === "string") { + const metadata = parseJson(row.metadata_json, {}); + sourceUri = typeof metadata.source_uri === "string" ? metadata.source_uri : ""; } + db.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(chunkId); + db.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(chunkId, text, title, sourceUri); + } +} +function refreshDerivedRowsForImport(db, table, rows) { + if (table === "chunks") + refreshChunkFtsRows(db, rows); +} +function assertInside2(root, target) { + const rel = relative3(root, target); + return rel !== ".." && !rel.startsWith("..") && !rel.startsWith(`..${sep3}`); +} +function keyForArtifactRow(row, artifactsDir) { + const metadata = parseJson(row.metadata_json, {}); + if (typeof metadata.key === "string") + return metadata.key; + if (!row.artifact_uri.startsWith("file://")) + return null; + try { + const path = fileURLToPath2(row.artifact_uri); + const root = resolve3(artifactsDir); + const target = resolve3(path); + if (!assertInside2(root, target)) + return null; + const rel = relative3(root, target).replace(/\\/g, "/"); + return rel ? normalizeArtifactKey(rel) : null; + } catch { + return null; + } +} +var TEXT_ARTIFACT_EXTENSIONS = new Set([".csv", ".html", ".json", ".jsonl", ".log", ".md", ".txt", ".xml", ".yaml", ".yml"]); +function isTextArtifact(contentType, key) { + const normalized = contentType?.toLowerCase() ?? ""; + if (normalized.startsWith("text/")) + return true; + if (/(json|markdown|xml|yaml|csv)/.test(normalized)) + return true; + return key ? TEXT_ARTIFACT_EXTENSIONS.has(extname(key).toLowerCase()) : false; +} +function artifactUriToKey(artifacts) { + const map = new Map; + for (const artifact of artifacts) { + if (artifact.key) + map.set(artifact.artifact_uri, artifact.key); } - const ranked = sortResults(Array.from(merged.values())); - const results = ranked.slice(offset, offset + limit); - return { - query: query2, - limit, - offset, - mode: { - keyword: true, - catalog: true, - semantic: semanticEnabled - }, - semantic_provider: semanticProvider, - semantic_model: semanticModel, - semantic_dimensions: semanticDimensions, - counts: { - keyword_results: keywordCount, - catalog_results: catalogCount, - semantic_results: semanticCount, - merged_results: results.length - }, - warnings, - results - }; + return map; } -async function hybridSearchLegacyStore(options) { - return hybridSearchItems(readLegacyItems(options.legacyStorePath), options, ["knowledge_db_missing"]); +function artifactFingerprint(artifact) { + return hashValue({ + key: artifact.key, + kind: artifact.kind, + hash: artifact.hash, + size_bytes: artifact.size_bytes + }); } -async function hybridSearchItems(items, options, baseWarnings = []) { - const query2 = options.query.trim(); - if (!query2) - throw new Error("Search query is required."); - const limit = Math.max(1, Math.min(options.limit ?? 10, 100)); - const offset = Math.max(0, Math.floor(options.offset ?? 0)); - const terms = queryTerms(query2); - const semanticEnabled = options.semantic === true || options.fake === true || Boolean(options.modelRef); - const merged = new Map; - const itemRows = selectItems(items, terms, Math.max(offset + limit, 10)); - itemRows.forEach(({ item, score }) => mergeResult(merged, legacyItemResult(item, score))); - const warnings = [...baseWarnings]; - if (semanticEnabled) - warnings.push("semantic_search_requires_local_catalog"); - const results = sortResults(Array.from(merged.values())).slice(offset, offset + limit); +function artifactIdentity(artifact) { + return artifact.key ?? artifact.artifact_uri; +} +function canReferenceExistingS3Artifact(artifact, targetStorage) { + return artifact.artifact_uri.startsWith("s3://") && targetStorage.artifact_store.type === "s3" && artifact.artifact_uri.startsWith(targetStorage.artifact_store.uri_prefix); +} +function tableCounts(db) { + return Object.fromEntries(KNOWLEDGE_SYNC_TABLES.map((table) => [table, tableExists2(db, table) ? count2(db, table) : 0])); +} +function artifactHashes(db) { + return db.query(`SELECT artifact_uri, kind, hash, size_bytes + FROM storage_objects + ORDER BY artifact_uri ASC`).all(); +} +function machineFromTopologyEntry(entry, now) { return { - query: query2, - limit, - offset, - mode: { - keyword: true, - catalog: true, - semantic: semanticEnabled - }, - semantic_provider: null, - semantic_model: null, - semantic_dimensions: null, - counts: { - keyword_results: itemRows.length, - catalog_results: 0, - semantic_results: 0, - merged_results: results.length - }, - warnings, - results + machine_id: entry.machine_id, + hostname: entry.hostname, + platform: entry.platform, + user_label: entry.user, + workspace_home: entry.workspace_path, + tailscale_dns: entry.tailscale.dns_name, + tailscale_ips_json: JSON.stringify(entry.tailscale.ips), + ssh_target: entry.ssh.command_target, + last_seen_at: entry.local || entry.tailscale.online === true || entry.heartbeat_status === "online" ? now : entry.last_heartbeat_at, + capabilities_json: JSON.stringify({ + route_hints: entry.route_hints, + heartbeat_status: entry.heartbeat_status, + manifest_declared: entry.manifest_declared + }), + metadata_json: JSON.stringify({ + ...entry.metadata, + source: entry.source, + tags: entry.tags, + tailscale: entry.tailscale, + ssh: entry.ssh + }), + created_at: now, + updated_at: now }; } - -// src/retrieval.ts -function stableId4(prefix, value) { - return `${prefix}_${createHash10("sha256").update(value).digest("hex").slice(0, 20)}`; +function parseJsonRecord(value) { + if (!value) + return {}; + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } } -function normalizeQuery(query2) { - return query2.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase(); +function parseJsonArray(value) { + if (!value) + return []; + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } } -function queryTerms2(query2) { - return Array.from(new Set(normalizeQuery(query2).match(/[\p{L}\p{N}_]+/gu) ?? [])).slice(0, 16); +function recordFromUnknown(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : {}; } -function textForResult(result) { - return [result.title, result.text].filter(Boolean).join(" ").toLowerCase(); +function compactRecord(input) { + return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)); } -function exactScore(result, terms) { - if (terms.length === 0) - return 0; - const text = textForResult(result); - const matched = terms.filter((term) => text.includes(term)).length; - return Number((matched / terms.length).toFixed(6)); +function canonicalJson(value) { + if (Array.isArray(value)) + return `[${value.map(canonicalJson).join(",")}]`; + if (value && typeof value === "object") { + return `{${Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; + } + return JSON.stringify(value); } -function hasReadOnlyProvenance(provenance) { - if (!provenance) - return true; - if ("read_only" in provenance) - return provenance.read_only === true; - if ("read_only_sources" in provenance) - return provenance.read_only_sources === true; - return true; +function stableResolverEvidence(value) { + const { recorded_at: _recordedAt, ...stable } = value; + return stable; } -function isStale(provenance) { - if (!provenance) +function stringFromUnknown(value) { + return typeof value === "string" && value.length > 0 ? value : null; +} +function numberFromUnknown(value) { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} +function booleanFromUnknown(value) { + return typeof value === "boolean" ? value : null; +} +function stringArrayFromUnknown(value) { + return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : []; +} +function cacheabilityFromUnknown(value) { + const raw = recordFromUnknown(value); + const observedAt = stringFromUnknown(raw.observed_at); + const sourceAuthority = stringFromUnknown(raw.source_authority); + if (!observedAt || !sourceAuthority) + return null; + return { + observed_at: observedAt, + verified_at: stringFromUnknown(raw.verified_at), + expires_at: stringFromUnknown(raw.expires_at), + ttl_ms: numberFromUnknown(raw.ttl_ms), + source_authority: sourceAuthority, + confidence: stringFromUnknown(raw.confidence), + cacheable: raw.cacheable === true, + stale: raw.stale === true, + reasons: stringArrayFromUnknown(raw.reasons) + }; +} +function cacheabilityIsFresh(cacheability, now) { + if (!cacheability || cacheability.stale) return false; - if ("stale" in provenance && provenance.stale) + if (!cacheability.expires_at) return true; - if ("status" in provenance) - return isStaleStatus(provenance.status); - return false; + const expires = Date.parse(cacheability.expires_at); + const observed = Date.parse(now); + return Number.isNaN(expires) || Number.isNaN(observed) || expires > observed; } -function freshnessScore(result) { - if (isStale(result.provenance)) - return 0; - if (result.source?.hash || result.source?.revision) - return 1; - if (result.artifact?.hash) - return 0.85; - if (result.provenance && "source_refs" in result.provenance && result.provenance.source_refs.length > 0) - return 0.75; - return 0.55; +function routeMatchesResolverEvidence(route, previous) { + return stringFromUnknown(previous.source) === route.source && stringFromUnknown(previous.target) === route.target && stringFromUnknown(previous.route) === route.route && stringFromUnknown(previous.target_kind) === route.targetKind && stringFromUnknown(previous.confidence) === route.confidence; +} +function workspaceMatchesResolverEvidence(workspace, previous) { + return stringFromUnknown(previous.source) === workspace.source && stringFromUnknown(previous.requested_machine_id) === workspace.requested_machine_id && stringFromUnknown(previous.machine_id) === workspace.machine_id && stringFromUnknown(previous.project_id) === workspace.project_id && stringFromUnknown(previous.repo_name) === workspace.repo_name && stringFromUnknown(previous.project_root) === workspace.project_root && stringFromUnknown(previous.project_root_source) === workspace.project_root_source && stringFromUnknown(previous.workspace_root) === workspace.workspace_root && stringFromUnknown(previous.workspace_root_source) === workspace.workspace_root_source && stringFromUnknown(previous.open_files_root) === workspace.open_files_root && stringFromUnknown(previous.open_files_root_source) === workspace.open_files_root_source && stringFromUnknown(previous.trust_status) === workspace.trust_status && stringFromUnknown(previous.auth_status) === workspace.auth_status && booleanFromUnknown(previous.current) === workspace.current && booleanFromUnknown(previous.primary) === workspace.primary; +} +function routeWithStableCacheability(route, previous, now) { + if (!route) + return null; + const previousCacheability = cacheabilityFromUnknown(previous.cacheability); + if (previousCacheability && cacheabilityIsFresh(previousCacheability, now) && routeMatchesResolverEvidence(route, previous)) { + return { ...route, cacheability: previousCacheability }; + } + return route; +} +function workspaceWithStableCacheability(workspace, previous, now) { + if (!workspace) + return null; + const previousCacheability = cacheabilityFromUnknown(previous.cacheability); + if (previousCacheability && cacheabilityIsFresh(previousCacheability, now) && workspaceMatchesResolverEvidence(workspace, previous)) { + return { ...workspace, cacheability: previousCacheability }; + } + return workspace; +} +function resolverMachineId(input) { + return input.workspace?.machine_id ?? input.workspace?.requested_machine_id ?? input.machineId ?? input.route?.target ?? hostname(); +} +function resolverSources(input, existing) { + const sources = new Set; + const existingSources = Array.isArray(existing.sources) ? existing.sources : []; + for (const source of existingSources) + if (typeof source === "string") + sources.add(source); + if (typeof existing.source === "string") + sources.add(existing.source); + if (input.route?.source) + sources.add(input.route.source); + if (input.workspace?.source) + sources.add(input.workspace.source); + sources.add("knowledge"); + return [...sources].sort(); +} +function resolverTailscaleDns(existing, route) { + if (route?.target && (route.route === "tailscale" || route.targetKind === "tailscale")) + return route.target; + return existing?.tailscale_dns ?? null; +} +function resolverEvidenceMetadata(input, existing, now) { + const previous = recordFromUnknown(existing.resolver_evidence); + const route = input.route ? compactRecord({ + source: input.route.source, + target: input.route.target, + route: input.route.route, + target_kind: input.route.targetKind, + confidence: input.route.confidence, + adapter: input.route.adapter, + evidence: input.route.evidence, + cacheability: input.route.cacheability, + warnings: input.route.warnings + }) : recordFromUnknown(previous.route); + const workspace = input.workspace ? compactRecord({ + source: input.workspace.source, + requested_machine_id: input.workspace.requested_machine_id, + machine_id: input.workspace.machine_id, + project_id: input.workspace.project_id, + repo_name: input.workspace.repo_name, + project_root: input.workspace.project_root, + project_root_source: input.workspace.project_root_source, + workspace_root: input.workspace.workspace_root, + workspace_root_source: input.workspace.workspace_root_source, + open_files_root: input.workspace.open_files_root, + open_files_root_source: input.workspace.open_files_root_source, + trust_status: input.workspace.trust_status, + auth_status: input.workspace.auth_status, + current: input.workspace.current, + primary: input.workspace.primary, + diagnostics: input.workspace.diagnostics, + repair_hints: input.workspace.repair_hints, + evidence: input.workspace.evidence, + cacheability: input.workspace.cacheability, + warnings: input.workspace.warnings + }) : recordFromUnknown(previous.workspace); + return compactRecord({ + ...previous, + recorded_at: now, + route, + workspace + }); +} +function recordKnowledgeMachineResolverEvidence(dbPath, input) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const machineId = resolverMachineId(input); + const existing = db.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(machineId) ?? null; + const now = nowIso(input.now); + const capabilities = parseJsonRecord(existing?.capabilities_json); + const metadata = parseJsonRecord(existing?.metadata_json); + const resolverCapabilities = recordFromUnknown(capabilities.resolver); + const previousResolverEvidence = recordFromUnknown(metadata.resolver_evidence); + const previousRouteEvidence = recordFromUnknown(previousResolverEvidence.route); + const previousWorkspaceEvidence = recordFromUnknown(previousResolverEvidence.workspace); + const route = routeWithStableCacheability(input.route?.source === "registry" ? null : input.route ?? null, previousRouteEvidence, now); + const workspace = workspaceWithStableCacheability(input.workspace?.source === "registry" ? null : input.workspace ?? null, previousWorkspaceEvidence, now); + const stableInput = { ...input, route, workspace }; + const nextCapabilities = { + ...capabilities, + resolver: compactRecord({ + ...resolverCapabilities, + route_source: route?.source ?? resolverCapabilities.route_source, + route_kind: route?.route ?? resolverCapabilities.route_kind, + route_target_kind: route?.targetKind ?? resolverCapabilities.route_target_kind, + route_confidence: route?.confidence ?? resolverCapabilities.route_confidence, + route_cacheable: route?.cacheability?.cacheable ?? resolverCapabilities.route_cacheable, + route_stale: route?.cacheability?.stale ?? resolverCapabilities.route_stale, + route_expires_at: route?.cacheability?.expires_at ?? resolverCapabilities.route_expires_at, + route_observed_at: route?.cacheability?.observed_at ?? resolverCapabilities.route_observed_at, + route_source_authority: route?.cacheability?.source_authority ?? resolverCapabilities.route_source_authority, + workspace_source: workspace?.source ?? resolverCapabilities.workspace_source, + project_root_source: workspace?.project_root_source ?? resolverCapabilities.project_root_source, + workspace_root_source: workspace?.workspace_root_source ?? resolverCapabilities.workspace_root_source, + open_files_root_source: workspace?.open_files_root_source ?? resolverCapabilities.open_files_root_source, + trust_status: workspace?.trust_status ?? resolverCapabilities.trust_status, + auth_status: workspace?.auth_status ?? resolverCapabilities.auth_status, + workspace_cacheable: workspace?.cacheability?.cacheable ?? resolverCapabilities.workspace_cacheable, + workspace_stale: workspace?.cacheability?.stale ?? resolverCapabilities.workspace_stale, + workspace_expires_at: workspace?.cacheability?.expires_at ?? resolverCapabilities.workspace_expires_at, + workspace_observed_at: workspace?.cacheability?.observed_at ?? resolverCapabilities.workspace_observed_at, + workspace_source_authority: workspace?.cacheability?.source_authority ?? resolverCapabilities.workspace_source_authority + }), + route_fallback: Boolean(route?.target ?? existing?.ssh_target), + workspace_fallback: Boolean(workspace?.project_root ?? existing?.workspace_home) + }; + const nextResolverEvidence = resolverEvidenceMetadata(stableInput, metadata, now); + if (existing) { + const existingResolverEvidence = previousResolverEvidence; + const unchanged = existing.workspace_home === (workspace?.project_root ?? existing.workspace_home ?? null) && existing.tailscale_dns === resolverTailscaleDns(existing, route) && existing.ssh_target === (route?.target ?? existing.ssh_target ?? null) && canonicalJson(parseJsonRecord(existing.capabilities_json)) === canonicalJson(nextCapabilities) && canonicalJson(stableResolverEvidence(existingResolverEvidence)) === canonicalJson(stableResolverEvidence(nextResolverEvidence)); + if (unchanged) + return existing; + } + const row = { + machine_id: machineId, + hostname: existing?.hostname ?? null, + platform: existing?.platform ?? null, + user_label: existing?.user_label ?? null, + workspace_home: workspace?.project_root ?? existing?.workspace_home ?? null, + tailscale_dns: resolverTailscaleDns(existing, route), + tailscale_ips_json: JSON.stringify(parseJsonArray(existing?.tailscale_ips_json)), + ssh_target: route?.target ?? existing?.ssh_target ?? null, + last_seen_at: now, + capabilities_json: JSON.stringify(nextCapabilities), + metadata_json: JSON.stringify({ + ...metadata, + source: "knowledge", + sources: resolverSources(stableInput, metadata), + resolver_evidence: nextResolverEvidence + }), + created_at: existing?.created_at ?? now, + updated_at: now + }; + upsertKnowledgeMachine(db, row); + return row; + } finally { + db.close(); + } +} +function upsertKnowledgeMachine(db, input) { + db.query(` + INSERT INTO knowledge_machines ( + machine_id, hostname, platform, user_label, workspace_home, tailscale_dns, + tailscale_ips_json, ssh_target, last_seen_at, capabilities_json, + metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(machine_id) DO UPDATE SET + hostname = excluded.hostname, + platform = excluded.platform, + user_label = excluded.user_label, + workspace_home = excluded.workspace_home, + tailscale_dns = excluded.tailscale_dns, + tailscale_ips_json = excluded.tailscale_ips_json, + ssh_target = excluded.ssh_target, + last_seen_at = excluded.last_seen_at, + capabilities_json = excluded.capabilities_json, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at + `).run(input.machine_id, input.hostname, input.platform, input.user_label, input.workspace_home, input.tailscale_dns, input.tailscale_ips_json, input.ssh_target, input.last_seen_at, input.capabilities_json, input.metadata_json, input.created_at, input.updated_at); +} +function refreshMachineRegistryFromTopology(db, topology, now = nowIso()) { + for (const entry of topology.machines) + upsertKnowledgeMachine(db, machineFromTopologyEntry(entry, now)); + return topology.machines.length; +} +function listKnowledgeMachines(dbPath) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + return db.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(); + } finally { + db.close(); + } +} +function createKnowledgeSyncBundle(options) { + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + const warnings = []; + const generatedAt = nowIso(options.now); + const sourceMachineId = defaultSyncMachineId(options.machineId); + const recordClocks = options.recordClocks !== false; + try { + const requestedTables = filterExistingTables(db, resolveSyncTables(options.tables)); + const artifactRows = db.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json + FROM storage_objects + ORDER BY artifact_uri ASC`).all(); + const artifacts = artifactRows.map((row) => { + const key = keyForArtifactRow(row, options.storage.local_layout.directories.artifacts); + let artifact = { ...row, key }; + if (options.includeArtifactContent !== false && key && row.artifact_uri.startsWith("file://")) { + try { + const path = fileURLToPath2(row.artifact_uri); + if (existsSync9(path)) { + if (!isTextArtifact(row.content_type, key)) { + warnings.push(`artifact_content_not_embedded_binary:${row.id}`); + } else { + const text = readFileSync11(path, "utf8"); + const redactedText = redactPrivateRefs(text); + if (redactedText !== text) + warnings.push(`artifact_content_redacted:${row.id}`); + artifact.content_base64 = Buffer.from(redactedText, "utf8").toString("base64"); + artifact.hash = sha256(redactedText); + artifact.size_bytes = Buffer.byteLength(redactedText); + } + } else { + warnings.push(`artifact_missing:${row.artifact_uri}`); + } + } catch (error) { + warnings.push(`artifact_read_failed:${row.artifact_uri}:${error instanceof Error ? error.message : String(error)}`); + } + } else if (options.includeArtifactContent !== false && row.artifact_uri.startsWith("s3://")) { + warnings.push(`artifact_content_not_embedded:${row.artifact_uri}`); + } + artifact = redactPrivateRefs(artifact); + return artifact; + }); + const sourceArtifactUriToKey = artifactUriToKey(artifacts); + const tables = requestedTables.filter((table) => !TABLE_SYNC_EXCLUDES.has(table)).map((table) => ({ + table, + primary_keys: PRIMARY_KEYS[table], + rows: tableRows(db, table).map((row) => redactPrivateRefs(row)) + })); + const tableClocks = tables.map((table) => prepareExportTableClock(db, { + table: table.table, + machineId: sourceMachineId, + highWaterHash: tableContentHash(table.table, table.rows, sourceArtifactUriToKey), + rowCount: table.rows.length, + record: recordClocks, + now: generatedAt + })); + const contentHash = sha256(stableJson({ + source: { + scope: options.scope, + workspace_home: redactPrivateRefs(options.workspaceHome), + sqlite_schema_version: getSchemaVersion(db), + machine_id: sourceMachineId, + artifact_root_uri: redactPrivateRefs(options.storage.artifact_store.uri_prefix) + }, + tables: tables.map((table) => ({ + table: table.table, + primary_keys: table.primary_keys, + rows: table.rows.map((row) => ({ + key: rowKey(table.table, row), + hash: rowHash(row, sourceArtifactUriToKey) + })).sort((a, b) => a.key.localeCompare(b.key)) + })), + table_clocks: tableClocks.map((clock) => ({ + table: clock.table, + machine_id: clock.machine_id, + logical_clock: clock.logical_clock, + high_water_hash: clock.high_water_hash, + row_count: clock.row_count + })), + artifacts: artifacts.map((artifact) => ({ + identity: artifactIdentity(artifact), + fingerprint: artifactFingerprint(artifact) + })).sort((a, b) => a.identity.localeCompare(b.identity)) + })); + const bundleId = `syncbundle_${contentHash.replace("sha256:", "").slice(0, 32)}`; + for (const clock of tableClocks) + finalizeExportTableClock(db, clock, bundleId, recordClocks, generatedAt); + return { + ok: true, + format: "knowledge-sync-bundle", + version: 1, + protocol_version: KNOWLEDGE_SYNC_PROTOCOL_VERSION, + min_protocol_version: KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION, + bundle_id: bundleId, + content_hash: contentHash, + generated_at: generatedAt, + source: { + scope: options.scope, + workspace_home: redactPrivateRefs(options.workspaceHome), + sqlite_schema_version: getSchemaVersion(db), + machine_id: sourceMachineId, + artifact_root_uri: redactPrivateRefs(options.storage.artifact_store.uri_prefix) + }, + table_clocks: tableClocks, + tables, + artifacts, + warnings: redactPrivateRefs(warnings), + message: `${tables.reduce((sum, table) => sum + table.rows.length, 0)} row(s), ${artifacts.length} artifact(s) exported` + }; + } finally { + db.close(); + } } -function citationScore(result) { - if (result.citation?.chunk_id && (result.source?.uri || result.artifact?.uri)) - return 1; - if (result.provenance && "citation_required" in result.provenance && result.provenance.citation_required) - return 0.75; - if (result.artifact?.uri) - return 0.65; - return 0.35; +function validateSyncProtocol(input, label) { + const protocolVersion = typeof input.protocol_version === "number" ? input.protocol_version : null; + const minProtocolVersion = typeof input.min_protocol_version === "number" ? input.min_protocol_version : null; + if (protocolVersion === null || minProtocolVersion === null || protocolVersion < KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION || minProtocolVersion > KNOWLEDGE_SYNC_PROTOCOL_VERSION) { + throw new Error(`Unsupported ${label} protocol. Expected knowledge sync protocol v${KNOWLEDGE_SYNC_PROTOCOL_VERSION} with min v${KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION}.`); + } } -function authorityScore(result) { - if (result.kind === "wiki_chunk") - return 0.85; - if (result.kind === "source_chunk") - return 0.8; - if (result.kind === "legacy_item") - return 0.6; - if (result.kind === "wiki_page") - return 0.65; - return 0.55; +function validateBundle(bundle) { + if (!bundle || bundle.format !== "knowledge-sync-bundle" || bundle.version !== 1) { + throw new Error("Invalid knowledge sync bundle."); + } + validateSyncProtocol(bundle, "knowledge sync bundle"); } -function rerank(result, terms) { - const scores = { - base_score: result.score, - exact_score: exactScore(result, terms), - citation_score: citationScore(result), - freshness_score: freshnessScore(result), - authority_score: authorityScore(result) - }; - const final = Math.min(1, scores.base_score * 0.65 + scores.exact_score * 0.1 + scores.citation_score * 0.1 + scores.freshness_score * 0.1 + scores.authority_score * 0.05); - const reasons = new Set(result.reasons); - if (scores.exact_score > 0.5) - reasons.add("exact_term"); - if (scores.citation_score >= 0.75) - reasons.add("cited_source"); - if (scores.freshness_score >= 0.85) - reasons.add("fresh_source"); - return { - ...result, - score: Number(final.toFixed(6)), - reasons: Array.from(reasons), - rerank: { - ...scores, - final_score: Number(final.toFixed(6)) - } - }; +function getBundleTable(bundle, table) { + return bundle.tables.find((entry) => entry.table === table) ?? null; } -function quoteFor(result, maxChars) { - const source = result.text ?? result.title; - if (!source) - return null; - const normalized = source.replace(/\s+/g, " ").trim(); - return normalized.length <= maxChars ? normalized : `${normalized.slice(0, Math.max(0, maxChars - 1)).trim()}...`; +function syncBundleContentHash(bundle) { + if (typeof bundle.content_hash === "string" && bundle.content_hash.length > 0) + return bundle.content_hash; + return sha256(stableJson({ + source: bundle.source, + tables: bundle.tables.map((table) => ({ + table: table.table, + rows: table.rows.map((row) => ({ + key: rowKey(table.table, row), + hash: rowHash(row, artifactUriToKey(bundle.artifacts)) + })).sort((a, b) => a.key.localeCompare(b.key)) + })), + artifacts: bundle.artifacts.map((artifact) => ({ + identity: artifactIdentity(artifact), + fingerprint: artifactFingerprint(artifact) + })).sort((a, b) => a.identity.localeCompare(b.identity)) + })); } -function citationFor(result) { - const id = stableId4("cite", `${result.kind}\x00${result.id}\x00${result.source?.uri ?? ""}\x00${result.artifact?.uri ?? ""}`); - return { - id, - result_id: result.id, - kind: result.kind, - source_uri: result.source?.uri ?? null, - source_ref: result.source?.ref ?? null, - artifact_uri: result.artifact?.uri ?? null, - artifact_path: result.artifact?.path ?? null, - revision: result.source?.revision ?? null, - hash: result.source?.hash ?? result.artifact?.hash ?? null, - chunk_id: result.citation?.chunk_id ?? null, - start_offset: result.citation?.start_offset ?? null, - end_offset: result.citation?.end_offset ?? null, - quote: quoteFor(result, 500), - provenance: result.provenance - }; +function syncBundleId(bundle) { + if (typeof bundle.bundle_id === "string" && bundle.bundle_id.length > 0) + return bundle.bundle_id; + return `syncbundle_${syncBundleContentHash(bundle).replace("sha256:", "").slice(0, 32)}`; } -function excerptFor(result, citation, contextChars) { - const text = quoteFor(result, contextChars); - if (!text) - return null; - return { - id: stableId4("excerpt", `${result.kind}\x00${result.id}`), - result_id: result.id, - citation_id: citation.id, - kind: result.kind, - text, - score: result.score - }; +function tableRowMap(table, rows) { + return new Map(rows.map((row) => [rowKey(table, row), row])); } -function placeholders(values) { - return values.map(() => "?").join(", "); +function bundleArtifactMap(bundle) { + return new Map(bundle.artifacts.map((artifact) => [artifactIdentity(artifact), artifact])); } -function loadGraphEvidence(dbPath, results) { - const chunkIds = results.map((result) => result.citation?.chunk_id).filter((id) => Boolean(id)); - const wikiPageIds = results.filter((result) => result.kind === "wiki_page").map((result) => result.id); - const citations = []; - const backlinks = []; - if (chunkIds.length === 0 && wikiPageIds.length === 0) - return { citations, backlinks }; - const db = openKnowledgeDb(dbPath); - try { - if (chunkIds.length > 0) { - citations.push(...db.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset - FROM citations - WHERE chunk_id IN (${placeholders(chunkIds)}) - ORDER BY created_at DESC - LIMIT 50`).all(...chunkIds)); - } - if (wikiPageIds.length > 0) { - citations.push(...db.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset - FROM citations - WHERE wiki_page_id IN (${placeholders(wikiPageIds)}) - ORDER BY created_at DESC - LIMIT 50`).all(...wikiPageIds)); - backlinks.push(...db.query(`SELECT from_page_id, to_page_id, label - FROM wiki_backlinks - WHERE from_page_id IN (${placeholders(wikiPageIds)}) OR to_page_id IN (${placeholders(wikiPageIds)}) - LIMIT 50`).all(...wikiPageIds, ...wikiPageIds)); +async function materializeArtifacts(options) { + const targetArtifacts = bundleArtifactMap(options.targetBundle); + const uriMap = new Map; + const conflicts = []; + const result = { + source_artifacts: options.bundle.artifacts.length, + target_artifacts: options.targetBundle.artifacts.length, + copied: 0, + skipped: 0, + conflicts: 0, + missing_content: 0 + }; + for (const artifact of options.bundle.artifacts) { + const identity = artifactIdentity(artifact); + const target = targetArtifacts.get(identity); + if (target && artifactFingerprint(target) === artifactFingerprint(artifact)) { + if (target.artifact_uri) + uriMap.set(artifact.artifact_uri, target.artifact_uri); + result.skipped += 1; + continue; } - } finally { - db.close(); - } - return { citations, backlinks }; -} -function retrieveKnowledgeContextFromSearch(search, options = {}) { - const contextChars = Math.max(200, Math.min(options.contextChars ?? 1200, 4000)); - const terms = queryTerms2(search.query); - const warnings = [...search.warnings]; - const permissionNotes = new Set; - const freshnessNotes = new Set; - const filtered = search.results.filter((result) => { - if (!hasReadOnlyProvenance(result.provenance)) { - warnings.push(`permission_filtered: ${result.kind}:${result.id}`); - permissionNotes.add("Dropped a result because provenance was not read-only."); - return false; + if (target && artifactFingerprint(target) !== artifactFingerprint(artifact)) { + const conflict = { + entityKind: "storage_object", + entityId: identity, + localMachineId: options.localMachineId, + remoteMachineId: options.bundle.source.machine_id ?? "unknown", + localHash: artifactFingerprint(target), + remoteHash: artifactFingerprint(artifact), + metadata: { + direction: options.direction, + target_artifact_uri: target.artifact_uri, + source_artifact_uri: artifact.artifact_uri, + local_artifact: sanitizeConflictEvidenceValue(target), + remote_artifact: sanitizeConflictEvidenceValue(artifact) + } + }; + if (hasResolvedConflictFingerprint(options.db, conflict)) { + result.skipped += 1; + continue; + } + result.conflicts += 1; + conflicts.push(conflict); + continue; } - if (isStale(result.provenance)) { - warnings.push(`stale_filtered: ${result.kind}:${result.id}`); - freshnessNotes.add("Dropped a stale result whose source status requires reindexing."); - return false; + const hasEmbeddedContent = Boolean(artifact.key && artifact.content_base64); + const canReferenceExistingS3 = canReferenceExistingS3Artifact(artifact, options.targetStorage); + if (!hasEmbeddedContent && !canReferenceExistingS3) { + result.missing_content += 1; + options.warnings.push(`artifact_content_missing:${artifact.artifact_uri}`); + continue; } - return true; - }); - const results = filtered.map((result) => rerank(result, terms)).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, search.limit); - const citations = results.map(citationFor); - const excerpts = results.map((result, index) => excerptFor(result, citations[index], contextChars)).filter((entry) => Boolean(entry)); - for (const result of results) { - if (result.provenance && "read_only" in result.provenance && result.provenance.read_only) { - permissionNotes.add("All source-backed excerpts are read-only and citation-required."); + if (options.dryRun) { + result.copied += 1; + continue; } - if (result.rerank.freshness_score >= 0.85) { - freshnessNotes.add("Fresh source revision/hash or artifact hash is present for top context."); + let nextUri = artifact.artifact_uri; + if (hasEmbeddedContent && artifact.key && artifact.content_base64) { + const write = await options.targetStore.put({ + key: artifact.key, + body: Buffer.from(artifact.content_base64, "base64"), + content_type: artifact.content_type ?? undefined + }); + nextUri = write.uri; + uriMap.set(artifact.artifact_uri, nextUri); + } else if (canReferenceExistingS3) { + uriMap.set(artifact.artifact_uri, nextUri); } + const metadata = parseJson(artifact.metadata_json, {}); + const modifiedAt = typeof metadata.artifact_modified_at === "string" ? metadata.artifact_modified_at : undefined; + const object = { + uri: nextUri, + key: artifact.key ?? metadata.key ?? artifact.artifact_uri, + kind: artifact.kind, + content_type: artifact.content_type ?? undefined, + hash: artifact.hash ?? undefined, + size_bytes: artifact.size_bytes ?? undefined, + modified_at: modifiedAt, + metadata: { + ...metadata, + synced_from_artifact_uri: artifact.artifact_uri, + synced_from_machine_id: options.bundle.source.machine_id ?? undefined + } + }; + recordStorageObjects(options.db, [object]); + result.copied += 1; } - return { - query: search.query, - normalized_query: normalizeQuery(search.query), - created_at: new Date().toISOString(), - mode: search.mode, - warnings, - search_counts: search.counts, - results, - citations, - excerpts, - graph: options.dbPath ? loadGraphEvidence(options.dbPath, results) : { citations: [], backlinks: [] }, - notes: { - permissions: Array.from(permissionNotes), - freshness: Array.from(freshnessNotes) - } - }; -} -async function retrieveKnowledgeContext(options) { - const search = await hybridSearch(options); - return retrieveKnowledgeContextFromSearch(search, { - dbPath: options.dbPath, - contextChars: options.contextChars - }); -} -async function retrieveKnowledgeContextFromItems(items, options) { - const search = await hybridSearchItems(items, options); - return retrieveKnowledgeContextFromSearch(search, { contextChars: options.contextChars }); -} - -// src/agent.ts -function estimateTokens(text) { - const words = text.trim().split(/\s+/).filter(Boolean).length; - return Math.max(1, Math.ceil(words * 1.25)); -} -function citationLabel(index) { - return `C${index + 1}`; + return { result, uriMap, conflicts }; } -function localAnswer(prompt, context) { - if (context.excerpts.length === 0) { - return `No indexed knowledge matched the prompt: ${prompt}`; +function transformImportedRow(row, artifactUriMap) { + const next = { ...row }; + if (typeof next.artifact_uri === "string" && artifactUriMap.has(next.artifact_uri)) { + next.artifact_uri = artifactUriMap.get(next.artifact_uri); } - const lines = [ - `Found ${context.excerpts.length} relevant knowledge excerpt(s) for: ${prompt}`, - "", - ...context.excerpts.slice(0, 5).map((excerpt, index) => { - const citation = context.citations.find((entry) => entry.id === excerpt.citation_id); - const ref = citation?.source_ref ?? citation?.source_uri ?? citation?.artifact_path ?? citation?.artifact_uri ?? "unknown source"; - return `[${citationLabel(index)}] ${excerpt.text} (${ref})`; - }) - ]; - return lines.join(` -`); -} -function promptForModel(prompt, context) { - const citations = context.citations.map((citation, index) => ({ - id: citationLabel(index), - source_ref: citation.source_ref, - source_uri: citation.source_uri, - artifact_path: citation.artifact_path, - revision: citation.revision, - hash: citation.hash, - quote: citation.quote - })); - const excerpts = context.excerpts.map((excerpt, index) => ({ - id: citationLabel(index), - kind: excerpt.kind, - text: excerpt.text, - score: excerpt.score - })); - return [ - `Prompt: ${prompt}`, - "", - "Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.", - "", - `Context excerpts: -${JSON.stringify(excerpts, null, 2)}`, - "", - `Citations: -${JSON.stringify(citations, null, 2)}` - ].join(` -`); + return next; } -function proposedUpdates(prompt, context) { - if (context.citations.length === 0) - return []; - return [{ - kind: "answer_note", - title: prompt.length > 80 ? `${prompt.slice(0, 77)}...` : prompt, - citations: context.citations.map((citation) => citation.id), - requires_approval: true - }]; +function insertSyncChange(db, input) { + const now = nowIso(); + db.query(` + INSERT INTO knowledge_sync_changes ( + id, origin_machine_id, updated_by_machine_id, entity_kind, entity_id, + operation, base_hash, next_hash, source_ref, source_revision_id, + artifact_uri, logical_clock, bundle_id, metadata_json, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(makeSyncId("syncchg"), input.sourceMachineId, input.localMachineId, input.entityKind, input.entityId, input.direction, null, input.nextHash, typeof input.row?.source_ref === "string" ? input.row.source_ref : typeof input.row?.source_uri === "string" ? input.row.source_uri : null, typeof input.row?.source_revision_id === "string" ? input.row.source_revision_id : null, typeof input.row?.artifact_uri === "string" ? input.row.artifact_uri : null, input.logicalClock, input.bundleId, JSON.stringify({ source_machine_id: input.sourceMachineId, bundle_id: input.bundleId }), now); } -function insertRun(dbPath, input) { - const db = openKnowledgeDb(dbPath); - try { - db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - input.runId, - "knowledge-prompt", - input.prompt, - input.status, - input.provider, - input.model, - JSON.stringify(input.metadata), - input.now, - input.now - ]); - } finally { - db.close(); - } +function hasResolvedConflictFingerprint(db, input) { + const localHash = input.localHash ?? ""; + const remoteHash = input.remoteHash ?? ""; + const exact = db.query(` + SELECT id FROM knowledge_sync_conflicts + WHERE entity_kind = ? + AND entity_id = ? + AND local_machine_id = ? + AND remote_machine_id = ? + AND COALESCE(local_hash, '') = ? + AND COALESCE(remote_hash, '') = ? + AND status IN ('resolved', 'ignored') + AND resolved_at IS NOT NULL + LIMIT 1 + `).get(input.entityKind, input.entityId, input.localMachineId, input.remoteMachineId, localHash, remoteHash); + if (exact) + return true; + const reversed = db.query(` + SELECT id FROM knowledge_sync_conflicts + WHERE entity_kind = ? + AND entity_id = ? + AND local_machine_id = ? + AND remote_machine_id = ? + AND COALESCE(local_hash, '') = ? + AND COALESCE(remote_hash, '') = ? + AND status IN ('resolved', 'ignored') + AND resolved_at IS NOT NULL + LIMIT 1 + `).get(input.entityKind, input.entityId, input.remoteMachineId, input.localMachineId, remoteHash, localHash); + return Boolean(reversed); } -function addRunEvent(dbPath, input) { - const db = openKnowledgeDb(dbPath); - try { - db.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, [ - `evt_${randomUUID6()}`, - input.runId, - input.level, - input.event, - JSON.stringify(input.metadata), - input.now - ]); - } finally { - db.close(); - } +function insertConflict(db, input) { + const duplicate = db.query(` + SELECT id FROM knowledge_sync_conflicts + WHERE entity_kind = ? + AND entity_id = ? + AND local_machine_id = ? + AND remote_machine_id = ? + AND COALESCE(local_hash, '') = COALESCE(?, '') + AND COALESCE(remote_hash, '') = COALESCE(?, '') + AND COALESCE(base_hash, '') = COALESCE(?, '') + AND status = 'open' + LIMIT 1 + `).get(input.entityKind, input.entityId, input.localMachineId, input.remoteMachineId, input.localHash ?? null, input.remoteHash ?? null, input.baseHash ?? null); + if (duplicate) + return false; + const now = nowIso(); + db.query(` + INSERT INTO knowledge_sync_conflicts ( + id, entity_kind, entity_id, local_machine_id, remote_machine_id, + local_hash, remote_hash, base_hash, status, resolution_strategy, + proposed_patch_uri, approved_by, resolved_at, metadata_json, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(makeSyncId("syncconf"), input.entityKind, input.entityId, input.localMachineId, input.remoteMachineId, input.localHash ?? null, input.remoteHash ?? null, input.baseHash ?? null, input.status ?? "open", input.resolutionStrategy ?? null, input.proposedPatchUri ?? null, input.approvedBy ?? null, input.resolvedAt ?? null, JSON.stringify(input.metadata ?? {}), now); + return true; } -function updateRun(dbPath, input) { - const db = openKnowledgeDb(dbPath); - try { - db.run(`UPDATE runs - SET status = ?, provider = ?, model = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`, [ - input.status, - input.provider, - input.model, - JSON.stringify(input.metadata), - input.now, - input.runId - ]); - } finally { - db.close(); - } +function getSyncImport(db, bundleId) { + return db.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get(bundleId) ?? null; } -function recordUsage(dbPath, runId, usage, provider, model, now, metadata = {}) { - const db = openKnowledgeDb(dbPath); - try { - recordProviderUsage(db, { - run_id: runId, - provider, - model, - input_tokens: usage.input_tokens, - output_tokens: usage.output_tokens, - cost_usd: usage.cost_usd, - metadata, - created_at: now - }); - } finally { - db.close(); - } +function recordSyncImport(db, input) { + const now = input.now ?? nowIso(); + db.query(` + INSERT INTO knowledge_sync_imports ( + bundle_id, source_machine_id, target_machine_id, direction, status, + content_hash, table_clocks_json, tables_json, generated_at, applied_at, + metadata_json + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(bundle_id) DO UPDATE SET + status = excluded.status, + applied_at = excluded.applied_at, + metadata_json = excluded.metadata_json + `).run(input.bundleId, input.sourceMachineId, input.targetMachineId, input.direction, input.status, input.contentHash, JSON.stringify(input.bundle.table_clocks ?? []), JSON.stringify(input.tableResults), input.bundle.generated_at, now, JSON.stringify({ + conflicts: input.conflicts, + artifacts: input.artifacts, + source_workspace_home: input.bundle.source.workspace_home + })); } -async function runKnowledgePrompt(options) { - const prompt = options.prompt.trim(); - if (!prompt) - throw new Error("Knowledge prompt is required."); - const now = (options.now ?? new Date).toISOString(); - const runId = `run_${randomUUID6()}`; - const modelRef = resolveModelRef(options.modelRef ?? "default", options.config); - const parsed = parseModelRef(modelRef); - migrateKnowledgeDb(options.dbPath); - insertRun(options.dbPath, { - runId, - prompt, - status: options.generate ? "running" : "dry_run", - provider: options.generate ? parsed.provider : "local", - model: options.generate ? parsed.model : "context-draft", - metadata: { - semantic: options.semantic === true || options.fake === true || Boolean(options.modelRef), - approve_write: options.approveWrite === true, - generated: options.generate === true - }, - now - }); - const { prompt: _prompt, generate: _generate, approveWrite: _approveWrite, now: _now, ...retrievalOptions } = options; - const context = await retrieveKnowledgeContext({ - ...retrievalOptions, - query: prompt - }); - addRunEvent(options.dbPath, { - runId, - level: "info", - event: "context_retrieved", - metadata: { - results: context.results.length, - citations: context.citations.length, - warnings: context.warnings +function replayedApplyResult(options) { + return { + ok: true, + protocol_version: KNOWLEDGE_SYNC_PROTOCOL_VERSION, + min_protocol_version: KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION, + dry_run: false, + direction: options.direction, + source: options.bundle.source, + target: { + scope: options.targetScope, + workspace_home: options.targetWorkspaceHome, + sqlite_schema_version: options.targetBundle.source.sqlite_schema_version, + artifact_root_uri: options.targetStorage.artifact_store.uri_prefix }, - now - }); - let answer = localAnswer(prompt, context); - let generated = false; - let provider = "local"; - let model = "context-draft"; - let usage = { - input_tokens: estimateTokens(prompt) + context.excerpts.reduce((sum, excerpt) => sum + estimateTokens(excerpt.text), 0), - output_tokens: estimateTokens(answer), - cost_usd: 0 - }; - const warnings = [...context.warnings]; - if (options.generate) { - try { - if (options.fake) { - generated = true; - provider = parsed.provider; - model = parsed.model; - answer = `Fake generated answer for: ${prompt} - -${answer}`; - } else { - const { generateText } = await import("ai"); - const languageModel = await languageModelFor(modelRef, { - config: options.config, - env: options.env - }); - const result = await generateText({ - model: languageModel, - system: "You answer company knowledge-base prompts using only provided context and citation ids.", - prompt: promptForModel(prompt, context) - }); - generated = true; - provider = parsed.provider; - model = parsed.model; - answer = result.text; - const normalized = normalizeAiSdkUsage({ - provider, - model, - usage: result.usage, - providerMetadata: result.providerMetadata - }); - usage = { - input_tokens: normalized.input_tokens, - output_tokens: normalized.output_tokens, - cost_usd: normalized.cost_usd - }; - } - } catch (error) { - addRunEvent(options.dbPath, { - runId, - level: "error", - event: "answer_generation_failed", - metadata: { message: error instanceof Error ? error.message : String(error) }, - now - }); - updateRun(options.dbPath, { - runId, - status: "failed", - provider: parsed.provider, - model: parsed.model, - metadata: { - generated: false, - error: error instanceof Error ? error.message : String(error) - }, - now - }); - throw error; - } - } - const updates = proposedUpdates(prompt, context); - const writePolicy = { - approved: options.approveWrite === true, - durable_writes_performed: false, - reason: options.approveWrite ? "Approval flag recorded; durable wiki writing is deferred to the wiki compile task." : "Dry-run mode: proposed wiki updates require approval before durable writes." - }; - addRunEvent(options.dbPath, { - runId, - level: "info", - event: generated ? "answer_generated" : "answer_drafted", - metadata: { - provider, - model, - proposed_updates: updates.length, - durable_writes_performed: false + tables: options.bundle.tables.filter((table) => !TABLE_SYNC_EXCLUDES.has(table.table)).map((table) => ({ + table: table.table, + source_rows: table.rows.length, + target_rows: getBundleTable(options.targetBundle, table.table)?.rows.length ?? 0, + inserted: 0, + updated: 0, + deleted: 0, + skipped: table.rows.length, + conflicts: 0, + stale_skipped: 0 + })), + artifacts: { + source_artifacts: options.bundle.artifacts.length, + target_artifacts: options.targetBundle.artifacts.length, + copied: 0, + skipped: options.bundle.artifacts.length, + conflicts: 0, + missing_content: 0 }, - now - }); - recordUsage(options.dbPath, runId, usage, provider, model, now, { - generated, - citations: context.citations.length - }); - updateRun(options.dbPath, { - runId, - status: generated ? "completed" : "dry_run", - provider, - model, - metadata: { - generated, - citations: context.citations.length, - proposed_updates: updates.length, - approve_write: options.approveWrite === true + conflicts_created: 0, + bundle_id: options.bundleId, + replayed: true, + clocks: { + advanced: 0, + stale_tables: 0 }, - now - }); - return { - run_id: runId, - prompt, - generated, - provider, - model, - answer, - context, - citations: context.citations, - proposed_wiki_updates: updates, - write_policy: writePolicy, - usage, - warnings + warnings: [...options.warnings, `bundle_replay_skipped:${options.bundleId}`], + message: `Skipped already-applied bundle ${options.bundleId}` }; } -async function runKnowledgePromptOverItems(items, options) { - const prompt = options.prompt.trim(); - if (!prompt) - throw new Error("Knowledge prompt is required."); - const runId = `run_${randomUUID6()}`; - const modelRef = resolveModelRef(options.modelRef ?? "default", options.config); - const parsed = parseModelRef(modelRef); - const { prompt: _p, generate: _g, approveWrite: _a, now: _n, ...retrievalOptions } = options; - const context = await retrieveKnowledgeContextFromItems(items, { - ...retrievalOptions, - query: prompt +function canSkipBundleReplay(bundle, targetBundle) { + const sourceArtifactUriToKey = artifactUriToKey(bundle.artifacts); + const targetArtifactUriToKey = artifactUriToKey(targetBundle.artifacts); + for (const sourceTable of bundle.tables) { + if (TABLE_SYNC_EXCLUDES.has(sourceTable.table)) + continue; + const targetTable = getBundleTable(targetBundle, sourceTable.table); + const incomingClock = bundleTableClock(bundle, sourceTable.table); + const incomingHash = incomingClock?.high_water_hash ?? tableContentHash(sourceTable.table, sourceTable.rows, sourceArtifactUriToKey); + const currentHash = tableContentHash(sourceTable.table, targetTable?.rows ?? [], targetArtifactUriToKey); + if (currentHash !== incomingHash) + return false; + } + return true; +} +async function applyKnowledgeSyncBundle(options) { + validateBundle(options.bundle); + migrateKnowledgeDb(options.targetDbPath); + const warnings = [...options.bundle.warnings]; + const dryRun = options.dryRun === true; + const localMachineId = defaultSyncMachineId(options.localMachineId); + const sourceMachineId = options.bundle.source.machine_id ?? "unknown"; + const bundleId = syncBundleId(options.bundle); + const contentHash = syncBundleContentHash(options.bundle); + const targetBundle = options.targetBundle ?? createKnowledgeSyncBundle({ + dbPath: options.targetDbPath, + scope: options.targetScope, + workspaceHome: options.targetWorkspaceHome, + storage: options.targetStorage, + machineId: localMachineId, + includeArtifactContent: false, + recordClocks: !dryRun }); - let answer = localAnswer(prompt, context); - let generated = false; - let provider = "local"; - let model = "context-draft"; - let usage = { - input_tokens: estimateTokens(prompt) + context.excerpts.reduce((sum, excerpt) => sum + estimateTokens(excerpt.text), 0), - output_tokens: estimateTokens(answer), - cost_usd: 0 - }; - const warnings = [...context.warnings]; - if (options.generate) { - if (options.fake) { - generated = true; - provider = parsed.provider; - model = parsed.model; - answer = `Fake generated answer for: ${prompt} - -${answer}`; - } else { - const { generateText } = await import("ai"); - const languageModel = await languageModelFor(modelRef, { - config: options.config, - env: options.env + const db = openKnowledgeDb(options.targetDbPath); + try { + if (!dryRun && getSyncImport(db, bundleId) && canSkipBundleReplay(options.bundle, targetBundle)) { + return replayedApplyResult({ + bundle: options.bundle, + targetBundle, + targetScope: options.targetScope, + targetWorkspaceHome: options.targetWorkspaceHome, + targetStorage: options.targetStorage, + direction: options.direction, + warnings, + bundleId }); - const result = await generateText({ - model: languageModel, - system: "You answer company knowledge-base prompts using only provided context and citation ids.", - prompt: promptForModel(prompt, context) + } + const artifactResult = await materializeArtifacts({ + db, + bundle: options.bundle, + targetBundle, + targetStorage: options.targetStorage, + targetStore: options.targetStore, + dryRun, + direction: options.direction, + localMachineId, + warnings + }); + const sourceArtifactUriToKey = artifactUriToKey(options.bundle.artifacts); + const targetArtifactUriToKey = artifactUriToKey(targetBundle.artifacts); + const tableResults = []; + let conflictsCreated = 0; + let clocksAdvanced = 0; + let staleTables = 0; + for (const sourceTable of options.bundle.tables) { + if (sourceTable.table === "storage_objects" || TABLE_SYNC_EXCLUDES.has(sourceTable.table)) + continue; + if (!tableExists2(db, sourceTable.table)) + continue; + const incomingClock = bundleTableClock(options.bundle, sourceTable.table); + const existingClock = tableClock(db, sourceTable.table, sourceMachineId); + const targetTable = getBundleTable(targetBundle, sourceTable.table); + const targetRows = tableRowMap(sourceTable.table, targetTable?.rows ?? []); + const incomingRowKeys = new Set(sourceTable.rows.map((row) => rowKey(sourceTable.table, row))); + const importedRowHashes = latestImportedRowHashes(db, sourceTable.table, sourceMachineId); + const rowsToWrite = []; + const result = { + table: sourceTable.table, + source_rows: sourceTable.rows.length, + target_rows: targetTable?.rows.length ?? 0, + inserted: 0, + updated: 0, + deleted: 0, + skipped: 0, + conflicts: 0, + stale_skipped: 0 + }; + if (!incomingClock) { + warnings.push(`legacy_clock_missing:${sourceTable.table}`); + } else if (staleIncomingClock(existingClock, incomingClock)) { + staleTables += 1; + result.skipped += sourceTable.rows.length; + result.stale_skipped = sourceTable.rows.length; + warnings.push(`stale_table_skipped:${sourceTable.table}:${sourceMachineId}:${incomingClock.logical_clock}`); + tableResults.push(result); + continue; + } + for (const sourceRow of sourceTable.rows) { + const key = rowKey(sourceTable.table, sourceRow); + const targetRow = targetRows.get(key); + const incomingHash = rowHash(sourceRow, sourceArtifactUriToKey); + if (!targetRow) { + result.inserted += 1; + rowsToWrite.push(transformImportedRow(sourceRow, artifactResult.uriMap)); + continue; + } + const currentHash = rowHash(targetRow, targetArtifactUriToKey); + if (currentHash === incomingHash) { + result.skipped += 1; + continue; + } + const importedHash = importedRowHashes.get(key); + if (importedRowHashes.has(key) && importedHash === currentHash) { + result.updated += 1; + rowsToWrite.push(transformImportedRow(sourceRow, artifactResult.uriMap)); + continue; + } + const conflict = { + entityKind: sourceTable.table, + entityId: key, + localMachineId, + remoteMachineId: sourceMachineId, + localHash: currentHash, + remoteHash: incomingHash, + baseHash: existingClock?.high_water_hash ?? null, + metadata: { + direction: options.direction, + bundle_id: bundleId, + incoming_logical_clock: incomingClock?.logical_clock ?? null, + current_logical_clock: existingClock?.logical_clock ?? null, + source_workspace_home: options.bundle.source.workspace_home, + target_workspace_home: options.targetWorkspaceHome, + local_row: sanitizeConflictEvidenceRow(targetRow), + remote_row: sanitizeConflictEvidenceRow(sourceRow) + } + }; + if (hasResolvedConflictFingerprint(db, conflict)) { + result.skipped += 1; + continue; + } + result.conflicts += 1; + if (!dryRun && insertConflict(db, conflict)) + conflictsCreated += 1; + } + if (!dryRun && rowsToWrite.length > 0) { + const writtenRows = rowsToWrite.map((row) => transformImportedRow(row, artifactResult.uriMap)); + upsertSqliteRows(db, sourceTable.table, writtenRows); + refreshDerivedRowsForImport(db, sourceTable.table, writtenRows); + for (const row of writtenRows) { + insertSyncChange(db, { + direction: options.direction, + sourceMachineId: options.bundle.source.machine_id ?? "unknown", + localMachineId, + entityKind: sourceTable.table, + entityId: rowKey(sourceTable.table, row), + nextHash: rowHash(row, artifactUriToKey(options.bundle.artifacts)), + logicalClock: incomingClock?.logical_clock ?? 0, + bundleId, + row + }); + } + } + for (const [key, importedHash] of importedRowHashes) { + if (incomingRowKeys.has(key)) + continue; + const targetRow = targetRows.get(key); + if (!targetRow) + continue; + const currentHash = rowHash(targetRow, targetArtifactUriToKey); + if (importedHash && currentHash !== importedHash) { + const conflict = { + entityKind: sourceTable.table, + entityId: key, + localMachineId, + remoteMachineId: sourceMachineId, + localHash: currentHash, + remoteHash: null, + baseHash: importedHash, + metadata: { + direction: options.direction, + bundle_id: bundleId, + reason: "remote_owned_row_missing_from_incoming_bundle", + source_workspace_home: options.bundle.source.workspace_home, + target_workspace_home: options.targetWorkspaceHome, + local_row: sanitizeConflictEvidenceRow(targetRow), + remote_row: null + } + }; + if (hasResolvedConflictFingerprint(db, conflict)) { + result.skipped += 1; + continue; + } + result.conflicts += 1; + if (!dryRun && insertConflict(db, conflict)) + conflictsCreated += 1; + continue; + } + result.deleted += 1; + if (!dryRun) + deleteSqliteRowByKey(db, sourceTable.table, key); + } + if (!dryRun && incomingClock) { + updateTableClock(db, { + table: sourceTable.table, + machineId: sourceMachineId, + logicalClock: incomingClock.logical_clock, + highWaterHash: incomingClock.high_water_hash, + highWaterBundleId: bundleId, + originMachineId: sourceMachineId, + updatedByMachineId: localMachineId, + lastAppliedAt: nowIso(), + metadata: { + source: "import", + direction: options.direction, + row_count: sourceTable.rows.length, + inserted: result.inserted, + updated: result.updated, + deleted: result.deleted, + skipped: result.skipped, + conflicts: result.conflicts + } + }); + clocksAdvanced += 1; + } + tableResults.push(result); + } + for (const conflict of artifactResult.conflicts) { + if (!dryRun) { + if (insertConflict(db, { + ...conflict, + baseHash: conflict.baseHash ?? null, + metadata: { + ...conflict.metadata, + bundle_id: bundleId + } + })) + conflictsCreated += 1; + } + } + const inserted = tableResults.reduce((sum, table) => sum + table.inserted, 0); + const conflicts = tableResults.reduce((sum, table) => sum + table.conflicts, 0) + artifactResult.result.conflicts; + if (!dryRun) { + recordSyncImport(db, { + bundle: options.bundle, + bundleId, + contentHash, + sourceMachineId, + targetMachineId: localMachineId, + direction: options.direction, + status: conflicts === 0 ? "applied" : "conflicted", + tableResults, + conflicts, + artifacts: artifactResult.result }); - generated = true; - provider = parsed.provider; - model = parsed.model; - answer = result.text; - const normalized = normalizeAiSdkUsage({ - provider, - model, - usage: result.usage, - providerMetadata: result.providerMetadata + } + return { + ok: conflicts === 0, + protocol_version: KNOWLEDGE_SYNC_PROTOCOL_VERSION, + min_protocol_version: KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION, + dry_run: dryRun, + direction: options.direction, + source: options.bundle.source, + target: { + scope: options.targetScope, + workspace_home: options.targetWorkspaceHome, + sqlite_schema_version: getSchemaVersion(db), + artifact_root_uri: options.targetStorage.artifact_store.uri_prefix + }, + tables: tableResults, + artifacts: artifactResult.result, + conflicts_created: conflictsCreated, + bundle_id: bundleId, + replayed: false, + clocks: { + advanced: clocksAdvanced, + stale_tables: staleTables + }, + warnings, + message: `${options.dryRun ? "Would import" : "Imported"} ${inserted} row(s), copied ${artifactResult.result.copied} artifact(s), ${conflicts} conflict(s)` + }; + } finally { + db.close(); + } +} +function createKnowledgeSyncSnapshot(options) { + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + const createdAt = nowIso(options.now); + try { + const machinesUpserted = options.topology ? refreshMachineRegistryFromTopology(db, options.topology, createdAt) : 0; + const tables = tableCounts(db); + const artifacts = redactPrivateRefs(artifactHashes(db)); + const machineId = options.machineId ?? options.topology?.local_machine_id ?? "unknown"; + const artifactRootUri = redactPrivateRefs(options.storage.artifact_store.uri_prefix); + const workspaceHome = redactPrivateRefs(options.workspaceHome); + const contentHash = sha256(stableJson({ + machine_id: machineId, + scope: options.scope, + workspace_home: workspaceHome, + sqlite_schema_version: getSchemaVersion(db), + artifact_root_uri: artifactRootUri, + tables, + artifacts + })); + const row = { + id: makeSyncId("syncsnap"), + machine_id: machineId, + scope: options.scope, + workspace_home: workspaceHome, + sqlite_schema_version: getSchemaVersion(db), + artifact_root_uri: artifactRootUri, + content_hash: contentHash, + tables_json: JSON.stringify(tables), + artifact_hashes_json: JSON.stringify(artifacts), + created_at: createdAt + }; + db.query(` + INSERT INTO knowledge_sync_snapshots ( + id, machine_id, scope, workspace_home, sqlite_schema_version, + artifact_root_uri, content_hash, tables_json, artifact_hashes_json, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(row.id, row.machine_id, row.scope, row.workspace_home, row.sqlite_schema_version, row.artifact_root_uri, row.content_hash, row.tables_json, row.artifact_hashes_json, row.created_at); + const artifactUriMap = new Map; + for (const table of filterExistingTables(db, resolveSyncTables()).filter((entry) => !TABLE_SYNC_EXCLUDES.has(entry))) { + const rows = tableRows(db, table).map((entry) => redactPrivateRefs(entry)); + const highWaterHash = tableContentHash(table, rows, artifactUriMap); + const existing = tableClock(db, table, machineId); + const logicalClock = existing?.high_water_hash === highWaterHash ? existing.logical_clock : (existing?.logical_clock ?? 0) + 1; + updateTableClock(db, { + table, + machineId, + logicalClock, + highWaterHash, + highWaterBundleId: row.id, + originMachineId: existing?.origin_machine_id ?? machineId, + updatedByMachineId: machineId, + lastAppliedAt: createdAt, + metadata: { + source: "snapshot", + row_count: rows.length + }, + now: createdAt }); - usage = { - input_tokens: normalized.input_tokens, - output_tokens: normalized.output_tokens, - cost_usd: normalized.cost_usd - }; } + return { + ok: true, + snapshot: { + ...row, + tables, + artifact_hashes: artifacts + }, + machines_upserted: machinesUpserted, + message: `Recorded sync snapshot ${row.id}` + }; + } finally { + db.close(); } - const updates = proposedUpdates(prompt, context); - const writePolicy = { - approved: options.approveWrite === true, - durable_writes_performed: false, - reason: options.approveWrite ? "Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode." : "Dry-run mode: proposed wiki updates require approval before durable writes." - }; - return { - run_id: runId, - prompt, - generated, - provider, - model, - answer, - context, - citations: context.citations, - proposed_wiki_updates: updates, - write_policy: writePolicy, - usage, - warnings - }; -} - -// src/context-pack.ts -import { createHash as createHash11 } from "crypto"; -var DEFAULT_MAX_TOKENS = 1200; -var DEFAULT_MAX_ITEMS = 6; -var MAX_MAX_TOKENS = 12000; -var MAX_MAX_ITEMS = 50; -var MIN_MAX_TOKENS = 800; -function stableId5(prefix, value, size = 16) { - return `${prefix}_${createHash11("sha256").update(value).digest("hex").slice(0, size)}`; } -function normalizeText(value) { - return value.normalize("NFKC").trim().replace(/\s+/g, " "); +function getKnowledgeSyncStatus(options) { + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + try { + const machines = db.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(); + const latest = db.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get() ?? null; + const conflictStatuses = db.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(); + const changeOps = db.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(); + const clocks = listTableClocks(db); + const latestImport = db.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get() ?? null; + const totalConflicts = conflictStatuses.reduce((sum, row) => sum + row.count, 0); + const openConflicts = conflictStatuses.filter((row) => row.status !== "resolved" && row.status !== "ignored").reduce((sum, row) => sum + row.count, 0); + return { + ok: true, + scope: options.scope, + workspace_home: redactPrivateRefs(options.workspaceHome), + sqlite_schema_version: getSchemaVersion(db), + local_machine_id: options.localMachineId ?? null, + machines: { + total: machines.length, + rows: redactPrivateRefs(machines) + }, + snapshots: { + total: count2(db, "knowledge_sync_snapshots"), + latest: redactPrivateRefs(latest) + }, + changes: { + total: count2(db, "knowledge_sync_changes"), + by_operation: changeOps + }, + clocks: { + total: clocks.length, + rows: clocks + }, + imports: { + total: count2(db, "knowledge_sync_imports"), + latest: redactPrivateRefs(latestImport) + }, + conflicts: { + total: totalConflicts, + by_status: conflictStatuses, + open: openConflicts + }, + table_counts: tableCounts(db), + message: `${machines.length} machine(s), ${openConflicts} open sync conflict(s)` + }; + } finally { + db.close(); + } } -function normalizedSearchText(value) { - return normalizeText(value).toLowerCase(); +function recordKnowledgeSyncConflict(dbPath, input) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = nowIso(); + const row = { + id: makeSyncId("syncconf"), + entity_kind: input.entityKind, + entity_id: input.entityId, + local_machine_id: input.localMachineId, + remote_machine_id: input.remoteMachineId, + local_hash: input.localHash ?? null, + remote_hash: input.remoteHash ?? null, + base_hash: input.baseHash ?? null, + status: input.status ?? "open", + resolution_strategy: input.resolutionStrategy ?? null, + proposed_patch_uri: input.proposedPatchUri ?? null, + approved_by: input.approvedBy ?? null, + resolved_at: input.resolvedAt ?? null, + metadata_json: JSON.stringify(input.metadata ?? {}), + created_at: now + }; + try { + db.query(` + INSERT INTO knowledge_sync_conflicts ( + id, entity_kind, entity_id, local_machine_id, remote_machine_id, + local_hash, remote_hash, base_hash, status, resolution_strategy, + proposed_patch_uri, approved_by, resolved_at, metadata_json, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(row.id, row.entity_kind, row.entity_id, row.local_machine_id, row.remote_machine_id, row.local_hash, row.remote_hash, row.base_hash, row.status, row.resolution_strategy, row.proposed_patch_uri, row.approved_by, row.resolved_at, row.metadata_json, row.created_at); + return row; + } finally { + db.close(); + } } -function termsFor(value) { - return Array.from(new Set(normalizedSearchText(value).match(/[\p{L}\p{N}_]+/gu) ?? [])).slice(0, 24); +function hydrateConflict(row) { + return { + ...row, + metadata: parseJson(row.metadata_json, {}) + }; } -function truncateText(value, maxChars) { - const normalized = normalizeText(value); - if (normalized.length <= maxChars) - return normalized; - const ellipsis = "..."; - if (maxChars <= ellipsis.length) - return normalized.slice(0, Math.max(0, maxChars)); - return `${normalized.slice(0, maxChars - ellipsis.length).trim()}${ellipsis}`; +function getKnowledgeSyncConflict(dbPath, id) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const row = db.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(id); + return row ? hydrateConflict(row) : null; + } finally { + db.close(); + } } -function parseJsonObject5(value) { - if (!value) - return {}; +function listKnowledgeSyncConflicts(dbPath, options = {}) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; + const rows = options.status ? db.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all(options.status, limit) : db.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(limit); + return rows.map(hydrateConflict); + } finally { + db.close(); } } -function isSecretishKey(key) { - return /(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test(key); +function conflictTable(value) { + return KNOWLEDGE_SYNC_TABLES.includes(value) ? value : null; } -function metadataKeys(metadata) { - return Object.keys(metadata).filter((key) => !isSecretishKey(key)).sort().slice(0, 12); +function catalogRowForConflict(db, conflict) { + const table = conflictTable(conflict.entity_kind); + if (!table || !tableExists2(db, table)) + return null; + const values = parseRowKeyValues(table, conflict.entity_id); + if (!values) + return null; + const where = primaryKeyWhereClause(table); + return db.query(`SELECT * FROM ${quoteIdent(table)} WHERE ${where} LIMIT 1`).get(...values); } -function rawMetadataRef(metadata, keys) { +function rowFromMetadata(metadata, keys) { for (const key of keys) { - if (isSecretishKey(key)) - continue; const value = metadata[key]; - if (typeof value === "string" && value.trim()) - return value.trim(); + if (value && typeof value === "object" && !Array.isArray(value)) + return sanitizeConflictEvidenceRow(value); } return null; } -function safeRef(value, policy) { - if (!value) - return null; - const redacted = redactSecrets(value, policy).text; - try { - const parsed = new URL(redacted); - const secretParams = ["token", "access_token", "api_key", "apikey", "key", "secret", "password", "signature", "sig"]; - for (const param of secretParams) - parsed.searchParams.delete(param); - for (const [key] of parsed.searchParams) { - if (isSecretishKey(key)) - parsed.searchParams.delete(key); +function addSourceRef(refs, value) { + if (typeof value !== "string") + return; + const trimmed = value.trim(); + if (!trimmed) + return; + if (trimmed.startsWith("open-files://") || trimmed.startsWith("s3://") || trimmed.startsWith("file://") || trimmed.startsWith("https://") || trimmed.startsWith("http://")) + refs.add(trimmed); +} +function collectSourceRefs(value, refs = new Set, depth = 0) { + if (depth > 8 || value === null || value === undefined) + return refs; + if (typeof value === "string") { + addSourceRef(refs, value); + return refs; + } + if (Array.isArray(value)) { + for (const entry of value) + collectSourceRefs(entry, refs, depth + 1); + return refs; + } + if (typeof value === "object") { + for (const [key, entry] of Object.entries(value)) { + if (key === "source_ref" || key === "source_uri" || key === "artifact_uri" || key.endsWith("_uri")) + addSourceRef(refs, entry); + collectSourceRefs(entry, refs, depth + 1); } - return parsed.toString(); - } catch { - return redacted; } + return refs; } -function metadataRef(metadata, keys, policy) { - return safeRef(rawMetadataRef(metadata, keys), policy); -} -function summarizeMetadata(metadata) { - const parts = []; - for (const key of metadataKeys(metadata).slice(0, 6)) { - const value = metadata[key]; - if (typeof value === "string" && value.trim()) - parts.push(`${key}=${truncateText(value, 80)}`); - else if (typeof value === "number" || typeof value === "boolean") - parts.push(`${key}=${String(value)}`); - else if (value && typeof value === "object") - parts.push(`${key}={...}`); +function conflictCitations(input) { + const citations = [{ + id: "conflict", + kind: "metadata", + ref: `knowledge-sync-conflict://${input.conflict.id}`, + hash: input.conflict.base_hash, + quote: `Conflict on ${input.conflict.entity_kind}:${input.conflict.entity_id}` + }]; + if (input.localRow) { + citations.push({ + id: "local-row", + kind: "row", + ref: `${input.conflict.entity_kind}:${input.conflict.entity_id}:local`, + hash: input.conflict.local_hash, + quote: JSON.stringify(input.localRow).slice(0, 300) + }); } - return parts.join("; "); -} -function estimateTokensForText(text) { - if (!text.trim()) - return 0; - return Math.max(1, Math.ceil(text.length / 4)); -} -function estimateTokensForValue(value) { - return estimateTokensForText(JSON.stringify(value)); -} -function coerceMaxTokens(value) { - if (!Number.isFinite(value ?? NaN)) - return DEFAULT_MAX_TOKENS; - const floor = Math.floor(value); - if (floor < MIN_MAX_TOKENS) - throw new Error(`--max-tokens must be at least ${MIN_MAX_TOKENS} for the stable context-pack schema.`); - return Math.min(floor, MAX_MAX_TOKENS); -} -function coerceMaxItems(value, limit) { - const raw = Number.isFinite(value ?? NaN) ? value : limit; - if (!Number.isFinite(raw ?? NaN)) - return DEFAULT_MAX_ITEMS; - return Math.max(1, Math.min(Math.floor(raw), MAX_MAX_ITEMS)); -} -function parseSince(value, now) { - if (!value) - return { cutoff: null, warning: null }; - const trimmed = value.trim(); - const duration = /^(\d+)\s*([mhdw])$/i.exec(trimmed); - if (duration) { - const amount = Number(duration[1]); - const unit = duration[2].toLowerCase(); - const multiplier = unit === "m" ? 60000 : unit === "h" ? 3600000 : unit === "d" ? 86400000 : 604800000; - return { cutoff: new Date(now.getTime() - amount * multiplier).toISOString(), warning: null }; + if (input.remoteRow) { + citations.push({ + id: "remote-row", + kind: "row", + ref: `${input.conflict.entity_kind}:${input.conflict.entity_id}:remote`, + hash: input.conflict.remote_hash, + quote: JSON.stringify(input.remoteRow).slice(0, 300) + }); } - const parsed = new Date(trimmed); - if (!Number.isNaN(parsed.getTime())) - return { cutoff: parsed.toISOString(), warning: null }; - return { cutoff: null, warning: `invalid_since_ignored: ${trimmed}` }; -} -function redactPreview(text, policy, maxChars) { - const redacted = redactSecrets(text, policy); - return { - text: truncateText(redacted.text, maxChars), - redactions: redacted.findings.length - }; -} -function scoreAgainstTopic(text, terms) { - if (terms.length === 0) - return 0.5; - const haystack = normalizedSearchText(text); - const matched = terms.filter((term) => haystack.includes(term)).length; - return Number((matched / terms.length).toFixed(6)); -} -function baseSafetyReminders(source) { - return [ - "This pack is read-only and performs no durable writes.", - "Use citation ids and refs instead of pasting raw artifacts into prompts.", - "Resolve source or artifact refs explicitly only when raw content is needed and allowed.", - "Run generated knowledge writes through approval-gated commands before applying.", - source === "loops" || source === "runs" ? "Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded." : "Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata." - ]; -} -function citationFromRetrieval(index, citation, policy) { - const sourceRef = safeRef(citation.source_ref, policy); - const sourceUri = safeRef(citation.source_uri, policy); - const artifactUri = safeRef(citation.artifact_uri, policy); - const artifactPath = safeRef(citation.artifact_path, policy); - const ref = sourceRef ?? sourceUri ?? artifactPath ?? artifactUri ?? citation.id; - const quote = citation.quote ? redactPreview(citation.quote, policy, index < 3 ? 220 : 140) : null; - return { - citation: { - id: stableId5("cite", `${citation.id}\x00${ref}`, 12), - kind: citation.artifact_uri || citation.artifact_path ? "artifact" : "source", + input.sourceRefs.slice(0, 10).forEach((ref, index) => { + citations.push({ + id: `source-${index + 1}`, + kind: ref.startsWith("file://") || ref.startsWith("s3://") ? "artifact" : "source_ref", ref, - source_ref: sourceRef, - source_uri: sourceUri, - artifact_uri: artifactUri, - artifact_path: artifactPath, - run_id: null, - run_event_id: null, - revision: citation.revision ?? null, - hash: citation.hash ?? null, - chunk_id: citation.chunk_id ?? null, - offsets: { - start: citation.start_offset ?? null, - end: citation.end_offset ?? null - }, - quote_preview: quote?.text ?? null - }, - redactions: quote?.redactions ?? 0 - }; -} -async function buildSearchDraft(options, maxItems) { - const query2 = (options.query ?? options.topic ?? "").trim(); - if (!query2) - throw new Error("Context pack query is required for search source."); - const { - config, - dbPath, - limit, - semantic, - modelRef, - dimensions, - fake, - env, - batchSize, - maxParallelCalls, - legacyStorePath - } = options; - const context = await retrieveKnowledgeContext({ - dbPath, - config, - legacyStorePath, - query: query2, - limit: Math.max(maxItems, limit ?? maxItems), - semantic, - modelRef, - dimensions, - fake, - env, - batchSize, - maxParallelCalls, - contextChars: Math.min(options.contextChars ?? 700, 1200) - }); - const citationMap = new Map; - let redactions = 0; - context.citations.forEach((citation, index) => { - const item = citationFromRetrieval(index, citation, options.safetyPolicy); - redactions += item.redactions; - citationMap.set(citation.id, item.citation); + hash: null, + quote: null + }); }); - const evidence = context.excerpts.slice(0, Math.max(maxItems * 2, maxItems)).map((excerpt) => { - const result = context.results.find((entry) => entry.id === excerpt.result_id); - const citation = excerpt.citation_id ? citationMap.get(excerpt.citation_id) : null; - const redacted = redactPreview(excerpt.text, options.safetyPolicy, 520); - redactions += redacted.redactions; - const title = result?.title ?? citation?.ref ?? excerpt.kind; - return { - id: stableId5("ev", `${excerpt.kind}\x00${excerpt.result_id}\x00${excerpt.citation_id ?? ""}`, 14), - kind: excerpt.kind, - title: truncateText(title, 100), - text_preview: redacted.text, - score: Number(excerpt.score.toFixed(6)), - citation_ids: citation ? [citation.id] : [], - provenance: { - source: "search", - record_ref: `${excerpt.kind}:${excerpt.result_id}`, - created_at: context.created_at, - updated_at: null, - metadata_keys: [] + return citations; +} +function getKnowledgeSyncConflictEvidence(dbPath, id) { + const conflict = getKnowledgeSyncConflict(dbPath, id); + if (!conflict) + throw new Error(`Sync conflict not found: ${id}`); + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const localRow = sanitizeConflictEvidenceRow(catalogRowForConflict(db, conflict)); + const remoteRow = rowFromMetadata(conflict.metadata, ["remote_row", "source_row", "incoming_row"]); + const refs = collectSourceRefs({ + conflict: { + entity_kind: conflict.entity_kind, + entity_id: conflict.entity_id, + metadata: conflict.metadata + }, + local_row: localRow, + remote_row: remoteRow + }); + const sourceRefs = [...refs].slice(0, 25); + const readOnlyTools = [ + { + name: "knowledge_sync_conflict_get", + input: { id }, + output_summary: `${conflict.entity_kind}:${conflict.entity_id} status=${conflict.status}` + }, + { + name: "knowledge_catalog_row_get", + input: { table: conflict.entity_kind, key: conflict.entity_id }, + output_summary: localRow ? "local row found" : "local row unavailable" + }, + { + name: "knowledge_source_ref_extract", + input: { id }, + output_summary: `${sourceRefs.length} source/artifact ref(s) found` } + ]; + return { + conflict, + local_row: localRow, + remote_row: remoteRow, + source_refs: sourceRefs, + citations: conflictCitations({ conflict, localRow, remoteRow, sourceRefs }), + read_only_tools: readOnlyTools }; - }); - const usedCitationIds = new Set(evidence.flatMap((entry) => entry.citation_ids)); - const citations = Array.from(citationMap.values()).filter((citation) => usedCitationIds.has(citation.id)); + } finally { + db.close(); + } +} +function proposeKnowledgeSyncConflictResolution(dbPath, id) { + const conflict = getKnowledgeSyncConflict(dbPath, id); + if (!conflict) + throw new Error(`Sync conflict not found: ${id}`); + const proposedStrategy = conflict.entity_kind === "wiki_pages" ? "manual-merge" : "review-and-select"; + const summary = [ + `Conflict ${conflict.id} affects ${conflict.entity_kind}:${conflict.entity_id}.`, + `Local machine ${conflict.local_machine_id} has ${conflict.local_hash ?? "unknown hash"}.`, + `Remote machine ${conflict.remote_machine_id} has ${conflict.remote_hash ?? "unknown hash"}.` + ].join(" "); + const mergePrompt = [ + "Review this knowledge sync conflict before any durable write.", + `Entity: ${conflict.entity_kind}:${conflict.entity_id}`, + `Local machine/hash: ${conflict.local_machine_id} / ${conflict.local_hash ?? "unknown"}`, + `Remote machine/hash: ${conflict.remote_machine_id} / ${conflict.remote_hash ?? "unknown"}`, + `Base hash: ${conflict.base_hash ?? "unknown"}`, + `Metadata: ${JSON.stringify(conflict.metadata)}`, + "Return a concise merge recommendation with citations to the competing records. Do not write changes without approval." + ].join(` +`); return { - citations, - evidence, - duplicateCandidates: [], - redactions, - warnings: context.warnings, - available: context.excerpts.length + ok: true, + conflict, + requires_approval: true, + mode: "deterministic", + proposed_strategy: proposedStrategy, + summary, + merge_prompt: mergePrompt, + proposed_patch: null, + citations: conflictCitations({ conflict, localRow: null, remoteRow: null, sourceRefs: [] }), + confidence: null, + agent: null, + warnings: conflict.status === "resolved" ? ["conflict_already_resolved"] : [], + message: `Prepared approval-gated merge proposal for ${conflict.id}` }; } -function loadRunRows(db, cutoff, limit) { - if (cutoff) { - return db.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at - FROM runs - WHERE updated_at >= ? OR created_at >= ? - ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(cutoff, cutoff, limit); +function resolveKnowledgeSyncConflict(dbPath, input) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = nowIso(); + try { + const existing = db.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(input.id); + if (!existing) + throw new Error(`Sync conflict not found: ${input.id}`); + db.query(` + UPDATE knowledge_sync_conflicts + SET status = 'resolved', + resolution_strategy = ?, + proposed_patch_uri = ?, + approved_by = ?, + resolved_at = ? + WHERE id = ? + `).run(input.strategy, input.proposedPatchUri ?? existing.proposed_patch_uri, input.approvedBy, now, input.id); + const row = db.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(input.id); + if (!row) + throw new Error(`Sync conflict not found after resolve: ${input.id}`); + return hydrateConflict(row); + } finally { + db.close(); } - return db.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at - FROM runs - ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(limit); } -function loadRunEvents(db, runIds, limit) { - if (runIds.length === 0) - return []; - const placeholders2 = runIds.map(() => "?").join(", "); - return db.query(`SELECT id, run_id, level, event, metadata_json, created_at - FROM run_events - WHERE run_id IN (${placeholders2}) - ORDER BY created_at DESC - LIMIT ?`).all(...runIds, limit); +function syncTablesFromSnapshot(snapshot) { + return parseJson(snapshot.tables_json, {}); } -function rowMentionsLoop(row, events) { - const text = `${row.type} ${row.metadata_json} ${events.map((event) => `${event.event} ${event.metadata_json}`).join(" ")}`.toLowerCase(); - return text.includes("loop"); +function syncArtifactsFromSnapshot(snapshot) { + return parseJson(snapshot.artifact_hashes_json, []); } -function citationForRun(row, metadata, policy) { - const sourceRef = metadataRef(metadata, ["source_ref", "source_uri", "evidence_uri", "receipt_uri"], policy); - const artifactUri = metadataRef(metadata, ["artifact_uri"], policy); - const artifactPath = metadataRef(metadata, ["artifact_path", "artifact_key"], policy); - const ref = sourceRef ?? artifactUri ?? artifactPath ?? `knowledge://project/runs/${row.id}`; - const quote = row.prompt ? redactPreview(row.prompt, policy, 180).text : null; - return { - id: stableId5("cite", `run\x00${row.id}\x00${ref}`, 12), - kind: artifactUri || artifactPath ? "artifact" : "run", - ref, - source_ref: sourceRef?.startsWith("open-files://") ? sourceRef : null, - source_uri: sourceRef && !sourceRef.startsWith("open-files://") ? sourceRef : null, - artifact_uri: artifactUri, - artifact_path: artifactPath, - run_id: row.id, - run_event_id: null, - revision: metadataRef(metadata, ["revision"], policy), - hash: metadataRef(metadata, ["hash", "content_hash"], policy), - chunk_id: null, - offsets: { start: null, end: null }, - quote_preview: quote - }; + +// src/conflict-agent.ts +function estimateTokens2(value) { + const text = typeof value === "string" ? value : JSON.stringify(value); + const words = text.trim().split(/\s+/).filter(Boolean).length; + return Math.max(1, Math.ceil(words * 1.25)); } -function citationForEvent(row, metadata, policy) { - const sourceRef = metadataRef(metadata, ["source_ref", "source_uri", "evidence_uri", "receipt_uri"], policy); - const artifactUri = metadataRef(metadata, ["artifact_uri"], policy); - const artifactPath = metadataRef(metadata, ["artifact_path", "artifact_key"], policy); - const ref = sourceRef ?? artifactUri ?? artifactPath ?? `knowledge://project/runs/${row.run_id}`; - const quote = redactPreview(row.event, policy, 160).text; - return { - id: stableId5("cite", `event\x00${row.id}\x00${ref}`, 12), - kind: artifactUri || artifactPath ? "artifact" : "run_event", - ref, - source_ref: sourceRef?.startsWith("open-files://") ? sourceRef : null, - source_uri: sourceRef && !sourceRef.startsWith("open-files://") ? sourceRef : null, - artifact_uri: artifactUri, - artifact_path: artifactPath, - run_id: row.run_id, - run_event_id: row.id, - revision: metadataRef(metadata, ["revision"], policy), - hash: metadataRef(metadata, ["hash", "content_hash"], policy), - chunk_id: null, - offsets: { start: null, end: null }, - quote_preview: quote - }; +function insertConflictRun(options) { + const db = openKnowledgeDb(options.dbPath); + try { + db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + options.runId, + "sync-conflict-proposal", + options.prompt, + options.status, + options.provider, + options.model, + JSON.stringify(options.metadata), + options.now, + options.now + ]); + } finally { + db.close(); + } } -function duplicateCandidatesFor(evidence) { - const groups = new Map; - for (const entry of evidence) { - const key = normalizedSearchText(`${entry.title} ${entry.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g, "").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g, "").replace(/[^a-z0-9 ]+/g, "").replace(/\b(?:run|event|completed|dry_run|pending)\b/g, "").replace(/\s+/g, " ").trim().slice(0, 220); - if (!key) - continue; - groups.set(key, [...groups.get(key) ?? [], entry.id]); +function updateConflictRun(options) { + const db = openKnowledgeDb(options.dbPath); + try { + db.run(`UPDATE runs + SET status = ?, provider = ?, model = ?, cost_tokens = ?, cost_usd = ?, metadata_json = ?, updated_at = ? + WHERE id = ?`, [ + options.status, + options.provider, + options.model, + options.usage.input_tokens + options.usage.output_tokens, + options.usage.cost_usd, + JSON.stringify(options.metadata), + options.now, + options.runId + ]); + } finally { + db.close(); } - return Array.from(groups.entries()).filter(([, ids]) => ids.length > 1).map(([key, ids]) => ({ - id: stableId5("dup", key, 12), - reason: "normalized_text_match", - evidence_ids: ids, - confidence: ids.length > 2 ? "high" : "medium" - })); } -async function buildRunDraft(options, maxItems, now) { - const source = options.source === "loops" ? "loops" : "runs"; - const topic = (options.topic ?? options.query ?? "").trim(); - const topicTerms = termsFor(topic); - const since = parseSince(options.since, now); - const warnings = since.warning ? [since.warning] : []; - migrateKnowledgeDb(options.dbPath); +function addConflictRunEvent(options) { const db = openKnowledgeDb(options.dbPath); try { - const runRows = loadRunRows(db, since.cutoff, Math.max(maxItems * 8, 40)); - const allEvents = loadRunEvents(db, runRows.map((row) => row.id), Math.max(maxItems * 12, 80)); - const eventsByRun = new Map; - for (const event of allEvents) - eventsByRun.set(event.run_id, [...eventsByRun.get(event.run_id) ?? [], event]); - const filteredRuns = source === "loops" ? runRows.filter((row) => rowMentionsLoop(row, eventsByRun.get(row.id) ?? [])) : runRows; - const scoredRuns = filteredRuns.map((row) => { - const metadata = parseJsonObject5(row.metadata_json); - const text = `${row.type} ${row.status} ${row.prompt ?? ""} ${summarizeMetadata(metadata)} ${(eventsByRun.get(row.id) ?? []).map((event) => `${event.event} ${event.metadata_json}`).join(" ")}`; - return { row, metadata, score: scoreAgainstTopic(text, topicTerms), text }; - }).filter((entry) => topicTerms.length === 0 || entry.score > 0).sort((a, b) => b.score - a.score || b.row.updated_at.localeCompare(a.row.updated_at) || a.row.id.localeCompare(b.row.id)); - const citations = []; - const evidence = []; - let redactions = 0; - for (const entry of scoredRuns.slice(0, Math.max(maxItems * 2, maxItems))) { - const citation = citationForRun(entry.row, entry.metadata, options.safetyPolicy); - citations.push(citation); - const metadataSummary = summarizeMetadata(entry.metadata); - const previewInput = [entry.row.prompt, metadataSummary].filter(Boolean).join(" | ") || `${entry.row.type} ${entry.row.status}`; - const preview2 = redactPreview(previewInput, options.safetyPolicy, 420); - redactions += preview2.redactions; - evidence.push({ - id: `run:${entry.row.id}`, - kind: entry.row.type, - title: truncateText(`${entry.row.type}: ${entry.row.status}`, 100), - text_preview: preview2.text, - score: entry.score, - citation_ids: [citation.id], - provenance: { - source, - record_ref: `knowledge://project/runs/${entry.row.id}`, - created_at: entry.row.created_at, - updated_at: entry.row.updated_at, - metadata_keys: metadataKeys(entry.metadata) - } - }); - const eventRows = (eventsByRun.get(entry.row.id) ?? []).map((event) => { - const metadata = parseJsonObject5(event.metadata_json); - const text = `${event.event} ${summarizeMetadata(metadata)} ${event.metadata_json}`; - return { event, metadata, score: scoreAgainstTopic(text, topicTerms), text }; - }).filter((eventEntry) => topicTerms.length === 0 || eventEntry.score > 0).sort((a, b) => b.score - a.score || b.event.created_at.localeCompare(a.event.created_at) || a.event.id.localeCompare(b.event.id)).slice(0, 2); - for (const eventEntry of eventRows) { - const eventCitation = citationForEvent(eventEntry.event, eventEntry.metadata, options.safetyPolicy); - citations.push(eventCitation); - const preview3 = redactPreview(`${eventEntry.event}: ${summarizeMetadata(eventEntry.metadata)}`, options.safetyPolicy, 320); - redactions += preview3.redactions; - evidence.push({ - id: `event:${eventEntry.event.id}`, - kind: `run_event:${eventEntry.event.level}`, - title: truncateText(eventEntry.event.event, 100), - text_preview: preview3.text, - score: eventEntry.score, - citation_ids: [eventCitation.id], - provenance: { - source, - record_ref: `knowledge://project/runs/${eventEntry.event.run_id}`, - created_at: eventEntry.event.created_at, - updated_at: null, - metadata_keys: metadataKeys(eventEntry.metadata) - } - }); - } - } - return { - citations, - evidence, - duplicateCandidates: options.dedupe ? duplicateCandidatesFor(evidence) : [], - redactions, - warnings, - available: scoredRuns.length - }; + db.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, [ + `event_${randomUUID8()}`, + options.runId, + options.level, + options.event, + JSON.stringify(options.metadata), + options.now + ]); } finally { db.close(); } } -function outlineFor(input) { - const title = input.purpose === "proposal" ? `Proposal context: ${truncateText(input.query || "loop evidence", 80)}` : `Knowledge context: ${truncateText(input.query, 80)}`; - const evidenceIds = input.evidence.slice(0, 8).map((entry) => entry.id); - const duplicateIds = input.duplicates.slice(0, 5).map((entry) => entry.id); - const bullets = input.evidence.slice(0, 5).map((entry) => `${entry.id}: ${entry.title}`); - if (input.evidence.length === 0) - bullets.push("No matching bounded evidence was found."); - return { - title, - bullets, - evidence_ids: evidenceIds, - duplicate_candidate_ids: duplicateIds, - next_actions: input.source === "loops" ? [ - "Review duplicate_candidates before drafting a new proposal.", - "Use cited run refs for provenance; inspect a run only when more detail is needed.", - "Keep proposal writes approval-gated and idempotent." - ] : [ - "Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.", - "Inspect cited refs only if the bounded preview is insufficient.", - "Use knowledge build/file-answer only with explicit approval for durable writes." - ] - }; +function recordUsage2(dbPath, runId, usage, now) { + const db = openKnowledgeDb(dbPath); + try { + recordProviderUsage(db, { + ...usage, + run_id: runId, + created_at: now + }); + } finally { + db.close(); + } } -function pruneCitations(pack) { - const used = new Set(pack.evidence.flatMap((entry) => entry.citation_ids)); - pack.citations = pack.citations.filter((citation) => used.has(citation.id)); +function promptForConflict(input) { + return [ + "Build an approval-gated merge proposal for this knowledge sync conflict.", + "Use only the supplied JSON evidence. Do not claim to inspect external files or write changes.", + "Return a patch recommendation that a human can review before approval.", + "", + `Deterministic proposal: +${JSON.stringify({ + proposed_strategy: input.deterministic.proposed_strategy, + summary: input.deterministic.summary, + warnings: input.deterministic.warnings + }, null, 2)}`, + "", + `Conflict evidence: +${JSON.stringify(input.evidence, null, 2)}` + ].join(` +`); } -function syncOutline(pack) { - pack.outline.evidence_ids = pack.evidence.slice(0, 8).map((entry) => entry.id); - pack.outline.bullets = pack.evidence.length > 0 ? pack.evidence.slice(0, 5).map((entry) => `${entry.id}: ${entry.title}`) : ["No matching bounded evidence was found."]; - pack.outline.duplicate_candidate_ids = pack.duplicate_candidates.slice(0, 5).map((entry) => entry.id); +function normalizeConfidence(value) { + const number4 = typeof value === "number" && Number.isFinite(value) ? value : 0.5; + return Math.max(0, Math.min(1, number4)); } -function fitPackToBudget(pack) { - const maxTokens = pack.budgets.max_tokens; - const warnings = new Set(pack.warnings); - while (estimateTokensForValue(pack) > maxTokens) { - const longest = pack.evidence.map((entry, index) => ({ entry, index })).filter(({ entry }) => entry.text_preview.length > 180).sort((a, b) => b.entry.text_preview.length - a.entry.text_preview.length)[0]; - if (longest) { - longest.entry.text_preview = truncateText(longest.entry.text_preview, 180); - warnings.add("text_preview_truncated_for_token_budget"); - continue; - } - const longCitation = pack.citations.filter((citation) => (citation.quote_preview?.length ?? 0) > 120).sort((a, b) => (b.quote_preview?.length ?? 0) - (a.quote_preview?.length ?? 0))[0]; - if (longCitation?.quote_preview) { - longCitation.quote_preview = truncateText(longCitation.quote_preview, 120); - warnings.add("citation_quote_truncated_for_token_budget"); - continue; - } - if (pack.evidence.length > 0) { - pack.evidence.pop(); - pack.budgets.items_truncated += 1; - pack.duplicate_candidates = pack.duplicate_candidates.map((candidate) => ({ - ...candidate, - evidence_ids: candidate.evidence_ids.filter((id) => pack.evidence.some((entry) => entry.id === id)) - })).filter((candidate) => candidate.evidence_ids.length > 1); - syncOutline(pack); - warnings.add("evidence_truncated_for_token_budget"); - pruneCitations(pack); - continue; +function normalizePatch(value, conflictTarget) { + const kind = value.kind === "choose_local" || value.kind === "choose_remote" || value.kind === "no_op" || value.kind === "custom" || value.kind === "manual_merge" ? value.kind : "manual_merge"; + return { + kind, + target: typeof value.target === "string" && value.target ? value.target : conflictTarget, + strategy: typeof value.strategy === "string" && value.strategy ? value.strategy : kind.replace("_", "-"), + summary: typeof value.summary === "string" && value.summary ? value.summary : "Review both sides before applying a merge.", + diff: typeof value.diff === "string" && value.diff ? value.diff : null, + metadata: value.metadata && typeof value.metadata === "object" && !Array.isArray(value.metadata) ? value.metadata : {} + }; +} +function fakePatch(input) { + const target = `${input.conflict.entity_kind}:${input.conflict.entity_id}`; + const hasBothRows = Boolean(input.local_row && input.remote_row); + return { + kind: hasBothRows ? "manual_merge" : "custom", + target, + strategy: hasBothRows ? "manual-merge" : "review-and-select", + summary: hasBothRows ? `Fake AI proposal: compare local and remote ${target} row snapshots, then apply a reviewed manual merge.` : `Fake AI proposal: inspect ${target} with available conflict metadata before selecting a side.`, + diff: hasBothRows ? [ + `--- ${target} local`, + `+++ ${target} remote`, + "@@ review-required @@", + JSON.stringify({ local: input.local_row, remote: input.remote_row }, null, 2).slice(0, 1200) + ].join(` +`) : null, + metadata: { + fake: true, + local_hash: input.conflict.local_hash, + remote_hash: input.conflict.remote_hash, + source_refs: input.source_refs } - if (pack.outline.next_actions.length > 1) { - pack.outline.next_actions.pop(); - warnings.add("outline_truncated_for_token_budget"); - continue; + }; +} +async function proposeKnowledgeSyncConflictResolutionWithAi(options) { + const now = (options.now ?? new Date).toISOString(); + migrateKnowledgeDb(options.dbPath); + const deterministic = proposeKnowledgeSyncConflictResolution(options.dbPath, options.id); + const evidence = getKnowledgeSyncConflictEvidence(options.dbPath, options.id); + const resolvedModelRef = resolveModelRef(options.modelRef ?? "default", options.config); + const parsed = parseModelRef(resolvedModelRef); + const runId = `run_${randomUUID8()}`; + const prompt = promptForConflict({ deterministic, evidence }); + insertConflictRun({ + dbPath: options.dbPath, + runId, + prompt, + provider: parsed.provider, + model: parsed.model, + status: options.fake ? "dry_run" : "running", + metadata: { + conflict_id: options.id, + mode: "ai", + fake: options.fake === true, + read_only_tools: evidence.read_only_tools.map((tool) => tool.name) + }, + now + }); + addConflictRunEvent({ + dbPath: options.dbPath, + runId, + level: "info", + event: "conflict_evidence_retrieved", + metadata: { + citations: evidence.citations.length, + source_refs: evidence.source_refs.length, + read_only_tools: evidence.read_only_tools + }, + now + }); + let patch; + let summary; + let confidence = 0.5; + let usage = { + input_tokens: estimateTokens2(prompt), + output_tokens: 0, + cost_usd: 0 + }; + if (options.fake) { + patch = fakePatch(evidence); + summary = patch.summary; + usage.output_tokens = estimateTokens2(summary) + estimateTokens2(patch.diff ?? ""); + } else { + try { + const { generateObject } = await import("ai"); + const { z: z2 } = await Promise.resolve().then(() => (init_zod(), exports_zod)); + const model = await languageModelFor(resolvedModelRef, { + config: options.config, + env: options.env + }); + const schema = z2.object({ + summary: z2.string(), + confidence: z2.number().min(0).max(1), + proposed_patch: z2.object({ + kind: z2.enum(["manual_merge", "choose_local", "choose_remote", "no_op", "custom"]), + target: z2.string(), + strategy: z2.string(), + summary: z2.string(), + diff: z2.string().nullable(), + metadata: z2.record(z2.string(), z2.unknown()).default({}) + }) + }); + const result = await generateObject({ + model, + schema, + system: "You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.", + prompt + }); + summary = result.object.summary; + confidence = normalizeConfidence(result.object.confidence); + patch = normalizePatch(result.object.proposed_patch, `${evidence.conflict.entity_kind}:${evidence.conflict.entity_id}`); + const normalized = normalizeAiSdkUsage({ + provider: parsed.provider, + model: parsed.model, + usage: result.usage, + providerMetadata: result.providerMetadata + }); + usage = { + input_tokens: normalized.input_tokens, + output_tokens: normalized.output_tokens, + cost_usd: normalized.cost_usd + }; + recordUsage2(options.dbPath, runId, normalized, now); + } catch (error51) { + addConflictRunEvent({ + dbPath: options.dbPath, + runId, + level: "error", + event: "conflict_proposal_generation_failed", + metadata: { message: error51 instanceof Error ? error51.message : String(error51) }, + now + }); + updateConflictRun({ + dbPath: options.dbPath, + runId, + status: "failed", + provider: parsed.provider, + model: parsed.model, + usage, + metadata: { + conflict_id: options.id, + mode: "ai", + error: error51 instanceof Error ? error51.message : String(error51) + }, + now + }); + throw error51; } - warnings.add("token_budget_floor_exceeded"); - break; - } - pack.warnings = Array.from(warnings).sort(); - pack.budgets.items_included = pack.evidence.length; - syncOutline(pack); - pack.budgets.estimated_tokens = estimateTokensForValue(pack); - pack.budgets.token_budget_exceeded = pack.budgets.estimated_tokens > maxTokens; - if (pack.budgets.token_budget_exceeded) { - throw new Error(`Unable to build context pack within ${maxTokens} token budget; increase --max-tokens.`); - } - pack.message = `${pack.evidence.length} bounded evidence item(s), estimated ${pack.budgets.estimated_tokens}/${maxTokens} token(s)`; - return pack; -} -async function buildKnowledgeAgentContextPack(options) { - const now = options.now ?? new Date; - const source = options.source ?? "search"; - const purpose = options.purpose ?? (source === "loops" || source === "runs" ? "proposal" : "agent_context"); - const maxTokens = coerceMaxTokens(options.maxTokens); - const maxItems = coerceMaxItems(options.maxItems, options.limit); - const query2 = normalizeText(options.query ?? options.topic ?? ""); - if (purpose === "proposal" && source !== "search" && !query2) { - throw new Error("Proposal context requires --topic <text> or a positional topic."); } - if (source !== "search") - migrateKnowledgeDb(options.dbPath); - const sinceForKey = parseSince(options.since, now).cutoff ?? options.since ?? ""; - const draft = source === "search" ? await buildSearchDraft(options, maxItems) : await buildRunDraft(options, maxItems, now); - const sortedEvidence = draft.evidence.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, maxItems); - const sortedCitations = draft.citations.filter((citation, index, rows) => rows.findIndex((entry) => entry.id === citation.id) === index).sort((a, b) => a.id.localeCompare(b.id)); - const duplicateCandidates = options.dedupe ? duplicateCandidatesFor(sortedEvidence) : draft.duplicateCandidates.filter((candidate) => candidate.evidence_ids.every((id) => sortedEvidence.some((entry) => entry.id === id))); - const outline = outlineFor({ - source, - purpose, - query: query2, - evidence: sortedEvidence, - duplicates: duplicateCandidates + updateConflictRun({ + dbPath: options.dbPath, + runId, + status: options.fake ? "dry_run" : "completed", + provider: parsed.provider, + model: parsed.model, + usage, + metadata: { + conflict_id: options.id, + mode: "ai", + fake: options.fake === true, + confidence, + proposed_strategy: patch.strategy, + citation_count: evidence.citations.length + }, + now }); - const pack = { - ok: true, - format: "knowledge-agent-context-pack", - version: 1, - created_at: now.toISOString(), - source, - purpose, - query: query2, - topic: options.topic ?? null, - since: options.since ?? null, - dry_run: true, - idempotency_key: stableId5("ctx", [ - source, - purpose, - query2, - sinceForKey, - options.dedupe === true ? "dedupe" : "no-dedupe", - options.semantic === true ? "semantic" : "keyword", - options.modelRef ?? "", - options.limit ?? "", - maxTokens, - maxItems, - sortedEvidence.map((entry) => entry.id).join(","), - sortedCitations.map((entry) => entry.id).join(",") - ].join("\x00"), 20), - budgets: { - max_tokens: maxTokens, - estimated_tokens: 0, - max_items: maxItems, - items_included: sortedEvidence.length, - items_available: draft.available, - items_truncated: Math.max(0, draft.available - sortedEvidence.length), - token_budget_exceeded: false + addConflictRunEvent({ + dbPath: options.dbPath, + runId, + level: "info", + event: options.fake ? "fake_conflict_proposal_generated" : "conflict_proposal_generated", + metadata: { + strategy: patch.strategy, + confidence, + patch_kind: patch.kind }, - safety: { - raw_artifact_content_included: false, - durable_writes_performed: false, - redactions: draft.redactions, - reminders: baseSafetyReminders(source) + now + }); + return { + ...deterministic, + mode: "ai", + proposed_strategy: patch.strategy, + summary, + proposed_patch: patch, + citations: evidence.citations, + confidence, + agent: { + generated: true, + provider: parsed.provider, + model: parsed.model, + run_id: runId, + read_only_tools: evidence.read_only_tools, + usage }, - citations: sortedCitations, - evidence: sortedEvidence, - duplicate_candidates: duplicateCandidates, - outline, - warnings: draft.warnings, - message: `${sortedEvidence.length} bounded evidence item(s), estimated under ${maxTokens} token(s)` + warnings: [ + ...deterministic.warnings, + ...evidence.remote_row ? [] : ["remote_row_snapshot_unavailable"] + ], + message: `Prepared AI SDK approval-gated merge proposal for ${options.id}` }; - pruneCitations(pack); - return fitPackToBudget(pack); } -// src/conflict-agent.ts -import { randomUUID as randomUUID8 } from "crypto"; - -// src/sync.ts -import { createHash as createHash12, randomUUID as randomUUID7 } from "crypto"; -import { existsSync as existsSync9, readFileSync as readFileSync10 } from "fs"; -import { hostname } from "os"; -import { fileURLToPath as fileURLToPath2 } from "url"; -import { extname, relative as relative3, resolve as resolve3, sep as sep3 } from "path"; -var KNOWLEDGE_SYNC_TABLES = [ - "sources", - "wiki_pages", - "source_revisions", - "chunks", - "chunk_embeddings", - "wiki_backlinks", - "citations", - "knowledge_indexes", - "runs", - "run_events", - "provider_usage", - "redaction_findings", - "storage_objects", - "audit_events", - "approval_gates", - "vector_index_entries", - "reindex_queue", - "knowledge_machines", - "knowledge_sync_snapshots", - "knowledge_sync_changes", - "knowledge_sync_conflicts", - "knowledge_sync_table_clocks", - "knowledge_sync_imports" -]; -var KNOWLEDGE_SYNC_PROTOCOL_VERSION = 2; -var KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION = 1; -var PRIMARY_KEYS = { - sources: ["id"], - wiki_pages: ["id"], - source_revisions: ["id"], - chunks: ["id"], - chunk_embeddings: ["id"], - wiki_backlinks: ["from_page_id", "to_page_id"], - citations: ["id"], - knowledge_indexes: ["id"], - runs: ["id"], - run_events: ["id"], - provider_usage: ["id"], - redaction_findings: ["id"], - storage_objects: ["id"], - audit_events: ["id"], - approval_gates: ["id"], - vector_index_entries: ["id"], - reindex_queue: ["id"], - knowledge_machines: ["machine_id"], - knowledge_sync_snapshots: ["id"], - knowledge_sync_changes: ["id"], - knowledge_sync_conflicts: ["id"], - knowledge_sync_table_clocks: ["table_name", "machine_id"], - knowledge_sync_imports: ["bundle_id"] -}; -var TABLE_SYNC_EXCLUDES = new Set([ - "storage_objects", - "knowledge_sync_changes", - "knowledge_sync_table_clocks", - "knowledge_sync_imports" -]); -function nowIso(now = new Date) { - return now.toISOString(); +// src/outbox-consume.ts +import { createHash as createHash13, randomUUID as randomUUID9 } from "crypto"; +import { existsSync as existsSync10, readFileSync as readFileSync12 } from "fs"; +import { basename as basename4 } from "path"; +function stableId6(prefix, value) { + return `${prefix}_${createHash13("sha256").update(value).digest("hex").slice(0, 20)}`; } -function makeSyncId(prefix) { - return `${prefix}_${Date.now().toString(36)}_${randomUUID7().slice(0, 8)}`; +function asObject2(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : undefined; } -function defaultSyncMachineId(input) { - const explicit = input?.trim(); +function asString2(value) { + return typeof value === "string" && value.length > 0 ? value : undefined; +} +function buildSourceRef(event) { + const explicit = asString2(event.source_ref) ?? asString2(event.source_uri) ?? asString2(event.uri); if (explicit) return explicit; - return process.env.HASNA_MACHINE_ID ?? process.env.OPEN_MACHINES_MACHINE_ID ?? process.env.MACHINE_ID ?? hostname(); + const fileId = asString2(event.file_id); + if (fileId) { + const revision = asString2(event.revision_id) ?? asString2(event.revision); + const fileRef = `open-files://file/${encodeURIComponent(fileId)}`; + return revision ? `${fileRef}/revision/${encodeURIComponent(revision)}` : fileRef; + } + const sourceId = asString2(event.source_id); + const path = asString2(event.path); + if (sourceId && path) { + return `open-files://source/${encodeURIComponent(sourceId)}/path/${encodeURIComponent(path)}`; + } + throw new Error("Outbox event is missing source_ref, file_id, or source_id/path."); } -function stableJson(value) { - if (Array.isArray(value)) - return `[${value.map(stableJson).join(",")}]`; - if (value && typeof value === "object") { - const record = value; - return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`; +function baseSourceUri2(sourceRef, parsed) { + if (parsed.kind === "open-files" && parsed.entity === "file" && parsed.revision_id) { + return sourceRef.replace(/\/revision\/[^/]+$/, ""); } - return JSON.stringify(value); + return sourceRef; } -function sha256(value) { - return `sha256:${createHash12("sha256").update(value).digest("hex")}`; +function hashFromEvent(event) { + return asString2(event.hash) ?? asString2(event.checksum) ?? asString2(event.sha256) ?? null; } -function count2(db, table) { - const row = db.query(`SELECT COUNT(*) AS n FROM ${table}`).get(); - return row?.n ?? 0; +function revisionFromEvent(event, parsed, hash2) { + return asString2(event.revision_id) ?? asString2(event.revision) ?? asString2(event.version_id) ?? (parsed.kind === "open-files" ? parsed.revision_id : undefined) ?? hash2 ?? null; } -function parseJson(value, fallback) { - try { - return JSON.parse(value); - } catch { - return fallback; - } +function previousRevisionFromEvent(event) { + return asString2(event.previous_revision_id) ?? asString2(event.previous_revision) ?? asString2(event.previous_version_id) ?? null; } -function quoteIdent(identifier) { - return `"${identifier.replace(/"/g, '""')}"`; +function eventType(event) { + return (asString2(event.event_type) ?? asString2(event.event) ?? asString2(event.type) ?? asString2(event.action) ?? asString2(event.change_type) ?? "changed").toLowerCase(); } -function coerceForSqlite(value) { - if (value === undefined || value === null) - return null; - if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") - return value; - if (value instanceof Date) - return value.toISOString(); - if (Buffer.isBuffer(value) || value instanceof Uint8Array) - return value; - if (typeof value === "object") - return JSON.stringify(value); - return String(value); +function titleFromEvent(event) { + const path = asString2(event.path); + return asString2(event.title) ?? asString2(event.name) ?? (path ? basename4(path) : null); } -function filterExistingTables(db, tables) { - return tables.filter((table) => tableExists2(db, table)); +function normalizeEvent(event, now) { + const sourceRef = buildSourceRef(event); + const parsed = parseSourceRef(sourceRef); + const hash2 = hashFromEvent(event); + return { + raw: event, + eventType: eventType(event), + sourceRef, + sourceUri: baseSourceUri2(sourceRef, parsed), + kind: parsed.kind, + title: titleFromEvent(event), + revision: revisionFromEvent(event, parsed, hash2), + previousRevision: previousRevisionFromEvent(event), + hash: hash2, + status: asString2(event.status)?.toLowerCase() ?? null, + updatedAt: asString2(event.updated_at) ?? now, + acl: event.permissions ?? event.acl ?? undefined + }; } -function tableExists2(db, table) { - const row = db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table); - return Boolean(row); +function parseOutboxText(text) { + const trimmed = text.trim(); + if (!trimmed) + return []; + if (trimmed.startsWith("[")) { + const parsed = JSON.parse(trimmed); + if (!Array.isArray(parsed)) + throw new Error("Outbox array parse failed."); + return parsed.map((entry) => { + const event = asObject2(entry); + if (!event) + throw new Error("Outbox array entries must be objects."); + return event; + }); + } + if (trimmed.startsWith("{")) { + try { + const parsed = JSON.parse(trimmed); + const object2 = asObject2(parsed); + if (!object2) + throw new Error("Outbox object parse failed."); + if (Array.isArray(object2.events)) { + return object2.events.map((entry) => { + const event = asObject2(entry); + if (!event) + throw new Error("Outbox events entries must be objects."); + return event; + }); + } + if ("source_ref" in object2 || "source_uri" in object2 || "file_id" in object2) + return [object2]; + } catch (error51) { + const lines = trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0); + if (lines.length <= 1) + throw error51; + return lines.map((line) => { + const event = asObject2(JSON.parse(line)); + if (!event) + throw new Error("Outbox JSONL entries must be objects."); + return event; + }); + } + } + return trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => { + const event = asObject2(JSON.parse(line)); + if (!event) + throw new Error("Outbox JSONL entries must be objects."); + return event; + }); } -function localColumns(db, table) { - const rows = db.query(`PRAGMA table_info(${quoteIdent(table)})`).all(); - return new Set(rows.map((row) => row.name)); +async function readS3Text3(uri, config2, safetyPolicy) { + const parsed = new URL(uri); + const bucket = parsed.hostname; + const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); + if (!bucket || !key) + throw new Error(`Invalid S3 outbox URI: ${uri}`); + if (safetyPolicy) + assertS3ReadAllowed(uri, safetyPolicy); + const [{ S3Client, GetObjectCommand }, { fromIni }] = await Promise.all([ + import("@aws-sdk/client-s3"), + import("@aws-sdk/credential-providers") + ]); + const s3Config = config2?.storage.type === "s3" && config2.storage.s3?.bucket === bucket ? config2.storage.s3 : undefined; + const client = new S3Client({ + region: s3Config?.region, + credentials: s3Config?.profile ? fromIni({ profile: s3Config.profile }) : undefined, + maxAttempts: s3Config?.max_attempts + }); + const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key })); + if (!response.Body) + return ""; + return await response.Body.transformToString(); } -function filterLocalColumns(db, table, columns) { - const allowed = localColumns(db, table); - return columns.filter((column) => allowed.has(column)); +async function readOutboxInput(input, config2, safetyPolicy) { + if (input.startsWith("s3://")) + return readS3Text3(input, config2, safetyPolicy); + if (!existsSync10(input)) + throw new Error(`Outbox not found: ${input}`); + return readFileSync12(input, "utf8"); } -function resolveSyncTables(tables) { - if (!tables || tables.length === 0) - return [...KNOWLEDGE_SYNC_TABLES]; - const allowed = new Set(KNOWLEDGE_SYNC_TABLES); - const requested = tables.map((table) => table.trim()).filter(Boolean); - const invalid = requested.filter((table) => !allowed.has(table)); - if (invalid.length > 0) - throw new Error(`Unknown knowledge sync table(s): ${invalid.join(", ")}`); - return requested; +function mergeJson(existing, patch) { + let base = {}; + if (existing) { + try { + base = asObject2(JSON.parse(existing)) ?? {}; + } catch { + base = {}; + } + } + return JSON.stringify({ ...base, ...patch }); } -function rowKey(table, row) { - const primaryKeys = PRIMARY_KEYS[table]; - return primaryKeys.map((key) => `${key}=${JSON.stringify(row[key] ?? null)}`).join("&"); +function ensureSource(db, event, now) { + const id = stableId6("src", event.sourceUri); + db.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(uri) DO UPDATE SET + kind = excluded.kind, + title = COALESCE(excluded.title, sources.title), + updated_at = excluded.updated_at`, [ + id, + event.sourceUri, + event.kind, + event.title, + JSON.stringify({ source_ref: event.sourceRef, source_uri: event.sourceUri, status: event.status, last_outbox_event: event.eventType }), + JSON.stringify(event.acl ?? {}), + now, + event.updatedAt + ]); + const row = db.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get(event.sourceUri); + if (!row) + throw new Error(`Failed to upsert source for outbox event: ${event.sourceUri}`); + const patch = { + source_ref: event.sourceRef, + source_uri: event.sourceUri, + last_outbox_event: event.eventType, + last_outbox_at: event.updatedAt + }; + if (event.status) + patch.status = event.status; + if (asString2(event.raw.path)) + patch.path = event.raw.path; + db.run("UPDATE sources SET metadata_json = ?, acl_json = CASE WHEN ? IS NULL THEN acl_json ELSE ? END, updated_at = ? WHERE id = ?", [ + mergeJson(row.metadata_json, patch), + event.acl === undefined ? null : JSON.stringify(event.acl), + event.acl === undefined ? null : JSON.stringify(event.acl), + event.updatedAt, + row.id + ]); + return row.id; } -var RAW_PAYLOAD_METADATA_KEYS = new Set([ - "raw", - "raw_bytes", - "raw_content", - "content_base64", - "source_bytes", - "source_content", - "body_bytes" -]); -function sanitizeConflictEvidenceValue(value, depth = 0) { - if (depth > 8) - return "[truncated-depth]"; - if (typeof value === "string") - return value.length > 4000 ? `${value.slice(0, 4000)}...[truncated]` : value; - if (value === null || typeof value !== "object") - return value; - if (Array.isArray(value)) - return value.slice(0, 50).map((entry) => sanitizeConflictEvidenceValue(entry, depth + 1)); - const output = {}; - for (const [key, entry] of Object.entries(value)) { - if (RAW_PAYLOAD_METADATA_KEYS.has(key.toLowerCase())) - continue; - output[key] = sanitizeConflictEvidenceValue(entry, depth + 1); +function ensureRevision(db, sourceId, event, now) { + if (!event.revision) + return null; + const id = stableId6("rev", `${sourceId}\x00${event.revision}`); + const metadata = { + source_ref: event.sourceRef, + source_uri: event.sourceUri, + status: event.status, + last_outbox_event: event.eventType, + reindex_required: true + }; + db.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(source_id, revision) DO UPDATE SET + hash = COALESCE(excluded.hash, source_revisions.hash), + metadata_json = excluded.metadata_json`, [id, sourceId, event.revision, event.hash, asString2(event.raw.extracted_text_ref) ?? null, JSON.stringify(metadata), now]); + const row = db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(sourceId, event.revision); + return row?.id ?? null; +} +function revisionIdsForEvent(db, sourceId, event) { + if (event.previousRevision) { + const previous = db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(sourceId, event.previousRevision).map((row) => row.id); + if (previous.length > 0) + return previous; } - return output; + if (event.revision) { + return db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(sourceId, event.revision).map((row) => row.id); + } + if (event.hash) { + return db.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all(sourceId, event.hash).map((row) => row.id); + } + return db.query("SELECT id FROM source_revisions WHERE source_id = ?").all(sourceId).map((row) => row.id); } -function sanitizeConflictEvidenceRow(row) { - if (!row) - return null; - return sanitizeConflictEvidenceValue(row); +function invalidateRevision(db, revisionId) { + const chunks = db.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(revisionId); + let embeddingsDeleted = 0; + let vectorEntriesDeleted = 0; + for (const chunk of chunks) { + const row = db.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(chunk.id); + embeddingsDeleted += row?.n ?? 0; + const vectorRow = db.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(chunk.id); + vectorEntriesDeleted += vectorRow?.n ?? 0; + db.run("DELETE FROM vector_index_entries WHERE chunk_id = ?", [chunk.id]); + db.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?", [chunk.id]); + db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [chunk.id]); + } + db.run("DELETE FROM chunks WHERE source_revision_id = ?", [revisionId]); + const revision = db.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get(revisionId); + db.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?", [mergeJson(revision?.metadata_json, { reindex_required: true, invalidated_at: new Date().toISOString() }), revisionId]); + return { chunksDeleted: chunks.length, embeddingsDeleted, vectorEntriesDeleted }; } -function hashValue(value) { - return sha256(stableJson(value)); +function isDeleteEvent(eventType2, status) { + return status === "deleted" || ["delete", "deleted", "remove", "removed"].includes(eventType2); } -function normalizeRowForHash(row, artifactUriToKey) { - const normalized = {}; - for (const [key, value] of Object.entries(row)) { - if (key === "artifact_uri" && typeof value === "string" && artifactUriToKey.has(value)) { - normalized[key] = `artifact:${artifactUriToKey.get(value)}`; - } else { - normalized[key] = value; - } +function isMoveEvent(eventType2) { + return ["move", "moved", "rename", "renamed", "path_changed", "canonical_key_changed"].includes(eventType2); +} +function isPermissionEvent(eventType2) { + return ["permission", "permissions", "permission_changed", "acl_changed", "acl_revoked"].includes(eventType2); +} +async function consumeOpenFilesOutbox(options) { + const now = (options.now ?? new Date).toISOString(); + if (options.safetyPolicy) + assertWriteAllowed(options.dbPath, options.safetyPolicy); + migrateKnowledgeDb(options.dbPath); + const text = await readOutboxInput(options.input, options.config, options.safetyPolicy); + const events = parseOutboxText(text); + const db = openKnowledgeDb(options.dbPath); + const runId = `run_${randomUUID9()}`; + try { + return db.transaction(() => { + db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + runId, + "open-files-outbox", + options.input, + "completed", + "local", + "open-files-outbox", + JSON.stringify({ path: options.input, events: events.length }), + now, + now + ]); + const sourcesTouched = new Set; + const revisionsTouched = new Set; + let chunksDeleted = 0; + let embeddingsDeleted = 0; + let vectorEntriesDeleted = 0; + let staleRevisions = 0; + let deletedSources = 0; + let movedSources = 0; + let permissionUpdates = 0; + recordAuditEvent(db, { + event_type: "source_read", + action: options.input.startsWith("s3://") ? "s3_outbox_read" : "local_outbox_read", + target_uri: options.input, + decision: "allow", + metadata: { events: events.length, read_only: true }, + created_at: now + }); + events.forEach((raw, index) => { + const event = normalizeEvent(raw, now); + const sourceId = ensureSource(db, event, now); + sourcesTouched.add(sourceId); + const createdRevisionId = ensureRevision(db, sourceId, event, now); + if (createdRevisionId) + revisionsTouched.add(createdRevisionId); + const affectedRevisionIds = revisionIdsForEvent(db, sourceId, event); + for (const revisionId of affectedRevisionIds) { + revisionsTouched.add(revisionId); + const invalidation = invalidateRevision(db, revisionId); + chunksDeleted += invalidation.chunksDeleted; + embeddingsDeleted += invalidation.embeddingsDeleted; + vectorEntriesDeleted += invalidation.vectorEntriesDeleted; + staleRevisions += 1; + } + if (isDeleteEvent(event.eventType, event.status)) + deletedSources += 1; + if (isMoveEvent(event.eventType)) + movedSources += 1; + if (isPermissionEvent(event.eventType) || event.acl !== undefined) + permissionUpdates += 1; + db.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, [ + stableId6("evt", `${runId}\x00${index}\x00${event.sourceRef}\x00${event.eventType}`), + runId, + "info", + event.eventType, + JSON.stringify({ + source_ref: event.sourceRef, + source_uri: event.sourceUri, + revision: event.revision, + hash: event.hash, + status: event.status, + affected_revisions: affectedRevisionIds.length + }), + event.updatedAt + ]); + }); + db.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`, [ + stableId6("usage", runId), + runId, + "local", + "open-files-outbox", + JSON.stringify({ note: "No model provider used for outbox invalidation." }), + now + ]); + recordAuditEvent(db, { + event_type: "write", + action: "knowledge_outbox_invalidation", + target_uri: options.dbPath, + decision: "allow", + metadata: { + run_id: runId, + events: events.length, + sources: sourcesTouched.size, + revisions: revisionsTouched.size, + chunks_deleted: chunksDeleted, + embeddings_deleted: embeddingsDeleted, + vector_entries_deleted: vectorEntriesDeleted + }, + created_at: now + }); + return { + path: options.input, + db_path: options.dbPath, + run_id: runId, + events_seen: events.length, + sources_touched: sourcesTouched.size, + revisions_touched: revisionsTouched.size, + chunks_deleted: chunksDeleted, + embeddings_deleted: embeddingsDeleted, + vector_entries_deleted: vectorEntriesDeleted, + stale_revisions: staleRevisions, + deleted_sources: deletedSources, + moved_sources: movedSources, + permission_updates: permissionUpdates + }; + })(); + } finally { + db.close(); } - return normalized; } -function rowHash(row, artifactUriToKey = new Map) { - return hashValue(normalizeRowForHash(row, artifactUriToKey)); + +// src/machines.ts +import { spawnSync } from "child_process"; +import { hostname as hostname4, platform, userInfo } from "os"; +var KNOWLEDGE_MACHINES_ADAPTER_CONTRACT_VERSION = 1; +var KNOWLEDGE_MACHINES_ADAPTER_PACKAGE = "@hasna/machines"; +var KNOWLEDGE_MACHINES_ADAPTER_ENTRYPOINT = "@hasna/machines/consumer"; +function asString3(value) { + return typeof value === "string" && value.length > 0 ? value : null; } -function tableRows(db, table) { - if (!tableExists2(db, table)) - return []; - return db.query(`SELECT * FROM ${quoteIdent(table)} ORDER BY rowid ASC`).all(); +function asStringArray(value) { + return Array.isArray(value) ? value.filter((item) => typeof item === "string") : []; } -function tableContentHash(table, rows, artifactUriToKey = new Map) { - return hashValue(rows.map((row) => ({ - key: rowKey(table, row), - hash: rowHash(row, artifactUriToKey) - })).sort((a, b) => a.key.localeCompare(b.key))); +function asRecord(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : {}; } -function tableClock(db, table, machineId) { - return db.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get(table, machineId) ?? null; +function asBooleanOrNull(value) { + return typeof value === "boolean" ? value : null; } -function listTableClocks(db) { - if (!tableExists2(db, "knowledge_sync_table_clocks")) - return []; - return db.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all(); +function asNumberOrNull(value) { + return typeof value === "number" && Number.isFinite(value) ? value : null; } -function updateTableClock(db, input) { - const now = input.now ?? nowIso(); - const existing = tableClock(db, input.table, input.machineId); - const createdAt = existing?.created_at ?? now; - db.query(` - INSERT INTO knowledge_sync_table_clocks ( - table_name, machine_id, logical_clock, high_water_hash, high_water_bundle_id, - origin_machine_id, updated_by_machine_id, last_applied_at, metadata_json, - created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(table_name, machine_id) DO UPDATE SET - logical_clock = excluded.logical_clock, - high_water_hash = excluded.high_water_hash, - high_water_bundle_id = excluded.high_water_bundle_id, - origin_machine_id = excluded.origin_machine_id, - updated_by_machine_id = excluded.updated_by_machine_id, - last_applied_at = excluded.last_applied_at, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at - `).run(input.table, input.machineId, input.logicalClock, input.highWaterHash, input.highWaterBundleId ?? null, input.originMachineId ?? input.machineId, input.updatedByMachineId ?? input.machineId, input.lastAppliedAt ?? now, JSON.stringify(input.metadata ?? {}), createdAt, now); - const row = tableClock(db, input.table, input.machineId); - if (!row) - throw new Error(`Failed to record sync clock for ${input.table}:${input.machineId}`); - return row; +function normalizePlatform(value = platform()) { + const normalized = value.toLowerCase(); + if (normalized === "darwin" || normalized === "macos") + return "macos"; + if (normalized === "win32" || normalized === "windows") + return "windows"; + if (normalized === "linux") + return "linux"; + return value; } -function prepareExportTableClock(db, input) { - const existing = tableClock(db, input.table, input.machineId); - const logicalClock = existing?.high_water_hash === input.highWaterHash ? existing.logical_clock : (existing?.logical_clock ?? 0) + 1; - const row = input.record ? updateTableClock(db, { - table: input.table, - machineId: input.machineId, - logicalClock, - highWaterHash: input.highWaterHash, - highWaterBundleId: null, - originMachineId: existing?.origin_machine_id ?? input.machineId, - updatedByMachineId: input.machineId, - lastAppliedAt: input.now, - metadata: { - source: "export", - row_count: input.rowCount - }, - now: input.now - }) : { - table_name: input.table, - machine_id: input.machineId, - logical_clock: logicalClock, - high_water_hash: input.highWaterHash, - high_water_bundle_id: existing?.high_water_bundle_id ?? null, - origin_machine_id: existing?.origin_machine_id ?? input.machineId, - updated_by_machine_id: input.machineId, - last_applied_at: input.now, - metadata_json: "{}", - created_at: existing?.created_at ?? input.now, - updated_at: input.now - }; +function defaultRunner(command) { + const result = spawnSync("bash", ["-c", command], { + encoding: "utf8", + env: process.env + }); return { - table: input.table, - machine_id: input.machineId, - logical_clock: row.logical_clock, - high_water_hash: input.highWaterHash, - high_water_bundle_id: row.high_water_bundle_id, - row_count: input.rowCount, - updated_at: row.updated_at + stdout: result.stdout || "", + stderr: result.stderr || "", + exitCode: result.status ?? 1 }; } -function finalizeExportTableClock(db, clock, bundleId, record, now) { - clock.high_water_bundle_id = bundleId; - if (!record) - return; - updateTableClock(db, { - table: clock.table, - machineId: clock.machine_id, - logicalClock: clock.logical_clock, - highWaterHash: clock.high_water_hash, - highWaterBundleId: bundleId, - originMachineId: clock.machine_id, - updatedByMachineId: clock.machine_id, - lastAppliedAt: now, - metadata: { - source: "export", - row_count: clock.row_count - }, - now - }); -} -function bundleTableClock(bundle, table) { - return bundle.table_clocks?.find((clock) => clock.table === table) ?? null; -} -function staleIncomingClock(existing, incoming) { - if (!existing || !incoming) - return false; - return incoming.logical_clock < existing.logical_clock; +async function runCommand(runner, command) { + return await runner(command); } -function upsertSqliteRows(db, table, rows) { - if (rows.length === 0) - return 0; - const columns = filterLocalColumns(db, table, Object.keys(rows[0])); - if (columns.length === 0) - return 0; - const primaryKeys = PRIMARY_KEYS[table]; - const columnList = columns.map(quoteIdent).join(", "); - const placeholders2 = columns.map(() => "?").join(", "); - const keyList = primaryKeys.map(quoteIdent).join(", "); - const updateColumns = columns.filter((column) => !primaryKeys.includes(column)); - const fallbackKey = primaryKeys[0]; - const setClause = updateColumns.length > 0 ? updateColumns.map((column) => `${quoteIdent(column)} = excluded.${quoteIdent(column)}`).join(", ") : `${quoteIdent(fallbackKey)} = excluded.${quoteIdent(fallbackKey)}`; - const statement = db.query(`INSERT INTO ${quoteIdent(table)} (${columnList}) VALUES (${placeholders2}) - ON CONFLICT (${keyList}) DO UPDATE SET ${setClause}`); - const insert = db.transaction((batch) => { - for (const row of batch) - statement.run(...columns.map((column) => coerceForSqlite(row[column]))); - }); - insert(rows); - return rows.length; +async function hasCommand(command, runner) { + const result = await runCommand(runner, `command -v ${command} >/dev/null 2>&1`); + return result.exitCode === 0; } -function parseRowKeyValues(table, key) { - const primaryKeys = PRIMARY_KEYS[table]; - const values = []; - let rest = key; - for (let index = 0;index < primaryKeys.length; index += 1) { - const primaryKey = primaryKeys[index]; - const prefix = `${primaryKey}=`; - if (!rest.startsWith(prefix)) - return null; - const remaining = rest.slice(prefix.length); - const nextPrimaryKey = primaryKeys[index + 1]; - const marker = nextPrimaryKey ? `&${nextPrimaryKey}=` : null; - const markerIndex = marker ? remaining.indexOf(marker) : -1; - const encoded = markerIndex >= 0 ? remaining.slice(0, markerIndex) : remaining; - try { - values.push(JSON.parse(encoded)); - } catch { +function parseTailscaleStatus(raw) { + try { + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== "object") return null; - } - rest = markerIndex >= 0 && marker ? remaining.slice(markerIndex + 1) : ""; + return parsed; + } catch { + return null; } - return rest.length === 0 ? values : null; -} -function primaryKeyWhereClause(table) { - return PRIMARY_KEYS[table].map((key) => `${quoteIdent(key)} = ?`).join(" AND "); -} -function latestImportedRowHashes(db, table, sourceMachineId) { - if (!tableExists2(db, "knowledge_sync_changes")) - return new Map; - const rows = db.query(`SELECT entity_id, next_hash - FROM knowledge_sync_changes - WHERE origin_machine_id = ? AND entity_kind = ? - ORDER BY created_at ASC, id ASC`).all(sourceMachineId, table); - const latest = new Map; - for (const row of rows) - latest.set(row.entity_id, row.next_hash); - return latest; -} -function removeChunkDerivedRows(db, chunkId) { - if (tableExists2(db, "chunks_fts")) - db.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(chunkId); - if (tableExists2(db, "chunk_embeddings")) - db.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run(chunkId); - if (tableExists2(db, "vector_index_entries")) - db.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run(chunkId); - if (tableExists2(db, "citations")) - db.query("DELETE FROM citations WHERE chunk_id = ?").run(chunkId); } -function deleteSqliteRowByKey(db, table, key) { - const values = parseRowKeyValues(table, key); - if (!values) - return false; - const where = primaryKeyWhereClause(table); - const existing = db.query(`SELECT * FROM ${quoteIdent(table)} WHERE ${where} LIMIT 1`).get(...values); - if (!existing) - return false; - if (table === "chunks" && typeof existing.id === "string") - removeChunkDerivedRows(db, existing.id); - db.query(`DELETE FROM ${quoteIdent(table)} WHERE ${where}`).run(...values); - return true; +function peerKey(peer) { + if (!peer) + return null; + return peer.HostName ?? peer.DNSName?.split(".")[0] ?? null; } -function refreshChunkFtsRows(db, rows) { - if (!tableExists2(db, "chunks_fts")) - return; - for (const row of rows) { - const chunkId = typeof row.id === "string" ? row.id : null; - const text = typeof row.text === "string" ? row.text : null; - if (!chunkId || text === null) - continue; - let title = ""; - let sourceUri = ""; - const sourceRevisionId = typeof row.source_revision_id === "string" ? row.source_revision_id : null; - if (sourceRevisionId) { - const source = db.query(`SELECT s.title, s.uri - FROM source_revisions sr - JOIN sources s ON s.id = sr.source_id - WHERE sr.id = ? - LIMIT 1`).get(sourceRevisionId); - title = source?.title ?? ""; - sourceUri = source?.uri ?? ""; - } - if (!sourceUri && typeof row.metadata_json === "string") { - const metadata = parseJson(row.metadata_json, {}); - sourceUri = typeof metadata.source_uri === "string" ? metadata.source_uri : ""; - } - db.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(chunkId); - db.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(chunkId, text, title, sourceUri); +async function loadTailscalePeers(runner, warnings) { + const peers = new Map; + if (!await hasCommand("tailscale", runner)) { + warnings.push("tailscale_not_available"); + return { peers, selfKey: null }; } + const result = await runCommand(runner, "tailscale status --json"); + if (result.exitCode !== 0) { + warnings.push(`tailscale_status_failed:${result.stderr.trim() || result.exitCode}`); + return { peers, selfKey: null }; + } + const status = parseTailscaleStatus(result.stdout); + if (!status) { + warnings.push("tailscale_status_invalid_json"); + return { peers, selfKey: null }; + } + const addPeer = (peer) => { + const key = peerKey(peer); + if (key && peer) + peers.set(key, peer); + }; + addPeer(status.Self); + for (const peer of Object.values(status.Peer ?? {})) + addPeer(peer); + return { peers, selfKey: peerKey(status.Self) }; } -function refreshDerivedRowsForImport(db, table, rows) { - if (table === "chunks") - refreshChunkFtsRows(db, rows); -} -function assertInside2(root, target) { - const rel = relative3(root, target); - return rel !== ".." && !rel.startsWith("..") && !rel.startsWith(`..${sep3}`); +function localMachineId(fallback) { + return process.env.HASNA_MACHINE_ID ?? process.env.OPEN_MACHINES_MACHINE_ID ?? process.env.MACHINE_ID ?? fallback ?? hostname4(); } -function keyForArtifactRow(row, artifactsDir) { - const metadata = parseJson(row.metadata_json, {}); - if (typeof metadata.key === "string") - return metadata.key; - if (!row.artifact_uri.startsWith("file://")) - return null; - try { - const path = fileURLToPath2(row.artifact_uri); - const root = resolve3(artifactsDir); - const target = resolve3(path); - if (!assertInside2(root, target)) - return null; - const rel = relative3(root, target).replace(/\\/g, "/"); - return rel ? normalizeArtifactKey(rel) : null; - } catch { - return null; - } +function buildLocalEntry(input) { + const local = input.machineId === input.localMachineId || input.machineId === hostname4(); + const dnsName = input.peer?.DNSName?.replace(/\.$/, "") ?? null; + const tailscaleTarget = dnsName ?? input.peer?.TailscaleIPs?.[0] ?? null; + const hints = []; + if (local) + hints.push({ kind: "local", target: "localhost", reachable: true }); + if (tailscaleTarget) + hints.push({ kind: "tailscale", target: tailscaleTarget, reachable: input.peer?.Online ?? null }); + const selectedRoute = hints.find((hint) => hint.kind === "local") ?? hints.find((hint) => hint.kind === "tailscale") ?? null; + return { + machine_id: input.machineId, + hostname: input.peer?.HostName ?? (local ? hostname4() : input.machineId), + local, + platform: input.peer?.OS ? normalizePlatform(input.peer.OS) : local ? normalizePlatform() : null, + os: input.peer?.OS ?? (local ? platform() : null), + user: local ? userInfo().username : null, + workspace_path: null, + manifest_declared: false, + heartbeat_status: "unknown", + last_heartbeat_at: null, + tailscale: { + dns_name: dnsName, + ips: input.peer?.TailscaleIPs ?? [], + online: input.peer?.Online ?? null, + active: input.peer?.Active ?? null, + last_seen: input.peer?.LastSeen ?? null + }, + ssh: { + address: null, + route: selectedRoute?.kind === "local" ? "local" : selectedRoute?.kind === "tailscale" ? "tailscale" : "unknown", + command_target: selectedRoute?.target ?? null + }, + route_hints: hints, + tags: [], + metadata: {}, + source: "local" + }; } -var TEXT_ARTIFACT_EXTENSIONS = new Set([".csv", ".html", ".json", ".jsonl", ".log", ".md", ".txt", ".xml", ".yaml", ".yml"]); -function isTextArtifact(contentType, key) { - const normalized = contentType?.toLowerCase() ?? ""; - if (normalized.startsWith("text/")) - return true; - if (/(json|markdown|xml|yaml|csv)/.test(normalized)) - return true; - return key ? TEXT_ARTIFACT_EXTENSIONS.has(extname(key).toLowerCase()) : false; +function normalizeRouteHints(value) { + if (!Array.isArray(value)) + return []; + return value.map((entry) => { + const record2 = asRecord(entry); + const kind = asString3(record2.kind) ?? "unknown"; + const routeKind = kind === "local" || kind === "lan" || kind === "tailscale" || kind === "ssh" ? kind : "unknown"; + return { + kind: routeKind, + target: asString3(record2.target) ?? "", + reachable: asBooleanOrNull(record2.reachable) + }; + }).filter((entry) => entry.target.length > 0); } -function artifactUriToKey(artifacts) { - const map = new Map; - for (const artifact of artifacts) { - if (artifact.key) - map.set(artifact.artifact_uri, artifact.key); - } - return map; +function normalizeOpenMachinesEntry(entry, localMachineId2) { + const machineId = asString3(entry.machine_id) ?? asString3(entry.hostname) ?? "unknown"; + const tailscale = asRecord(entry.tailscale); + const ssh = asRecord(entry.ssh); + const heartbeatStatus = asString3(entry.heartbeat_status); + const route = asString3(ssh.route); + return { + machine_id: machineId, + hostname: asString3(entry.hostname), + local: machineId === localMachineId2, + platform: asString3(entry.platform), + os: asString3(entry.os), + user: asString3(entry.user), + workspace_path: asString3(entry.workspace_path), + manifest_declared: entry.manifest_declared === true, + heartbeat_status: heartbeatStatus === "online" || heartbeatStatus === "offline" ? heartbeatStatus : "unknown", + last_heartbeat_at: asString3(entry.last_heartbeat_at), + tailscale: { + dns_name: asString3(tailscale.dns_name), + ips: asStringArray(tailscale.ips), + online: asBooleanOrNull(tailscale.online), + active: asBooleanOrNull(tailscale.active), + last_seen: asString3(tailscale.last_seen) + }, + ssh: { + address: asString3(ssh.address), + route: route === "local" || route === "lan" || route === "tailscale" ? route : "unknown", + command_target: asString3(ssh.command_target) + }, + route_hints: normalizeRouteHints(entry.route_hints), + tags: asStringArray(entry.tags), + metadata: asRecord(entry.metadata), + source: "open-machines" + }; } -function artifactFingerprint(artifact) { - return hashValue({ - key: artifact.key, - kind: artifact.kind, - hash: artifact.hash, - size_bytes: artifact.size_bytes - }); +function topologyMessage(source, count3) { + return `${count3} machine${count3 === 1 ? "" : "s"} discovered via ${source}`; } -function artifactIdentity(artifact) { - return artifact.key ?? artifact.artifact_uri; +function optionalModuleError(error51) { + const message = error51 instanceof Error ? error51.message : String(error51); + return message.includes("Cannot find module '@hasna/machines'") || message.includes("Cannot find module '@hasna/machines/consumer'") ? "module_not_found" : message; } -function canReferenceExistingS3Artifact(artifact, targetStorage) { - return artifact.artifact_uri.startsWith("s3://") && targetStorage.artifact_store.type === "s3" && artifact.artifact_uri.startsWith(targetStorage.artifact_store.uri_prefix); +function adapterMode(options) { + return options.adapterMode ?? "auto"; } -function tableCounts(db) { - return Object.fromEntries(KNOWLEDGE_SYNC_TABLES.map((table) => [table, tableExists2(db, table) ? count2(db, table) : 0])); +function contractVersion(mod) { + const fromContract = mod?.MACHINES_CONSUMER_CONTRACT?.schema_version; + if (typeof fromContract === "number") + return fromContract; + const direct = mod?.MACHINES_CONSUMER_CONTRACT_VERSION; + return typeof direct === "number" ? direct : null; } -function artifactHashes(db) { - return db.query(`SELECT artifact_uri, kind, hash, size_bytes - FROM storage_objects - ORDER BY artifact_uri ASC`).all(); +function payloadContractVersion(value) { + return typeof value.schema_version === "number" ? value.schema_version : null; } -function machineFromTopologyEntry(entry, now) { +function unsupportedContractVersion(version2) { + return typeof version2 === "number" && version2 > KNOWLEDGE_MACHINES_ADAPTER_CONTRACT_VERSION ? version2 : null; +} +function adapterStatus(input) { return { - machine_id: entry.machine_id, - hostname: entry.hostname, - platform: entry.platform, - user_label: entry.user, - workspace_home: entry.workspace_path, - tailscale_dns: entry.tailscale.dns_name, - tailscale_ips_json: JSON.stringify(entry.tailscale.ips), - ssh_target: entry.ssh.command_target, - last_seen_at: entry.local || entry.tailscale.online === true || entry.heartbeat_status === "online" ? now : entry.last_heartbeat_at, - capabilities_json: JSON.stringify({ - route_hints: entry.route_hints, - heartbeat_status: entry.heartbeat_status, - manifest_declared: entry.manifest_declared - }), - metadata_json: JSON.stringify({ - ...entry.metadata, - source: entry.source, - tags: entry.tags, - tailscale: entry.tailscale, - ssh: entry.ssh - }), - created_at: now, - updated_at: now + package: KNOWLEDGE_MACHINES_ADAPTER_PACKAGE, + entrypoint: KNOWLEDGE_MACHINES_ADAPTER_ENTRYPOINT, + mode: input.mode, + implementation: input.implementation, + contract_version: input.contractVersion ?? null, + available: input.available, + error: input.error ?? null }; } -function parseJsonRecord(value) { - if (!value) - return {}; - try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; - } +function disabledAdapterStatus(mode2, error51 = "adapter_disabled") { + return adapterStatus({ + mode: mode2, + implementation: "disabled", + available: false, + error: error51 + }); } -function parseJsonArray(value) { - if (!value) - return []; - try { - const parsed = JSON.parse(value); - return Array.isArray(parsed) ? parsed : []; - } catch { - return []; - } +function unsupportedContractAdapterStatus(mode2, mod) { + const version2 = unsupportedContractVersion(contractVersion(mod)); + if (!version2) + return null; + return adapterStatus({ + mode: mode2, + implementation: "disabled", + available: false, + error: `unsupported_contract_version:${version2}`, + contractVersion: version2 + }); } -function recordFromUnknown(value) { - return value && typeof value === "object" && !Array.isArray(value) ? value : {}; +function cliAdapterStatus(mode2) { + return adapterStatus({ + mode: mode2, + implementation: "cli", + available: true + }); } -function compactRecord(input) { - return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)); +function sdkAdapterStatus(mode2, mod) { + return adapterStatus({ + mode: mode2, + implementation: "sdk", + available: true, + contractVersion: contractVersion(mod) + }); } -function canonicalJson(value) { - if (Array.isArray(value)) - return `[${value.map(canonicalJson).join(",")}]`; - if (value && typeof value === "object") { - return `{${Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; +function parseJson2(value) { + try { + return JSON.parse(value); + } catch { + return null; } - return JSON.stringify(value); -} -function stableResolverEvidence(value) { - const { recorded_at: _recordedAt, ...stable } = value; - return stable; -} -function stringFromUnknown(value) { - return typeof value === "string" && value.length > 0 ? value : null; } -function numberFromUnknown(value) { - return typeof value === "number" && Number.isFinite(value) ? value : null; +function shellQuote(value) { + return `'${value.replace(/'/g, "'\\''")}'`; } -function booleanFromUnknown(value) { - return typeof value === "boolean" ? value : null; +function machinesCliCommand(args) { + return ["machines", ...args].map(shellQuote).join(" "); } -function stringArrayFromUnknown(value) { - return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : []; +function preflightTargetIsLocal(machineId) { + return machineId === "local" || machineId === "localhost" || machineId === hostname4() || machineId === process.env.HASNA_MACHINE_ID || machineId === process.env.OPEN_MACHINES_MACHINE_ID || machineId === process.env.MACHINE_ID; } -function cacheabilityFromUnknown(value) { - const raw = recordFromUnknown(value); - const observedAt = stringFromUnknown(raw.observed_at); - const sourceAuthority = stringFromUnknown(raw.source_authority); - if (!observedAt || !sourceAuthority) - return null; +function defaultPreflightRunner(machineId, command) { + const local = preflightTargetIsLocal(machineId); + const shellCommand = local ? command : `ssh ${shellQuote(machineId)} ${shellQuote(command)}`; + const result = spawnSync("bash", ["-c", shellCommand], { + encoding: "utf8", + env: process.env + }); return { - observed_at: observedAt, - verified_at: stringFromUnknown(raw.verified_at), - expires_at: stringFromUnknown(raw.expires_at), - ttl_ms: numberFromUnknown(raw.ttl_ms), - source_authority: sourceAuthority, - confidence: stringFromUnknown(raw.confidence), - cacheable: raw.cacheable === true, - stale: raw.stale === true, - reasons: stringArrayFromUnknown(raw.reasons) + stdout: result.stdout || "", + stderr: result.stderr || "", + exitCode: result.status ?? 1, + source: local ? "local" : "ssh" }; } -function cacheabilityIsFresh(cacheability, now) { - if (!cacheability || cacheability.stale) - return false; - if (!cacheability.expires_at) - return true; - const expires = Date.parse(cacheability.expires_at); - const observed = Date.parse(now); - return Number.isNaN(expires) || Number.isNaN(observed) || expires > observed; -} -function routeMatchesResolverEvidence(route, previous) { - return stringFromUnknown(previous.source) === route.source && stringFromUnknown(previous.target) === route.target && stringFromUnknown(previous.route) === route.route && stringFromUnknown(previous.target_kind) === route.targetKind && stringFromUnknown(previous.confidence) === route.confidence; +async function runPreflightCommand(runner, machineId, command) { + return await runner(machineId, command); } -function workspaceMatchesResolverEvidence(workspace, previous) { - return stringFromUnknown(previous.source) === workspace.source && stringFromUnknown(previous.requested_machine_id) === workspace.requested_machine_id && stringFromUnknown(previous.machine_id) === workspace.machine_id && stringFromUnknown(previous.project_id) === workspace.project_id && stringFromUnknown(previous.repo_name) === workspace.repo_name && stringFromUnknown(previous.project_root) === workspace.project_root && stringFromUnknown(previous.project_root_source) === workspace.project_root_source && stringFromUnknown(previous.workspace_root) === workspace.workspace_root && stringFromUnknown(previous.workspace_root_source) === workspace.workspace_root_source && stringFromUnknown(previous.open_files_root) === workspace.open_files_root && stringFromUnknown(previous.open_files_root_source) === workspace.open_files_root_source && stringFromUnknown(previous.trust_status) === workspace.trust_status && stringFromUnknown(previous.auth_status) === workspace.auth_status && booleanFromUnknown(previous.current) === workspace.current && booleanFromUnknown(previous.primary) === workspace.primary; +function preflightStatus(required2, ok) { + if (ok) + return "ok"; + return required2 === false ? "warn" : "fail"; } -function routeWithStableCacheability(route, previous, now) { - if (!route) - return null; - const previousCacheability = cacheabilityFromUnknown(previous.cacheability); - if (previousCacheability && cacheabilityIsFresh(previousCacheability, now) && routeMatchesResolverEvidence(route, previous)) { - return { ...route, cacheability: previousCacheability }; - } - return route; +function preflightId(value) { + return value.replace(/[^a-zA-Z0-9_.@/-]+/g, "-").replace(/^-+|-+$/g, ""); } -function workspaceWithStableCacheability(workspace, previous, now) { - if (!workspace) - return null; - const previousCacheability = cacheabilityFromUnknown(previous.cacheability); - if (previousCacheability && cacheabilityIsFresh(previousCacheability, now) && workspaceMatchesResolverEvidence(workspace, previous)) { - return { ...workspace, cacheability: previousCacheability }; - } - return workspace; +function packageCommand(name) { + if (name === "@hasna/knowledge") + return "knowledge"; + if (name === "@hasna/machines") + return "machines"; + return name.split("/").pop() ?? name; } -function resolverMachineId(input) { - return input.workspace?.machine_id ?? input.workspace?.requested_machine_id ?? input.machineId ?? input.route?.target ?? hostname(); +function firstLine(value) { + return value.trim().split(/\r?\n/).find(Boolean) ?? ""; } -function resolverSources(input, existing) { - const sources = new Set; - const existingSources = Array.isArray(existing.sources) ? existing.sources : []; - for (const source of existingSources) - if (typeof source === "string") - sources.add(source); - if (typeof existing.source === "string") - sources.add(existing.source); - if (input.route?.source) - sources.add(input.route.source); - if (input.workspace?.source) - sources.add(input.workspace.source); - sources.add("knowledge"); - return [...sources].sort(); +function extractVersion(value) { + const match = value.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/); + return match?.[0] ?? null; } -function resolverTailscaleDns(existing, route) { - if (route?.target && (route.route === "tailscale" || route.targetKind === "tailscale")) - return route.target; - return existing?.tailscale_dns ?? null; +function parseKeyValue(stdout) { + const result = {}; + for (const line of stdout.split(/\r?\n/)) { + const idx = line.indexOf("="); + if (idx <= 0) + continue; + result[line.slice(0, idx)] = line.slice(idx + 1); + } + return result; } -function resolverEvidenceMetadata(input, existing, now) { - const previous = recordFromUnknown(existing.resolver_evidence); - const route = input.route ? compactRecord({ - source: input.route.source, - target: input.route.target, - route: input.route.route, - target_kind: input.route.targetKind, - confidence: input.route.confidence, - adapter: input.route.adapter, - evidence: input.route.evidence, - cacheability: input.route.cacheability, - warnings: input.route.warnings - }) : recordFromUnknown(previous.route); - const workspace = input.workspace ? compactRecord({ - source: input.workspace.source, - requested_machine_id: input.workspace.requested_machine_id, - machine_id: input.workspace.machine_id, - project_id: input.workspace.project_id, - repo_name: input.workspace.repo_name, - project_root: input.workspace.project_root, - project_root_source: input.workspace.project_root_source, - workspace_root: input.workspace.workspace_root, - workspace_root_source: input.workspace.workspace_root_source, - open_files_root: input.workspace.open_files_root, - open_files_root_source: input.workspace.open_files_root_source, - trust_status: input.workspace.trust_status, - auth_status: input.workspace.auth_status, - current: input.workspace.current, - primary: input.workspace.primary, - diagnostics: input.workspace.diagnostics, - repair_hints: input.workspace.repair_hints, - evidence: input.workspace.evidence, - cacheability: input.workspace.cacheability, - warnings: input.workspace.warnings - }) : recordFromUnknown(previous.workspace); - return compactRecord({ - ...previous, - recorded_at: now, - route, - workspace - }); +function makePreflightCheck(input) { + return { + id: input.id, + kind: input.kind, + status: input.status, + target: input.target, + expected: input.expected ?? null, + actual: input.actual ?? null, + detail: input.detail, + source: input.source + }; } -function recordKnowledgeMachineResolverEvidence(dbPath, input) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - try { - const machineId = resolverMachineId(input); - const existing = db.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(machineId) ?? null; - const now = nowIso(input.now); - const capabilities = parseJsonRecord(existing?.capabilities_json); - const metadata = parseJsonRecord(existing?.metadata_json); - const resolverCapabilities = recordFromUnknown(capabilities.resolver); - const previousResolverEvidence = recordFromUnknown(metadata.resolver_evidence); - const previousRouteEvidence = recordFromUnknown(previousResolverEvidence.route); - const previousWorkspaceEvidence = recordFromUnknown(previousResolverEvidence.workspace); - const route = routeWithStableCacheability(input.route?.source === "registry" ? null : input.route ?? null, previousRouteEvidence, now); - const workspace = workspaceWithStableCacheability(input.workspace?.source === "registry" ? null : input.workspace ?? null, previousWorkspaceEvidence, now); - const stableInput = { ...input, route, workspace }; - const nextCapabilities = { - ...capabilities, - resolver: compactRecord({ - ...resolverCapabilities, - route_source: route?.source ?? resolverCapabilities.route_source, - route_kind: route?.route ?? resolverCapabilities.route_kind, - route_target_kind: route?.targetKind ?? resolverCapabilities.route_target_kind, - route_confidence: route?.confidence ?? resolverCapabilities.route_confidence, - route_cacheable: route?.cacheability?.cacheable ?? resolverCapabilities.route_cacheable, - route_stale: route?.cacheability?.stale ?? resolverCapabilities.route_stale, - route_expires_at: route?.cacheability?.expires_at ?? resolverCapabilities.route_expires_at, - route_observed_at: route?.cacheability?.observed_at ?? resolverCapabilities.route_observed_at, - route_source_authority: route?.cacheability?.source_authority ?? resolverCapabilities.route_source_authority, - workspace_source: workspace?.source ?? resolverCapabilities.workspace_source, - project_root_source: workspace?.project_root_source ?? resolverCapabilities.project_root_source, - workspace_root_source: workspace?.workspace_root_source ?? resolverCapabilities.workspace_root_source, - open_files_root_source: workspace?.open_files_root_source ?? resolverCapabilities.open_files_root_source, - trust_status: workspace?.trust_status ?? resolverCapabilities.trust_status, - auth_status: workspace?.auth_status ?? resolverCapabilities.auth_status, - workspace_cacheable: workspace?.cacheability?.cacheable ?? resolverCapabilities.workspace_cacheable, - workspace_stale: workspace?.cacheability?.stale ?? resolverCapabilities.workspace_stale, - workspace_expires_at: workspace?.cacheability?.expires_at ?? resolverCapabilities.workspace_expires_at, - workspace_observed_at: workspace?.cacheability?.observed_at ?? resolverCapabilities.workspace_observed_at, - workspace_source_authority: workspace?.cacheability?.source_authority ?? resolverCapabilities.workspace_source_authority - }), - route_fallback: Boolean(route?.target ?? existing?.ssh_target), - workspace_fallback: Boolean(workspace?.project_root ?? existing?.workspace_home) - }; - const nextResolverEvidence = resolverEvidenceMetadata(stableInput, metadata, now); - if (existing) { - const existingResolverEvidence = previousResolverEvidence; - const unchanged = existing.workspace_home === (workspace?.project_root ?? existing.workspace_home ?? null) && existing.tailscale_dns === resolverTailscaleDns(existing, route) && existing.ssh_target === (route?.target ?? existing.ssh_target ?? null) && canonicalJson(parseJsonRecord(existing.capabilities_json)) === canonicalJson(nextCapabilities) && canonicalJson(stableResolverEvidence(existingResolverEvidence)) === canonicalJson(stableResolverEvidence(nextResolverEvidence)); - if (unchanged) - return existing; - } - const row = { - machine_id: machineId, - hostname: existing?.hostname ?? null, - platform: existing?.platform ?? null, - user_label: existing?.user_label ?? null, - workspace_home: workspace?.project_root ?? existing?.workspace_home ?? null, - tailscale_dns: resolverTailscaleDns(existing, route), - tailscale_ips_json: JSON.stringify(parseJsonArray(existing?.tailscale_ips_json)), - ssh_target: route?.target ?? existing?.ssh_target ?? null, - last_seen_at: now, - capabilities_json: JSON.stringify(nextCapabilities), - metadata_json: JSON.stringify({ - ...metadata, - source: "knowledge", - sources: resolverSources(stableInput, metadata), - resolver_evidence: nextResolverEvidence - }), - created_at: existing?.created_at ?? now, - updated_at: now - }; - upsertKnowledgeMachine(db, row); - return row; - } finally { - db.close(); - } +async function inspectPreflightCommand(machineId, spec, runner) { + const script = [ + `cmd=${shellQuote(spec.command)}`, + 'path="$(command -v "$cmd" 2>/dev/null || true)"', + 'printf "path=%s\\n" "$path"', + `if [ -n "$path" ]; then version="$("$cmd" ${spec.versionArgs ?? "--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi` + ].join("; "); + const result = await runPreflightCommand(runner, machineId, script); + const parsed = parseKeyValue(result.stdout); + return { + path: parsed.path || null, + version: parsed.version ? firstLine(parsed.version) : null, + stderr: result.stderr, + source: result.source ?? (preflightTargetIsLocal(machineId) ? "local" : "ssh") + }; } -function upsertKnowledgeMachine(db, input) { - db.query(` - INSERT INTO knowledge_machines ( - machine_id, hostname, platform, user_label, workspace_home, tailscale_dns, - tailscale_ips_json, ssh_target, last_seen_at, capabilities_json, - metadata_json, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(machine_id) DO UPDATE SET - hostname = excluded.hostname, - platform = excluded.platform, - user_label = excluded.user_label, - workspace_home = excluded.workspace_home, - tailscale_dns = excluded.tailscale_dns, - tailscale_ips_json = excluded.tailscale_ips_json, - ssh_target = excluded.ssh_target, - last_seen_at = excluded.last_seen_at, - capabilities_json = excluded.capabilities_json, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at - `).run(input.machine_id, input.hostname, input.platform, input.user_label, input.workspace_home, input.tailscale_dns, input.tailscale_ips_json, input.ssh_target, input.last_seen_at, input.capabilities_json, input.metadata_json, input.created_at, input.updated_at); +function jsonFieldCommand(field) { + const regex = field === "name" ? String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p` : String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`; + return [ + `if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${field} ?? '')" "$pkg" 2>/dev/null`, + `elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${field} || '')" "$pkg" 2>/dev/null`, + `else sed -n '${regex}' "$pkg" | head -n 1`, + "fi" + ].join("; "); } -function refreshMachineRegistryFromTopology(db, topology, now = nowIso()) { - for (const entry of topology.machines) - upsertKnowledgeMachine(db, machineFromTopologyEntry(entry, now)); - return topology.machines.length; +async function inspectPreflightWorkspace(machineId, spec, runner) { + const script = [ + `path=${shellQuote(spec.path)}`, + 'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"', + 'pkg="$path/package.json"', + 'printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"', + `if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${jsonFieldCommand("name")})"; printf "version=%s\\n" "$(${jsonFieldCommand("version")})"; fi` + ].join("; "); + const result = await runPreflightCommand(runner, machineId, script); + const parsed = parseKeyValue(result.stdout); + return { + exists: parsed.exists === "yes", + packageJson: parsed.package_json === "yes", + packageName: parsed.package_name || null, + version: parsed.version || null, + stderr: result.stderr, + source: result.source ?? (preflightTargetIsLocal(machineId) ? "local" : "ssh") + }; } -function listKnowledgeMachines(dbPath) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - try { - return db.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(); - } finally { - db.close(); +async function fallbackCommandChecks(machineId, spec, runner) { + const inspection = await inspectPreflightCommand(machineId, spec, runner); + const found = Boolean(inspection.path); + const checks3 = [ + makePreflightCheck({ + id: `command:${preflightId(spec.command)}:path`, + kind: "command", + status: preflightStatus(spec.required, found), + target: spec.command, + expected: "available", + actual: inspection.path ?? "missing", + detail: found ? `found at ${inspection.path}` : inspection.stderr || "command missing", + source: inspection.source + }) + ]; + if (spec.expectedVersion) { + const actualVersion = extractVersion(inspection.version ?? ""); + checks3.push(makePreflightCheck({ + id: `command:${preflightId(spec.command)}:version`, + kind: "command", + status: actualVersion === spec.expectedVersion ? "ok" : preflightStatus(spec.required, false), + target: spec.command, + expected: spec.expectedVersion, + actual: actualVersion ?? inspection.version ?? "missing", + detail: actualVersion ? `version output: ${inspection.version}` : "version unavailable", + source: inspection.source + })); } + return checks3; } -function createKnowledgeSyncBundle(options) { - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - const warnings = []; - const generatedAt = nowIso(options.now); - const sourceMachineId = defaultSyncMachineId(options.machineId); - const recordClocks = options.recordClocks !== false; - try { - const requestedTables = filterExistingTables(db, resolveSyncTables(options.tables)); - const artifactRows = db.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json - FROM storage_objects - ORDER BY artifact_uri ASC`).all(); - const artifacts = artifactRows.map((row) => { - const key = keyForArtifactRow(row, options.storage.local_layout.directories.artifacts); - let artifact = { ...row, key }; - if (options.includeArtifactContent !== false && key && row.artifact_uri.startsWith("file://")) { - try { - const path = fileURLToPath2(row.artifact_uri); - if (existsSync9(path)) { - if (!isTextArtifact(row.content_type, key)) { - warnings.push(`artifact_content_not_embedded_binary:${row.id}`); - } else { - const text = readFileSync10(path, "utf8"); - const redactedText = redactPrivateRefs(text); - if (redactedText !== text) - warnings.push(`artifact_content_redacted:${row.id}`); - artifact.content_base64 = Buffer.from(redactedText, "utf8").toString("base64"); - artifact.hash = sha256(redactedText); - artifact.size_bytes = Buffer.byteLength(redactedText); - } - } else { - warnings.push(`artifact_missing:${row.artifact_uri}`); - } - } catch (error) { - warnings.push(`artifact_read_failed:${row.artifact_uri}:${error instanceof Error ? error.message : String(error)}`); - } - } else if (options.includeArtifactContent !== false && row.artifact_uri.startsWith("s3://")) { - warnings.push(`artifact_content_not_embedded:${row.artifact_uri}`); - } - artifact = redactPrivateRefs(artifact); - return artifact; - }); - const sourceArtifactUriToKey = artifactUriToKey(artifacts); - const tables = requestedTables.filter((table) => !TABLE_SYNC_EXCLUDES.has(table)).map((table) => ({ - table, - primary_keys: PRIMARY_KEYS[table], - rows: tableRows(db, table).map((row) => redactPrivateRefs(row)) - })); - const tableClocks = tables.map((table) => prepareExportTableClock(db, { - table: table.table, - machineId: sourceMachineId, - highWaterHash: tableContentHash(table.table, table.rows, sourceArtifactUriToKey), - rowCount: table.rows.length, - record: recordClocks, - now: generatedAt - })); - const contentHash = sha256(stableJson({ - source: { - scope: options.scope, - workspace_home: redactPrivateRefs(options.workspaceHome), - sqlite_schema_version: getSchemaVersion(db), - machine_id: sourceMachineId, - artifact_root_uri: redactPrivateRefs(options.storage.artifact_store.uri_prefix) - }, - tables: tables.map((table) => ({ - table: table.table, - primary_keys: table.primary_keys, - rows: table.rows.map((row) => ({ - key: rowKey(table.table, row), - hash: rowHash(row, sourceArtifactUriToKey) - })).sort((a, b) => a.key.localeCompare(b.key)) - })), - table_clocks: tableClocks.map((clock) => ({ - table: clock.table, - machine_id: clock.machine_id, - logical_clock: clock.logical_clock, - high_water_hash: clock.high_water_hash, - row_count: clock.row_count - })), - artifacts: artifacts.map((artifact) => ({ - identity: artifactIdentity(artifact), - fingerprint: artifactFingerprint(artifact) - })).sort((a, b) => a.identity.localeCompare(b.identity)) +async function fallbackPackageChecks(machineId, spec, runner) { + const command = spec.command ?? packageCommand(spec.name); + const inspection = await inspectPreflightCommand(machineId, { command, expectedVersion: spec.expectedVersion, required: spec.required }, runner); + const found = Boolean(inspection.path); + const checks3 = [ + makePreflightCheck({ + id: `package:${preflightId(spec.name)}:command`, + kind: "package", + status: preflightStatus(spec.required, found), + target: spec.name, + expected: command, + actual: inspection.path ?? "missing", + detail: found ? `${command} found at ${inspection.path}` : `${command} command missing`, + source: inspection.source + }) + ]; + if (spec.expectedVersion) { + const actualVersion = extractVersion(inspection.version ?? ""); + checks3.push(makePreflightCheck({ + id: `package:${preflightId(spec.name)}:version`, + kind: "package", + status: actualVersion === spec.expectedVersion ? "ok" : preflightStatus(spec.required, false), + target: spec.name, + expected: spec.expectedVersion, + actual: actualVersion ?? inspection.version ?? "missing", + detail: actualVersion ? `version output: ${inspection.version}` : "version unavailable", + source: inspection.source })); - const bundleId = `syncbundle_${contentHash.replace("sha256:", "").slice(0, 32)}`; - for (const clock of tableClocks) - finalizeExportTableClock(db, clock, bundleId, recordClocks, generatedAt); - return { - ok: true, - format: "knowledge-sync-bundle", - version: 1, - protocol_version: KNOWLEDGE_SYNC_PROTOCOL_VERSION, - min_protocol_version: KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION, - bundle_id: bundleId, - content_hash: contentHash, - generated_at: generatedAt, - source: { - scope: options.scope, - workspace_home: redactPrivateRefs(options.workspaceHome), - sqlite_schema_version: getSchemaVersion(db), - machine_id: sourceMachineId, - artifact_root_uri: redactPrivateRefs(options.storage.artifact_store.uri_prefix) - }, - table_clocks: tableClocks, - tables, - artifacts, - warnings: redactPrivateRefs(warnings), - message: `${tables.reduce((sum, table) => sum + table.rows.length, 0)} row(s), ${artifacts.length} artifact(s) exported` - }; - } finally { - db.close(); } + return checks3; } -function validateSyncProtocol(input, label) { - const protocolVersion = typeof input.protocol_version === "number" ? input.protocol_version : null; - const minProtocolVersion = typeof input.min_protocol_version === "number" ? input.min_protocol_version : null; - if (protocolVersion === null || minProtocolVersion === null || protocolVersion < KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION || minProtocolVersion > KNOWLEDGE_SYNC_PROTOCOL_VERSION) { - throw new Error(`Unsupported ${label} protocol. Expected knowledge sync protocol v${KNOWLEDGE_SYNC_PROTOCOL_VERSION} with min v${KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION}.`); +async function fallbackWorkspaceChecks(machineId, spec, runner) { + const inspection = await inspectPreflightWorkspace(machineId, spec, runner); + const target = spec.label ?? spec.path; + const checks3 = [ + makePreflightCheck({ + id: `workspace:${preflightId(target)}:path`, + kind: "workspace", + status: preflightStatus(spec.required, inspection.exists), + target, + expected: spec.path, + actual: inspection.exists ? "exists" : "missing", + detail: inspection.exists ? `workspace exists at ${spec.path}` : inspection.stderr || `workspace missing at ${spec.path}`, + source: inspection.source + }) + ]; + if (spec.expectedPackageName) { + checks3.push(makePreflightCheck({ + id: `workspace:${preflightId(target)}:package-name`, + kind: "workspace", + status: inspection.packageName === spec.expectedPackageName ? "ok" : preflightStatus(spec.required, false), + target, + expected: spec.expectedPackageName, + actual: inspection.packageName ?? (inspection.packageJson ? "missing-name" : "missing-package-json"), + detail: inspection.packageJson ? "package.json inspected" : "package.json missing", + source: inspection.source + })); } -} -function validateBundle(bundle) { - if (!bundle || bundle.format !== "knowledge-sync-bundle" || bundle.version !== 1) { - throw new Error("Invalid knowledge sync bundle."); + if (spec.expectedVersion) { + checks3.push(makePreflightCheck({ + id: `workspace:${preflightId(target)}:version`, + kind: "workspace", + status: inspection.version === spec.expectedVersion ? "ok" : preflightStatus(spec.required, false), + target, + expected: spec.expectedVersion, + actual: inspection.version ?? (inspection.packageJson ? "missing-version" : "missing-package-json"), + detail: inspection.packageJson ? "package.json inspected" : "package.json missing", + source: inspection.source + })); } - validateSyncProtocol(bundle, "knowledge sync bundle"); -} -function getBundleTable(bundle, table) { - return bundle.tables.find((entry) => entry.table === table) ?? null; + return checks3; } -function syncBundleContentHash(bundle) { - if (typeof bundle.content_hash === "string" && bundle.content_hash.length > 0) - return bundle.content_hash; - return sha256(stableJson({ - source: bundle.source, - tables: bundle.tables.map((table) => ({ - table: table.table, - rows: table.rows.map((row) => ({ - key: rowKey(table.table, row), - hash: rowHash(row, artifactUriToKey(bundle.artifacts)) - })).sort((a, b) => a.key.localeCompare(b.key)) - })), - artifacts: bundle.artifacts.map((artifact) => ({ - identity: artifactIdentity(artifact), - fingerprint: artifactFingerprint(artifact) - })).sort((a, b) => a.identity.localeCompare(b.identity)) - })); +function withKnowledgeContext(topology, options) { + return { + ...topology, + knowledge: { + scope: options.knowledge?.scope ?? "global", + app_path: HASNA_KNOWLEDGE_APP_PATH, + workspace_home: options.knowledge?.workspace_home ?? null + }, + message: topologyMessage(topology.source, topology.machines.length) + }; } -function syncBundleId(bundle) { - if (typeof bundle.bundle_id === "string" && bundle.bundle_id.length > 0) - return bundle.bundle_id; - return `syncbundle_${syncBundleContentHash(bundle).replace("sha256:", "").slice(0, 32)}`; +async function loadOpenMachinesModule() { + try { + const specifier = "@hasna/machines/consumer"; + return await import(specifier); + } catch (error51) { + if (optionalModuleError(error51) !== "module_not_found") + throw error51; + const specifier = "@hasna/machines"; + return await import(specifier); + } } -function tableRowMap(table, rows) { - return new Map(rows.map((row) => [rowKey(table, row), row])); +function normalizeOpenMachinesTopology(value, options, adapter) { + const raw = asRecord(value); + if (unsupportedContractVersion(payloadContractVersion(raw))) + return null; + const machines = Array.isArray(raw.machines) ? raw.machines : null; + const localMachine = asString3(raw.local_machine_id); + if (!machines || !localMachine) + return null; + const topology = { + ok: true, + source: "open-machines", + generated_at: asString3(raw.generated_at) ?? (options.now ?? new Date).toISOString(), + local_machine_id: localMachine, + local_hostname: asString3(raw.local_hostname) ?? hostname4(), + current_platform: asString3(raw.current_platform) ?? normalizePlatform(), + machines: machines.map((machine) => normalizeOpenMachinesEntry(machine, localMachine)), + warnings: asStringArray(raw.warnings), + adapter + }; + return withKnowledgeContext(topology, options); } -function bundleArtifactMap(bundle) { - return new Map(bundle.artifacts.map((artifact) => [artifactIdentity(artifact), artifact])); +function normalizeRouteKind(value) { + return value === "local" || value === "lan" || value === "tailscale" || value === "ssh" || value === "unknown" ? value : null; } -async function materializeArtifacts(options) { - const targetArtifacts = bundleArtifactMap(options.targetBundle); - const uriMap = new Map; - const conflicts = []; - const result = { - source_artifacts: options.bundle.artifacts.length, - target_artifacts: options.targetBundle.artifacts.length, - copied: 0, - skipped: 0, - conflicts: 0, - missing_content: 0 +function normalizeResolverCacheability(value) { + const raw = asRecord(value); + const observedAt = asString3(raw.observed_at); + const sourceAuthority = asString3(raw.source_authority); + if (!observedAt || !sourceAuthority) + return null; + return { + observed_at: observedAt, + verified_at: asString3(raw.verified_at), + expires_at: asString3(raw.expires_at), + ttl_ms: asNumberOrNull(raw.ttl_ms), + source_authority: sourceAuthority, + confidence: asString3(raw.confidence), + cacheable: raw.cacheable === true, + stale: raw.stale === true, + reasons: asStringArray(raw.reasons) }; - for (const artifact of options.bundle.artifacts) { - const identity = artifactIdentity(artifact); - const target = targetArtifacts.get(identity); - if (target && artifactFingerprint(target) === artifactFingerprint(artifact)) { - if (target.artifact_uri) - uriMap.set(artifact.artifact_uri, target.artifact_uri); - result.skipped += 1; - continue; - } - if (target && artifactFingerprint(target) !== artifactFingerprint(artifact)) { - const conflict = { - entityKind: "storage_object", - entityId: identity, - localMachineId: options.localMachineId, - remoteMachineId: options.bundle.source.machine_id ?? "unknown", - localHash: artifactFingerprint(target), - remoteHash: artifactFingerprint(artifact), - metadata: { - direction: options.direction, - target_artifact_uri: target.artifact_uri, - source_artifact_uri: artifact.artifact_uri, - local_artifact: sanitizeConflictEvidenceValue(target), - remote_artifact: sanitizeConflictEvidenceValue(artifact) - } - }; - if (hasResolvedConflictFingerprint(options.db, conflict)) { - result.skipped += 1; - continue; - } - result.conflicts += 1; - conflicts.push(conflict); - continue; - } - const hasEmbeddedContent = Boolean(artifact.key && artifact.content_base64); - const canReferenceExistingS3 = canReferenceExistingS3Artifact(artifact, options.targetStorage); - if (!hasEmbeddedContent && !canReferenceExistingS3) { - result.missing_content += 1; - options.warnings.push(`artifact_content_missing:${artifact.artifact_uri}`); - continue; - } - if (options.dryRun) { - result.copied += 1; - continue; - } - let nextUri = artifact.artifact_uri; - if (hasEmbeddedContent && artifact.key && artifact.content_base64) { - const write = await options.targetStore.put({ - key: artifact.key, - body: Buffer.from(artifact.content_base64, "base64"), - content_type: artifact.content_type ?? undefined - }); - nextUri = write.uri; - uriMap.set(artifact.artifact_uri, nextUri); - } else if (canReferenceExistingS3) { - uriMap.set(artifact.artifact_uri, nextUri); - } - const metadata = parseJson(artifact.metadata_json, {}); - const modifiedAt = typeof metadata.artifact_modified_at === "string" ? metadata.artifact_modified_at : undefined; - const object = { - uri: nextUri, - key: artifact.key ?? metadata.key ?? artifact.artifact_uri, - kind: artifact.kind, - content_type: artifact.content_type ?? undefined, - hash: artifact.hash ?? undefined, - size_bytes: artifact.size_bytes ?? undefined, - modified_at: modifiedAt, - metadata: { - ...metadata, - synced_from_artifact_uri: artifact.artifact_uri, - synced_from_machine_id: options.bundle.source.machine_id ?? undefined - } - }; - recordStorageObjects(options.db, [object]); - result.copied += 1; - } - return { result, uriMap, conflicts }; -} -function transformImportedRow(row, artifactUriMap) { - const next = { ...row }; - if (typeof next.artifact_uri === "string" && artifactUriMap.has(next.artifact_uri)) { - next.artifact_uri = artifactUriMap.get(next.artifact_uri); - } - return next; } -function insertSyncChange(db, input) { - const now = nowIso(); - db.query(` - INSERT INTO knowledge_sync_changes ( - id, origin_machine_id, updated_by_machine_id, entity_kind, entity_id, - operation, base_hash, next_hash, source_ref, source_revision_id, - artifact_uri, logical_clock, bundle_id, metadata_json, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(makeSyncId("syncchg"), input.sourceMachineId, input.localMachineId, input.entityKind, input.entityId, input.direction, null, input.nextHash, typeof input.row?.source_ref === "string" ? input.row.source_ref : typeof input.row?.source_uri === "string" ? input.row.source_uri : null, typeof input.row?.source_revision_id === "string" ? input.row.source_revision_id : null, typeof input.row?.artifact_uri === "string" ? input.row.artifact_uri : null, input.logicalClock, input.bundleId, JSON.stringify({ source_machine_id: input.sourceMachineId, bundle_id: input.bundleId }), now); +function normalizeOpenMachinesRoute(value, adapter) { + const raw = asRecord(value); + if (unsupportedContractVersion(payloadContractVersion(raw))) + return null; + const target = asString3(raw.target) ?? asString3(raw.command_target); + if (raw.ok !== true || !target) + return null; + const evidence = typeof raw.evidence === "object" && raw.evidence !== null ? raw.evidence : null; + const selectedHint = typeof evidence?.selected_hint === "object" && evidence.selected_hint !== null ? evidence.selected_hint : null; + return { + target, + route: normalizeRouteKind(raw.route), + targetKind: normalizeRouteKind(selectedHint?.kind) ?? normalizeRouteKind(raw.source) ?? normalizeRouteKind(raw.route), + confidence: asString3(raw.confidence), + source: "open-machines", + adapter, + evidence, + cacheability: normalizeResolverCacheability(raw.cacheability), + warnings: asStringArray(raw.warnings) + }; } -function hasResolvedConflictFingerprint(db, input) { - const localHash = input.localHash ?? ""; - const remoteHash = input.remoteHash ?? ""; - const exact = db.query(` - SELECT id FROM knowledge_sync_conflicts - WHERE entity_kind = ? - AND entity_id = ? - AND local_machine_id = ? - AND remote_machine_id = ? - AND COALESCE(local_hash, '') = ? - AND COALESCE(remote_hash, '') = ? - AND status IN ('resolved', 'ignored') - AND resolved_at IS NOT NULL - LIMIT 1 - `).get(input.entityKind, input.entityId, input.localMachineId, input.remoteMachineId, localHash, remoteHash); - if (exact) - return true; - const reversed = db.query(` - SELECT id FROM knowledge_sync_conflicts - WHERE entity_kind = ? - AND entity_id = ? - AND local_machine_id = ? - AND remote_machine_id = ? - AND COALESCE(local_hash, '') = ? - AND COALESCE(remote_hash, '') = ? - AND status IN ('resolved', 'ignored') - AND resolved_at IS NOT NULL - LIMIT 1 - `).get(input.entityKind, input.entityId, input.remoteMachineId, input.localMachineId, remoteHash, localHash); - return Boolean(reversed); +function pathRecord(value) { + const raw = asRecord(value); + return { + path: asString3(raw.path), + source: asString3(raw.source) ?? "unresolved" + }; } -function insertConflict(db, input) { - const duplicate = db.query(` - SELECT id FROM knowledge_sync_conflicts - WHERE entity_kind = ? - AND entity_id = ? - AND local_machine_id = ? - AND remote_machine_id = ? - AND COALESCE(local_hash, '') = COALESCE(?, '') - AND COALESCE(remote_hash, '') = COALESCE(?, '') - AND COALESCE(base_hash, '') = COALESCE(?, '') - AND status = 'open' - LIMIT 1 - `).get(input.entityKind, input.entityId, input.localMachineId, input.remoteMachineId, input.localHash ?? null, input.remoteHash ?? null, input.baseHash ?? null); - if (duplicate) - return false; - const now = nowIso(); - db.query(` - INSERT INTO knowledge_sync_conflicts ( - id, entity_kind, entity_id, local_machine_id, remote_machine_id, - local_hash, remote_hash, base_hash, status, resolution_strategy, - proposed_patch_uri, approved_by, resolved_at, metadata_json, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(makeSyncId("syncconf"), input.entityKind, input.entityId, input.localMachineId, input.remoteMachineId, input.localHash ?? null, input.remoteHash ?? null, input.baseHash ?? null, input.status ?? "open", input.resolutionStrategy ?? null, input.proposedPatchUri ?? null, input.approvedBy ?? null, input.resolvedAt ?? null, JSON.stringify(input.metadata ?? {}), now); - return true; +function normalizeWorkspaceDiagnostics(value) { + if (!Array.isArray(value)) + return []; + return value.flatMap((entry) => { + const raw = asRecord(entry); + const id = asString3(raw.id); + const status = asString3(raw.status); + const severity = asString3(raw.severity); + const message = asString3(raw.message); + if (!id || !status || !severity || !message) + return []; + return [{ + id, + status, + severity, + message, + path: asString3(raw.path), + source: asString3(raw.source) ?? "unknown", + path_exists: asBooleanOrNull(raw.path_exists) + }]; + }); } -function getSyncImport(db, bundleId) { - return db.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get(bundleId) ?? null; +function normalizeWorkspaceRepairHints(value) { + if (!Array.isArray(value)) + return []; + return value.flatMap((entry) => { + const raw = asRecord(entry); + const id = asString3(raw.id); + const reason = asString3(raw.reason); + const command = asStringArray(raw.command); + const shellCommand = asString3(raw.shell_command); + const applyCommand = asStringArray(raw.apply_command); + const applyShellCommand = asString3(raw.apply_shell_command); + if (!id || !reason || !command.length || !shellCommand || !applyCommand.length || !applyShellCommand) + return []; + return [{ + id, + reason, + command, + shell_command: shellCommand, + apply_command: applyCommand, + apply_shell_command: applyShellCommand + }]; + }); } -function recordSyncImport(db, input) { - const now = input.now ?? nowIso(); - db.query(` - INSERT INTO knowledge_sync_imports ( - bundle_id, source_machine_id, target_machine_id, direction, status, - content_hash, table_clocks_json, tables_json, generated_at, applied_at, - metadata_json - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(bundle_id) DO UPDATE SET - status = excluded.status, - applied_at = excluded.applied_at, - metadata_json = excluded.metadata_json - `).run(input.bundleId, input.sourceMachineId, input.targetMachineId, input.direction, input.status, input.contentHash, JSON.stringify(input.bundle.table_clocks ?? []), JSON.stringify(input.tableResults), input.bundle.generated_at, now, JSON.stringify({ - conflicts: input.conflicts, - artifacts: input.artifacts, - source_workspace_home: input.bundle.source.workspace_home - })); +function fallbackWorkspaceRepairHints(input) { + const needsRepair = input.projectRootSource === "inferred" || input.openFilesRootSource === "inferred" || input.trustStatus === "untrusted" || input.authStatus === "unknown" || input.warnings.some((warning) => warning.includes("inferred") || warning.includes("untrusted") || warning.includes("unknown_auth") || warning.includes("missing")); + if (!needsRepair) + return []; + const command = [ + "machines", + "workspace", + "repair", + "--machine", + input.requestedMachineId, + "--project", + input.projectId, + "--repo", + input.repoName, + "--open-files-repo", + input.openFilesRepoName ?? "open-files", + "--json" + ]; + const applyCommand = [...command, "--apply"]; + return [{ + id: "machines_workspace_repair", + reason: "Workspace paths or trust metadata need confirmation before remote knowledge sync.", + command, + shell_command: command.map(shellQuote).join(" "), + apply_command: applyCommand, + apply_shell_command: applyCommand.map(shellQuote).join(" ") + }]; } -function replayedApplyResult(options) { +function normalizeOpenMachinesWorkspace(value, options, adapter) { + const raw = asRecord(value); + if (unsupportedContractVersion(payloadContractVersion(raw))) + return null; + const paths = asRecord(raw.paths); + const project = asRecord(raw.project); + const machine = asRecord(raw.machine); + const projectRoot = pathRecord(paths.project_root); + const workspaceRoot = pathRecord(paths.workspace_root); + const openFilesRoot = pathRecord(paths.open_files_root); + if (raw.ok !== true || !projectRoot.path) + return null; + const evidence = typeof raw.evidence === "object" && raw.evidence !== null ? raw.evidence : null; + const requestedMachineId = asString3(raw.requested_machine_id) ?? options.machineId; + const projectId = asString3(project.project_id) ?? options.projectId ?? "open-knowledge"; + const repoName = asString3(project.repo_name) ?? options.repoName ?? options.projectId ?? "open-knowledge"; + const trustStatus = asString3(machine.trust_status) ?? "unknown"; + const authStatus = asString3(machine.auth_status) ?? "unknown"; + const warnings = asStringArray(raw.warnings); + const diagnostics = normalizeWorkspaceDiagnostics(raw.diagnostics); + const repairHints = normalizeWorkspaceRepairHints(raw.repair_hints); return { ok: true, - protocol_version: KNOWLEDGE_SYNC_PROTOCOL_VERSION, - min_protocol_version: KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION, - dry_run: false, - direction: options.direction, - source: options.bundle.source, - target: { - scope: options.targetScope, - workspace_home: options.targetWorkspaceHome, - sqlite_schema_version: options.targetBundle.source.sqlite_schema_version, - artifact_root_uri: options.targetStorage.artifact_store.uri_prefix - }, - tables: options.bundle.tables.filter((table) => !TABLE_SYNC_EXCLUDES.has(table.table)).map((table) => ({ - table: table.table, - source_rows: table.rows.length, - target_rows: getBundleTable(options.targetBundle, table.table)?.rows.length ?? 0, - inserted: 0, - updated: 0, - deleted: 0, - skipped: table.rows.length, - conflicts: 0, - stale_skipped: 0 - })), - artifacts: { - source_artifacts: options.bundle.artifacts.length, - target_artifacts: options.targetBundle.artifacts.length, - copied: 0, - skipped: options.bundle.artifacts.length, - conflicts: 0, - missing_content: 0 - }, - conflicts_created: 0, - bundle_id: options.bundleId, - replayed: true, - clocks: { - advanced: 0, - stale_tables: 0 - }, - warnings: [...options.warnings, `bundle_replay_skipped:${options.bundleId}`], - message: `Skipped already-applied bundle ${options.bundleId}` + source: "open-machines", + adapter, + requested_machine_id: requestedMachineId, + machine_id: asString3(raw.machine_id), + project_id: projectId, + repo_name: repoName, + project_root: projectRoot.path, + project_root_source: projectRoot.source, + workspace_root: workspaceRoot.path, + workspace_root_source: workspaceRoot.source, + open_files_root: openFilesRoot.path, + open_files_root_source: openFilesRoot.source, + trust_status: trustStatus, + auth_status: authStatus, + current: machine.current === true, + primary: machine.primary === true, + diagnostics, + repair_hints: repairHints.length ? repairHints : fallbackWorkspaceRepairHints({ + requestedMachineId, + projectId, + repoName, + openFilesRepoName: options.openFilesRepoName, + warnings, + projectRootSource: projectRoot.source, + openFilesRootSource: openFilesRoot.source, + trustStatus, + authStatus + }), + evidence, + cacheability: normalizeResolverCacheability(raw.cacheability), + warnings }; } -function canSkipBundleReplay(bundle, targetBundle) { - const sourceArtifactUriToKey = artifactUriToKey(bundle.artifacts); - const targetArtifactUriToKey = artifactUriToKey(targetBundle.artifacts); - for (const sourceTable of bundle.tables) { - if (TABLE_SYNC_EXCLUDES.has(sourceTable.table)) - continue; - const targetTable = getBundleTable(targetBundle, sourceTable.table); - const incomingClock = bundleTableClock(bundle, sourceTable.table); - const incomingHash = incomingClock?.high_water_hash ?? tableContentHash(sourceTable.table, sourceTable.rows, sourceArtifactUriToKey); - const currentHash = tableContentHash(sourceTable.table, targetTable?.rows ?? [], targetArtifactUriToKey); - if (currentHash !== incomingHash) - return false; - } - return true; +async function discoverOpenMachinesCliTopology(options, adapter) { + const runner = options.runner ?? defaultRunner; + if (!await hasCommand("machines", runner)) + return null; + const args = ["topology", "--json"]; + if (options.includeTailscale === false) + args.push("--no-tailscale"); + const result = await runCommand(runner, machinesCliCommand(args)); + if (result.exitCode !== 0) + return null; + return normalizeOpenMachinesTopology(parseJson2(result.stdout), options, adapter); } -async function applyKnowledgeSyncBundle(options) { - validateBundle(options.bundle); - migrateKnowledgeDb(options.targetDbPath); - const warnings = [...options.bundle.warnings]; - const dryRun = options.dryRun === true; - const localMachineId = defaultSyncMachineId(options.localMachineId); - const sourceMachineId = options.bundle.source.machine_id ?? "unknown"; - const bundleId = syncBundleId(options.bundle); - const contentHash = syncBundleContentHash(options.bundle); - const targetBundle = options.targetBundle ?? createKnowledgeSyncBundle({ - dbPath: options.targetDbPath, - scope: options.targetScope, - workspaceHome: options.targetWorkspaceHome, - storage: options.targetStorage, - machineId: localMachineId, - includeArtifactContent: false, - recordClocks: !dryRun - }); - const db = openKnowledgeDb(options.targetDbPath); +async function discoverLocalTopology(options, adapter) { + const warnings = []; + if (adapter.error) + warnings.push(`open_machines_unavailable:${adapter.error}`); + const runner = options.runner ?? defaultRunner; + const tailscale = options.includeTailscale === false ? { peers: new Map, selfKey: null } : await loadTailscalePeers(runner, warnings); + const localId = localMachineId(tailscale.selfKey); + const machineIds = new Set([localId, ...tailscale.peers.keys()]); + const machines = [...machineIds].sort().map((machineId) => buildLocalEntry({ + machineId, + localMachineId: localId, + peer: tailscale.peers.get(machineId) + })); + return withKnowledgeContext({ + ok: true, + source: "local", + generated_at: (options.now ?? new Date).toISOString(), + local_machine_id: localId, + local_hostname: hostname4(), + current_platform: normalizePlatform(), + machines, + warnings, + adapter + }, options); +} +async function discoverKnowledgeMachineTopology(options = {}) { + const mode2 = adapterMode(options); + if (mode2 === "disabled") + return await discoverLocalTopology(options, disabledAdapterStatus(mode2)); + const cliStatus = cliAdapterStatus(mode2); try { - if (!dryRun && getSyncImport(db, bundleId) && canSkipBundleReplay(options.bundle, targetBundle)) { - return replayedApplyResult({ - bundle: options.bundle, - targetBundle, - targetScope: options.targetScope, - targetWorkspaceHome: options.targetWorkspaceHome, - targetStorage: options.targetStorage, - direction: options.direction, - warnings, - bundleId - }); - } - const artifactResult = await materializeArtifacts({ - db, - bundle: options.bundle, - targetBundle, - targetStorage: options.targetStorage, - targetStore: options.targetStore, - dryRun, - direction: options.direction, - localMachineId, - warnings - }); - const sourceArtifactUriToKey = artifactUriToKey(options.bundle.artifacts); - const targetArtifactUriToKey = artifactUriToKey(targetBundle.artifacts); - const tableResults = []; - let conflictsCreated = 0; - let clocksAdvanced = 0; - let staleTables = 0; - for (const sourceTable of options.bundle.tables) { - if (sourceTable.table === "storage_objects" || TABLE_SYNC_EXCLUDES.has(sourceTable.table)) - continue; - if (!tableExists2(db, sourceTable.table)) - continue; - const incomingClock = bundleTableClock(options.bundle, sourceTable.table); - const existingClock = tableClock(db, sourceTable.table, sourceMachineId); - const targetTable = getBundleTable(targetBundle, sourceTable.table); - const targetRows = tableRowMap(sourceTable.table, targetTable?.rows ?? []); - const incomingRowKeys = new Set(sourceTable.rows.map((row) => rowKey(sourceTable.table, row))); - const importedRowHashes = latestImportedRowHashes(db, sourceTable.table, sourceMachineId); - const rowsToWrite = []; - const result = { - table: sourceTable.table, - source_rows: sourceTable.rows.length, - target_rows: targetTable?.rows.length ?? 0, - inserted: 0, - updated: 0, - deleted: 0, - skipped: 0, - conflicts: 0, - stale_skipped: 0 - }; - if (!incomingClock) { - warnings.push(`legacy_clock_missing:${sourceTable.table}`); - } else if (staleIncomingClock(existingClock, incomingClock)) { - staleTables += 1; - result.skipped += sourceTable.rows.length; - result.stale_skipped = sourceTable.rows.length; - warnings.push(`stale_table_skipped:${sourceTable.table}:${sourceMachineId}:${incomingClock.logical_clock}`); - tableResults.push(result); - continue; - } - for (const sourceRow of sourceTable.rows) { - const key = rowKey(sourceTable.table, sourceRow); - const targetRow = targetRows.get(key); - const incomingHash = rowHash(sourceRow, sourceArtifactUriToKey); - if (!targetRow) { - result.inserted += 1; - rowsToWrite.push(transformImportedRow(sourceRow, artifactResult.uriMap)); - continue; - } - const currentHash = rowHash(targetRow, targetArtifactUriToKey); - if (currentHash === incomingHash) { - result.skipped += 1; - continue; - } - const importedHash = importedRowHashes.get(key); - if (importedRowHashes.has(key) && importedHash === currentHash) { - result.updated += 1; - rowsToWrite.push(transformImportedRow(sourceRow, artifactResult.uriMap)); - continue; - } - const conflict = { - entityKind: sourceTable.table, - entityId: key, - localMachineId, - remoteMachineId: sourceMachineId, - localHash: currentHash, - remoteHash: incomingHash, - baseHash: existingClock?.high_water_hash ?? null, - metadata: { - direction: options.direction, - bundle_id: bundleId, - incoming_logical_clock: incomingClock?.logical_clock ?? null, - current_logical_clock: existingClock?.logical_clock ?? null, - source_workspace_home: options.bundle.source.workspace_home, - target_workspace_home: options.targetWorkspaceHome, - local_row: sanitizeConflictEvidenceRow(targetRow), - remote_row: sanitizeConflictEvidenceRow(sourceRow) - } - }; - if (hasResolvedConflictFingerprint(db, conflict)) { - result.skipped += 1; - continue; - } - result.conflicts += 1; - if (!dryRun && insertConflict(db, conflict)) - conflictsCreated += 1; - } - if (!dryRun && rowsToWrite.length > 0) { - const writtenRows = rowsToWrite.map((row) => transformImportedRow(row, artifactResult.uriMap)); - upsertSqliteRows(db, sourceTable.table, writtenRows); - refreshDerivedRowsForImport(db, sourceTable.table, writtenRows); - for (const row of writtenRows) { - insertSyncChange(db, { - direction: options.direction, - sourceMachineId: options.bundle.source.machine_id ?? "unknown", - localMachineId, - entityKind: sourceTable.table, - entityId: rowKey(sourceTable.table, row), - nextHash: rowHash(row, artifactUriToKey(options.bundle.artifacts)), - logicalClock: incomingClock?.logical_clock ?? 0, - bundleId, - row - }); - } - } - for (const [key, importedHash] of importedRowHashes) { - if (incomingRowKeys.has(key)) - continue; - const targetRow = targetRows.get(key); - if (!targetRow) - continue; - const currentHash = rowHash(targetRow, targetArtifactUriToKey); - if (importedHash && currentHash !== importedHash) { - const conflict = { - entityKind: sourceTable.table, - entityId: key, - localMachineId, - remoteMachineId: sourceMachineId, - localHash: currentHash, - remoteHash: null, - baseHash: importedHash, - metadata: { - direction: options.direction, - bundle_id: bundleId, - reason: "remote_owned_row_missing_from_incoming_bundle", - source_workspace_home: options.bundle.source.workspace_home, - target_workspace_home: options.targetWorkspaceHome, - local_row: sanitizeConflictEvidenceRow(targetRow), - remote_row: null - } - }; - if (hasResolvedConflictFingerprint(db, conflict)) { - result.skipped += 1; - continue; - } - result.conflicts += 1; - if (!dryRun && insertConflict(db, conflict)) - conflictsCreated += 1; - continue; - } - result.deleted += 1; - if (!dryRun) - deleteSqliteRowByKey(db, sourceTable.table, key); - } - if (!dryRun && incomingClock) { - updateTableClock(db, { - table: sourceTable.table, - machineId: sourceMachineId, - logicalClock: incomingClock.logical_clock, - highWaterHash: incomingClock.high_water_hash, - highWaterBundleId: bundleId, - originMachineId: sourceMachineId, - updatedByMachineId: localMachineId, - lastAppliedAt: nowIso(), - metadata: { - source: "import", - direction: options.direction, - row_count: sourceTable.rows.length, - inserted: result.inserted, - updated: result.updated, - deleted: result.deleted, - skipped: result.skipped, - conflicts: result.conflicts - } + if (mode2 !== "cli") { + const loader = options.loadOpenMachines ?? loadOpenMachinesModule; + const mod = await loader(); + const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); + if (unsupportedStatus) + return await discoverLocalTopology(options, unsupportedStatus); + const sdkStatus = sdkAdapterStatus(mode2, mod); + if (mod?.discoverMachineTopology) { + const topology = mod.discoverMachineTopology({ + includeTailscale: options.includeTailscale, + runner: options.runner, + now: options.now }); - clocksAdvanced += 1; + const normalized = normalizeOpenMachinesTopology(topology, options, sdkStatus); + if (normalized) + return normalized; + if (mode2 === "sdk") + return await discoverLocalTopology(options, disabledAdapterStatus(mode2, "invalid_topology_shape")); + return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, "invalid_topology_shape")); } - tableResults.push(result); + if (mode2 === "sdk") + return await discoverLocalTopology(options, disabledAdapterStatus(mode2, "missing_discoverMachineTopology")); + return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, "missing_discoverMachineTopology")); } - for (const conflict of artifactResult.conflicts) { - if (!dryRun) { - if (insertConflict(db, { - ...conflict, - baseHash: conflict.baseHash ?? null, - metadata: { - ...conflict.metadata, - bundle_id: bundleId - } - })) - conflictsCreated += 1; + return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, "machines_cli_unavailable")); + } catch (error51) { + if (mode2 === "sdk") + return await discoverLocalTopology(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); + return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); + } +} +async function resolveOpenMachinesCliRoute(options, adapter) { + const runner = options.runner ?? defaultRunner; + if (!await hasCommand("machines", runner)) + return null; + const args = ["route", "--machine", options.machineId, "--json"]; + if (options.includeTailscale === false) + args.push("--no-tailscale"); + const result = await runCommand(runner, machinesCliCommand(args)); + if (result.exitCode !== 0) + return null; + return normalizeOpenMachinesRoute(parseJson2(result.stdout), adapter); +} +function rawMachineRoute(machineId, adapter) { + return { + target: machineId, + route: null, + targetKind: null, + confidence: null, + source: "raw", + adapter, + evidence: null, + cacheability: null, + warnings: [] + }; +} +async function resolveKnowledgeMachineRoute(options) { + const mode2 = adapterMode(options); + if (mode2 === "disabled") + return rawMachineRoute(options.machineId, disabledAdapterStatus(mode2)); + const cliStatus = cliAdapterStatus(mode2); + try { + if (mode2 !== "cli") { + const loader = options.loadOpenMachines ?? loadOpenMachinesModule; + const mod = await loader(); + const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); + if (unsupportedStatus) + return rawMachineRoute(options.machineId, unsupportedStatus); + const sdkStatus = sdkAdapterStatus(mode2, mod); + if (mod?.resolveMachineRoute) { + const normalized = normalizeOpenMachinesRoute(mod.resolveMachineRoute(options.machineId, { + includeTailscale: options.includeTailscale, + runner: options.runner, + now: options.now + }), sdkStatus); + if (normalized) + return normalized; + if (mode2 === "sdk") + return rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "invalid_route_shape")); + return await resolveOpenMachinesCliRoute(options, cliStatus) ?? rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "invalid_route_shape")); } + if (mode2 === "sdk") + return rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "missing_resolveMachineRoute")); + return await resolveOpenMachinesCliRoute(options, cliStatus) ?? rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "missing_resolveMachineRoute")); } - const inserted = tableResults.reduce((sum, table) => sum + table.inserted, 0); - const conflicts = tableResults.reduce((sum, table) => sum + table.conflicts, 0) + artifactResult.result.conflicts; - if (!dryRun) { - recordSyncImport(db, { - bundle: options.bundle, - bundleId, - contentHash, - sourceMachineId, - targetMachineId: localMachineId, - direction: options.direction, - status: conflicts === 0 ? "applied" : "conflicted", - tableResults, - conflicts, - artifacts: artifactResult.result - }); + return await resolveOpenMachinesCliRoute(options, cliStatus) ?? rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "machines_cli_unavailable")); + } catch (error51) { + if (mode2 === "sdk") { + return { + ...rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, optionalModuleError(error51))), + warnings: [optionalModuleError(error51)] + }; } - return { - ok: conflicts === 0, - protocol_version: KNOWLEDGE_SYNC_PROTOCOL_VERSION, - min_protocol_version: KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION, - dry_run: dryRun, - direction: options.direction, - source: options.bundle.source, - target: { - scope: options.targetScope, - workspace_home: options.targetWorkspaceHome, - sqlite_schema_version: getSchemaVersion(db), - artifact_root_uri: options.targetStorage.artifact_store.uri_prefix - }, - tables: tableResults, - artifacts: artifactResult.result, - conflicts_created: conflictsCreated, - bundle_id: bundleId, - replayed: false, - clocks: { - advanced: clocksAdvanced, - stale_tables: staleTables - }, - warnings, - message: `${options.dryRun ? "Would import" : "Imported"} ${inserted} row(s), copied ${artifactResult.result.copied} artifact(s), ${conflicts} conflict(s)` + return await resolveOpenMachinesCliRoute(options, cliStatus) ?? { + ...rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, optionalModuleError(error51))), + warnings: [optionalModuleError(error51)] }; - } finally { - db.close(); } } -function createKnowledgeSyncSnapshot(options) { - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - const createdAt = nowIso(options.now); +async function resolveOpenMachinesCliWorkspace(options, adapter) { + const runner = options.runner ?? defaultRunner; + if (!await hasCommand("machines", runner)) + return null; + const projectId = options.projectId ?? "open-knowledge"; + const repoName = options.repoName ?? "open-knowledge"; + const args = [ + "workspace", + "resolve", + "--machine", + options.machineId, + "--project", + projectId, + "--repo", + repoName, + "--open-files-repo", + options.openFilesRepoName ?? "open-files", + "--json" + ]; + if (options.includeTailscale === false) + args.push("--no-tailscale"); + const result = await runCommand(runner, machinesCliCommand(args)); + if (result.exitCode !== 0) + return null; + return normalizeOpenMachinesWorkspace(parseJson2(result.stdout), options, adapter); +} +function argumentMachineWorkspace(options) { + const peerWorkspace = options.peerWorkspace?.trim(); + if (!peerWorkspace) + return null; + const adapter = disabledAdapterStatus(adapterMode(options), "argument_override"); + return { + ok: true, + source: "argument", + adapter, + requested_machine_id: options.machineId, + machine_id: options.machineId, + project_id: options.projectId ?? "open-knowledge", + repo_name: options.repoName ?? "open-knowledge", + project_root: peerWorkspace, + project_root_source: "argument", + workspace_root: null, + workspace_root_source: "unresolved", + open_files_root: null, + open_files_root_source: "unresolved", + trust_status: "unknown", + auth_status: "unknown", + current: false, + primary: false, + diagnostics: [], + repair_hints: [], + evidence: null, + cacheability: null, + warnings: [] + }; +} +function unresolvedMachineWorkspace(options, warnings, adapter) { + return { + ok: false, + source: "raw", + adapter, + requested_machine_id: options.machineId, + machine_id: null, + project_id: options.projectId ?? "open-knowledge", + repo_name: options.repoName ?? "open-knowledge", + project_root: null, + project_root_source: "unresolved", + workspace_root: null, + workspace_root_source: "unresolved", + open_files_root: null, + open_files_root_source: "unresolved", + trust_status: "unknown", + auth_status: "unknown", + current: false, + primary: false, + diagnostics: [], + repair_hints: [], + evidence: null, + cacheability: null, + warnings + }; +} +async function resolveKnowledgeMachineWorkspace(options) { + const argument = argumentMachineWorkspace(options); + if (argument) + return argument; + const mode2 = adapterMode(options); + if (mode2 === "disabled") + return unresolvedMachineWorkspace(options, ["adapter_disabled"], disabledAdapterStatus(mode2)); + const cliStatus = cliAdapterStatus(mode2); try { - const machinesUpserted = options.topology ? refreshMachineRegistryFromTopology(db, options.topology, createdAt) : 0; - const tables = tableCounts(db); - const artifacts = redactPrivateRefs(artifactHashes(db)); - const machineId = options.machineId ?? options.topology?.local_machine_id ?? "unknown"; - const artifactRootUri = redactPrivateRefs(options.storage.artifact_store.uri_prefix); - const workspaceHome = redactPrivateRefs(options.workspaceHome); - const contentHash = sha256(stableJson({ - machine_id: machineId, - scope: options.scope, - workspace_home: workspaceHome, - sqlite_schema_version: getSchemaVersion(db), - artifact_root_uri: artifactRootUri, - tables, - artifacts - })); - const row = { - id: makeSyncId("syncsnap"), - machine_id: machineId, - scope: options.scope, - workspace_home: workspaceHome, - sqlite_schema_version: getSchemaVersion(db), - artifact_root_uri: artifactRootUri, - content_hash: contentHash, - tables_json: JSON.stringify(tables), - artifact_hashes_json: JSON.stringify(artifacts), - created_at: createdAt - }; - db.query(` - INSERT INTO knowledge_sync_snapshots ( - id, machine_id, scope, workspace_home, sqlite_schema_version, - artifact_root_uri, content_hash, tables_json, artifact_hashes_json, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(row.id, row.machine_id, row.scope, row.workspace_home, row.sqlite_schema_version, row.artifact_root_uri, row.content_hash, row.tables_json, row.artifact_hashes_json, row.created_at); - const artifactUriMap = new Map; - for (const table of filterExistingTables(db, resolveSyncTables()).filter((entry) => !TABLE_SYNC_EXCLUDES.has(entry))) { - const rows = tableRows(db, table).map((entry) => redactPrivateRefs(entry)); - const highWaterHash = tableContentHash(table, rows, artifactUriMap); - const existing = tableClock(db, table, machineId); - const logicalClock = existing?.high_water_hash === highWaterHash ? existing.logical_clock : (existing?.logical_clock ?? 0) + 1; - updateTableClock(db, { - table, - machineId, - logicalClock, - highWaterHash, - highWaterBundleId: row.id, - originMachineId: existing?.origin_machine_id ?? machineId, - updatedByMachineId: machineId, - lastAppliedAt: createdAt, - metadata: { - source: "snapshot", - row_count: rows.length - }, - now: createdAt - }); + if (mode2 !== "cli") { + const loader = options.loadOpenMachines ?? loadOpenMachinesModule; + const mod = await loader(); + const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); + if (unsupportedStatus) + return unresolvedMachineWorkspace(options, [`unsupported_contract_version:${unsupportedStatus.contract_version}`], unsupportedStatus); + const sdkStatus = sdkAdapterStatus(mode2, mod); + if (mod?.resolveMachineWorkspace) { + const normalized = normalizeOpenMachinesWorkspace(mod.resolveMachineWorkspace({ + machineId: options.machineId, + projectId: options.projectId ?? "open-knowledge", + repoName: options.repoName ?? "open-knowledge", + openFilesRepoName: options.openFilesRepoName ?? "open-files", + includeTailscale: options.includeTailscale, + runner: options.runner, + now: options.now + }), options, sdkStatus); + if (normalized) + return normalized; + if (mode2 === "sdk") + return unresolvedMachineWorkspace(options, ["invalid_workspace_shape"], disabledAdapterStatus(mode2, "invalid_workspace_shape")); + return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, ["invalid_workspace_shape"], disabledAdapterStatus(mode2, "invalid_workspace_shape")); + } + if (mode2 === "sdk") + return unresolvedMachineWorkspace(options, ["missing_resolveMachineWorkspace"], disabledAdapterStatus(mode2, "missing_resolveMachineWorkspace")); + return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, ["missing_resolveMachineWorkspace"], disabledAdapterStatus(mode2, "missing_resolveMachineWorkspace")); } + return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, ["machines_cli_unavailable"], disabledAdapterStatus(mode2, "machines_cli_unavailable")); + } catch (error51) { + if (mode2 === "sdk") + return unresolvedMachineWorkspace(options, [optionalModuleError(error51)], disabledAdapterStatus(mode2, optionalModuleError(error51))); + return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, [optionalModuleError(error51)], disabledAdapterStatus(mode2, optionalModuleError(error51))); + } +} +function withPreflightKnowledgeContext(report, options) { + return { + ...report, + knowledge: { + scope: options.knowledge?.scope ?? "global", + app_path: HASNA_KNOWLEDGE_APP_PATH, + workspace_home: options.knowledge?.workspace_home ?? null + }, + message: report.ok ? `Machine ${report.machine_id} passed knowledge preflight` : `Machine ${report.machine_id} failed knowledge preflight: ${report.summary.fail} failing check(s)` + }; +} +function normalizeOpenMachinesPreflight(value, options, adapter) { + const raw = asRecord(value); + if (unsupportedContractVersion(payloadContractVersion(raw))) + return null; + const checksRaw = Array.isArray(raw.checks) ? raw.checks : null; + const machineId = asString3(raw.machine_id) ?? asString3(raw.machineId); + if (!checksRaw || !machineId) + return null; + const checks3 = checksRaw.map((entry) => { + const record2 = asRecord(entry); + const status = asString3(record2.status); + const kind = asString3(record2.kind); + const source = asString3(record2.source); + return makePreflightCheck({ + id: asString3(record2.id) ?? "unknown", + kind: kind === "command" || kind === "package" || kind === "workspace" ? kind : "command", + status: status === "ok" || status === "warn" || status === "fail" ? status : "fail", + target: asString3(record2.target) ?? "unknown", + expected: asString3(record2.expected), + actual: asString3(record2.actual), + detail: asString3(record2.detail) ?? "", + source: source === "local" || source === "ssh" || source === "open-machines" ? source : "open-machines" + }); + }); + const summary = { + ok: checks3.filter((check2) => check2.status === "ok").length, + warn: checks3.filter((check2) => check2.status === "warn").length, + fail: checks3.filter((check2) => check2.status === "fail").length + }; + return withPreflightKnowledgeContext({ + ok: summary.fail === 0, + source: "open-machines", + machine_id: machineId, + generated_at: asString3(raw.generated_at) ?? (options.now ?? new Date).toISOString(), + checks: checks3, + summary, + adapter + }, options); +} +function machinesCliPreflightRunner(options) { + if (!options.runner) + return defaultRunner; + return async (command) => { + const result = await options.runner?.("local", command); return { - ok: true, - snapshot: { - ...row, - tables, - artifact_hashes: artifacts - }, - machines_upserted: machinesUpserted, - message: `Recorded sync snapshot ${row.id}` + stdout: result?.stdout ?? "", + stderr: result?.stderr ?? "", + exitCode: result?.exitCode ?? 1 }; - } finally { - db.close(); + }; +} +function machinesCliPackageSpec(spec) { + return [spec.name, spec.command, spec.expectedVersion].filter((value) => Boolean(value)).join(":"); +} +function machinesCliWorkspaceSpec(spec) { + const suffix = [spec.expectedPackageName, spec.expectedVersion].filter((value) => Boolean(value)).join(":"); + const path = suffix ? `${spec.path}:${suffix}` : spec.path; + return spec.label ? `${spec.label}=${path}` : path; +} +async function preflightOpenMachinesCli(options, adapter) { + const runner = machinesCliPreflightRunner(options); + if (!await hasCommand("machines", runner)) + return null; + const args = [ + "compatibility", + "--json", + "--machine", + options.machineId ?? "local" + ]; + for (const spec of options.commands ?? []) { + args.push("--command", spec.expectedVersion ? `${spec.command}:${spec.expectedVersion}` : spec.command); } + for (const spec of options.packages ?? []) + args.push("--package", machinesCliPackageSpec(spec)); + for (const spec of options.workspaces ?? []) + args.push("--workspace", machinesCliWorkspaceSpec(spec)); + const result = await runCommand(runner, machinesCliCommand(args)); + if (result.exitCode !== 0) + return null; + return normalizeOpenMachinesPreflight(parseJson2(result.stdout), options, adapter); } -function getKnowledgeSyncStatus(options) { - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); +async function fallbackPreflight(options, adapter) { + const machineId = options.machineId ?? hostname4(); + const runner = options.runner ?? defaultPreflightRunner; + const commands = options.commands ?? [{ command: "bun", required: true }, { command: "knowledge", required: true }]; + const packages = options.packages ?? [{ name: "@hasna/knowledge", command: "knowledge", required: true }]; + const workspaces = options.workspaces ?? []; + const checks3 = []; + for (const spec of commands) + checks3.push(...await fallbackCommandChecks(machineId, spec, runner)); + for (const spec of packages) + checks3.push(...await fallbackPackageChecks(machineId, spec, runner)); + for (const spec of workspaces) + checks3.push(...await fallbackWorkspaceChecks(machineId, spec, runner)); + if (adapter.error) { + checks3.push(makePreflightCheck({ + id: "adapter:@hasna/machines", + kind: "package", + status: "warn", + target: "@hasna/machines", + expected: "optional", + actual: adapter.error, + detail: "Using knowledge local/ssh compatibility fallback", + source: preflightTargetIsLocal(machineId) ? "local" : "ssh" + })); + } + const summary = { + ok: checks3.filter((check2) => check2.status === "ok").length, + warn: checks3.filter((check2) => check2.status === "warn").length, + fail: checks3.filter((check2) => check2.status === "fail").length + }; + return withPreflightKnowledgeContext({ + ok: summary.fail === 0, + source: "local", + machine_id: machineId, + generated_at: (options.now ?? new Date).toISOString(), + checks: checks3, + summary, + adapter + }, options); +} +async function preflightKnowledgeMachine(options = {}) { + const mode2 = adapterMode(options); + if (mode2 === "disabled") + return await fallbackPreflight(options, disabledAdapterStatus(mode2)); + const cliStatus = cliAdapterStatus(mode2); try { - const machines = db.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(); - const latest = db.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get() ?? null; - const conflictStatuses = db.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(); - const changeOps = db.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(); - const clocks = listTableClocks(db); - const latestImport = db.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get() ?? null; - const totalConflicts = conflictStatuses.reduce((sum, row) => sum + row.count, 0); - const openConflicts = conflictStatuses.filter((row) => row.status !== "resolved" && row.status !== "ignored").reduce((sum, row) => sum + row.count, 0); - return { - ok: true, - scope: options.scope, - workspace_home: redactPrivateRefs(options.workspaceHome), - sqlite_schema_version: getSchemaVersion(db), - local_machine_id: options.localMachineId ?? null, - machines: { - total: machines.length, - rows: redactPrivateRefs(machines) - }, - snapshots: { - total: count2(db, "knowledge_sync_snapshots"), - latest: redactPrivateRefs(latest) - }, - changes: { - total: count2(db, "knowledge_sync_changes"), - by_operation: changeOps - }, - clocks: { - total: clocks.length, - rows: clocks - }, - imports: { - total: count2(db, "knowledge_sync_imports"), - latest: redactPrivateRefs(latestImport) - }, - conflicts: { - total: totalConflicts, - by_status: conflictStatuses, - open: openConflicts - }, - table_counts: tableCounts(db), - message: `${machines.length} machine(s), ${openConflicts} open sync conflict(s)` - }; - } finally { - db.close(); + if (mode2 !== "cli") { + const loader = options.loadOpenMachines ?? loadOpenMachinesModule; + const mod = await loader(); + const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); + if (unsupportedStatus) + return await fallbackPreflight(options, unsupportedStatus); + const sdkStatus = sdkAdapterStatus(mode2, mod); + if (mod?.checkMachineCompatibility) { + const report = mod.checkMachineCompatibility({ + machineId: options.machineId, + commands: options.commands, + packages: options.packages, + workspaces: options.workspaces, + runner: options.runner, + now: options.now + }); + const normalized = normalizeOpenMachinesPreflight(report, options, sdkStatus); + if (normalized) + return normalized; + if (mode2 === "sdk") + return await fallbackPreflight(options, disabledAdapterStatus(mode2, "invalid_compatibility_shape")); + return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, "invalid_compatibility_shape")); + } + if (mode2 === "sdk") + return await fallbackPreflight(options, disabledAdapterStatus(mode2, "missing_checkMachineCompatibility")); + return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, "missing_checkMachineCompatibility")); + } + return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, "machines_cli_unavailable")); + } catch (error51) { + if (mode2 === "sdk") + return await fallbackPreflight(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); + return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); } } -function recordKnowledgeSyncConflict(dbPath, input) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - const now = nowIso(); - const row = { - id: makeSyncId("syncconf"), - entity_kind: input.entityKind, - entity_id: input.entityId, - local_machine_id: input.localMachineId, - remote_machine_id: input.remoteMachineId, - local_hash: input.localHash ?? null, - remote_hash: input.remoteHash ?? null, - base_hash: input.baseHash ?? null, - status: input.status ?? "open", - resolution_strategy: input.resolutionStrategy ?? null, - proposed_patch_uri: input.proposedPatchUri ?? null, - approved_by: input.approvedBy ?? null, - resolved_at: input.resolvedAt ?? null, - metadata_json: JSON.stringify(input.metadata ?? {}), - created_at: now +function mergeAdapterTopologyOptions(defaults, options = {}) { + return { + ...options, + adapterMode: defaults.mode ?? "auto", + includeTailscale: options.includeTailscale ?? defaults.includeTailscale, + runner: options.runner ?? defaults.runner, + now: options.now ?? defaults.now, + loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines + }; +} +function mergeAdapterRouteOptions(defaults, options) { + return { + ...options, + adapterMode: defaults.mode ?? "auto", + includeTailscale: options.includeTailscale ?? defaults.includeTailscale, + runner: options.runner ?? defaults.runner, + now: options.now ?? defaults.now, + loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines + }; +} +function mergeAdapterWorkspaceOptions(defaults, options) { + return { + ...options, + adapterMode: defaults.mode ?? "auto", + includeTailscale: options.includeTailscale ?? defaults.includeTailscale, + runner: options.runner ?? defaults.runner, + now: options.now ?? defaults.now, + loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines + }; +} +function mergeAdapterPreflightOptions(defaults, options = {}) { + return { + ...options, + adapterMode: defaults.mode ?? "auto", + commands: options.commands, + packages: options.packages, + workspaces: options.workspaces, + runner: options.runner ?? defaults.preflightRunner, + now: options.now ?? defaults.now, + loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines + }; +} +function createKnowledgeMachinesAdapter(defaults = {}) { + const mode2 = defaults.mode ?? "auto"; + return { + mode: mode2, + async status() { + if (mode2 === "disabled") + return disabledAdapterStatus(mode2); + if (mode2 === "cli") + return cliAdapterStatus(mode2); + try { + const loader = defaults.loadOpenMachines ?? loadOpenMachinesModule; + const mod = await loader(); + const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); + if (unsupportedStatus) + return unsupportedStatus; + if (mod) + return sdkAdapterStatus(mode2, mod); + if (mode2 === "sdk") + return disabledAdapterStatus(mode2, "module_not_found"); + return cliAdapterStatus(mode2); + } catch (error51) { + return disabledAdapterStatus(mode2, optionalModuleError(error51)); + } + }, + topology(options = {}) { + return discoverKnowledgeMachineTopology(mergeAdapterTopologyOptions(defaults, options)); + }, + route(options) { + return resolveKnowledgeMachineRoute(mergeAdapterRouteOptions(defaults, options)); + }, + workspace(options) { + return resolveKnowledgeMachineWorkspace(mergeAdapterWorkspaceOptions(defaults, options)); + }, + preflight(options = {}) { + return preflightKnowledgeMachine(mergeAdapterPreflightOptions(defaults, options)); + } }; +} + +// src/promotion-inbox.ts +import { createHash as createHash14 } from "crypto"; +function stableId7(prefix, value, length = 24) { + return `${prefix}_${createHash14("sha256").update(value).digest("hex").slice(0, length)}`; +} +function normalizedText(value) { + return value.normalize("NFKC").trim().replace(/\s+/g, " "); +} +function normalizedKey(value) { + return normalizedText(value).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, ""); +} +function parseJson3(value, fallback) { try { - db.query(` - INSERT INTO knowledge_sync_conflicts ( - id, entity_kind, entity_id, local_machine_id, remote_machine_id, - local_hash, remote_hash, base_hash, status, resolution_strategy, - proposed_patch_uri, approved_by, resolved_at, metadata_json, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(row.id, row.entity_kind, row.entity_id, row.local_machine_id, row.remote_machine_id, row.local_hash, row.remote_hash, row.base_hash, row.status, row.resolution_strategy, row.proposed_patch_uri, row.approved_by, row.resolved_at, row.metadata_json, row.created_at); - return row; - } finally { - db.close(); + return JSON.parse(value); + } catch { + return fallback; } } -function hydrateConflict(row) { +function asCandidate(row) { return { ...row, - metadata: parseJson(row.metadata_json, {}) + record_kind: row.record_kind, + source_kind: row.source_kind, + status: row.status, + source_refs: parseJson3(row.source_refs_json, []), + evidence_refs: parseJson3(row.evidence_refs_json, []), + requires_approval: row.requires_approval === 1, + checks: parseJson3(row.checks_json, emptyChecks()), + metadata: parseJson3(row.metadata_json, {}) }; } -function getKnowledgeSyncConflict(dbPath, id) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - try { - const row = db.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(id); - return row ? hydrateConflict(row) : null; - } finally { - db.close(); - } +function asDurableRecord(row) { + return { + ...row, + record_kind: row.record_kind, + source_refs: parseJson3(row.source_refs_json, []), + evidence_refs: parseJson3(row.evidence_refs_json, []), + metadata: parseJson3(row.metadata_json, {}) + }; } -function listKnowledgeSyncConflicts(dbPath, options = {}) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); +function emptyChecks() { + return { + citations: { provided: 0, valid: 0, invalid: 0, entries: [] }, + invalid_source_refs: [], + stale_refs: [], + duplicate_record_ids: [], + duplicate_candidate_ids: [], + conflicting_record_ids: [], + conflicting_candidate_ids: [], + approval_reasons: [] + }; +} +function normalizeEvidenceRef(input) { + const value = typeof input === "string" ? { ref: input } : input; + return { + ref: normalizedText(value.ref), + citation_id: value.citation_id ?? null, + chunk_id: value.chunk_id ?? null, + revision: value.revision ?? null, + hash: value.hash ?? null, + observed_at: value.observed_at ?? null, + expires_at: value.expires_at ?? null, + status: value.status ?? null + }; +} +function validReference(ref) { try { - const rows = options.status ? db.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all(options.status, limit) : db.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(limit); - return rows.map(hydrateConflict); - } finally { - db.close(); + const parsed = new URL(ref); + return parsed.protocol.length > 1 && (parsed.hostname.length > 0 || parsed.pathname.length > 0); + } catch { + return /^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(ref); } } -function conflictTable(value) { - return KNOWLEDGE_SYNC_TABLES.includes(value) ? value : null; +function staleStatus(status) { + return ["deleted", "stale", "invalidated", "reindex_required", "expired", "superseded"].includes((status ?? "").toLowerCase()); } -function catalogRowForConflict(db, conflict) { - const table = conflictTable(conflict.entity_kind); - if (!table || !tableExists2(db, table)) - return null; - const values = parseRowKeyValues(table, conflict.entity_id); - if (!values) +function metadataStatus(value) { + if (!value) return null; - const where = primaryKeyWhereClause(table); - return db.query(`SELECT * FROM ${quoteIdent(table)} WHERE ${where} LIMIT 1`).get(...values); + const metadata = parseJson3(value, {}); + if (metadata.stale === true) + return "stale"; + return typeof metadata.status === "string" ? metadata.status : null; } -function rowFromMetadata(metadata, keys) { - for (const key of keys) { - const value = metadata[key]; - if (value && typeof value === "object" && !Array.isArray(value)) - return sanitizeConflictEvidenceRow(value); - } - return null; +function citationIdentifier(evidence) { + if (evidence.citation_id) + return evidence.citation_id; + const match = evidence.ref.match(/^(?:cite|citation):(.+)$/); + return match?.[1] ?? null; } -function addSourceRef(refs, value) { - if (typeof value !== "string") - return; - const trimmed = value.trim(); - if (!trimmed) - return; - if (trimmed.startsWith("open-files://") || trimmed.startsWith("s3://") || trimmed.startsWith("file://") || trimmed.startsWith("https://") || trimmed.startsWith("http://")) - refs.add(trimmed); +function chunkIdentifier(evidence) { + if (evidence.chunk_id) + return evidence.chunk_id; + const match = evidence.ref.match(/^chunk:(.+)$/); + return match?.[1] ?? null; } -function collectSourceRefs(value, refs = new Set, depth = 0) { - if (depth > 8 || value === null || value === undefined) - return refs; - if (typeof value === "string") { - addSourceRef(refs, value); - return refs; +function inspectCitation(db, evidence, now) { + const explicitStale = staleStatus(evidence.status) || Boolean(evidence.expires_at && evidence.expires_at <= now); + if (!evidence.ref || !validReference(evidence.ref)) { + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "invalid_reference" }; } - if (Array.isArray(value)) { - for (const entry of value) - collectSourceRefs(entry, refs, depth + 1); - return refs; + const citationId = citationIdentifier(evidence); + const citation = db.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, + sr.source_id, sr.created_at AS revision_created_at, + (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at + FROM citations c + LEFT JOIN chunks ch ON ch.id = c.chunk_id + LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE c.id = ? OR c.source_uri = ? + ORDER BY c.created_at DESC + LIMIT 1`).get(citationId, evidence.ref); + if (citation) { + const hashMismatch = Boolean(evidence.hash && citation.revision_hash && evidence.hash !== citation.revision_hash); + const revisionMismatch = Boolean(evidence.revision && citation.revision && evidence.revision !== citation.revision); + const oldRevision = Boolean(citation.revision_created_at && citation.latest_revision_at && citation.revision_created_at < citation.latest_revision_at); + const stale = explicitStale || staleStatus(metadataStatus(citation.chunk_metadata_json)) || hashMismatch || revisionMismatch || oldRevision; + return { + ref: evidence.ref, + valid: true, + resolved_by: "citation", + stale, + reason: hashMismatch ? "hash_mismatch" : revisionMismatch ? "revision_mismatch" : oldRevision ? "newer_source_revision" : stale ? "stale_citation" : null + }; } - if (typeof value === "object") { - for (const [key, entry] of Object.entries(value)) { - if (key === "source_ref" || key === "source_uri" || key === "artifact_uri" || key.endsWith("_uri")) - addSourceRef(refs, entry); - collectSourceRefs(entry, refs, depth + 1); - } + const chunkId = chunkIdentifier(evidence); + if (chunkId) { + const chunk = db.query(`SELECT ch.metadata_json, sr.hash, sr.revision + FROM chunks ch LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE ch.id = ?`).get(chunkId); + if (!chunk) + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "chunk_not_found" }; + const mismatch = Boolean(evidence.hash && chunk.hash && evidence.hash !== chunk.hash || evidence.revision && chunk.revision && evidence.revision !== chunk.revision); + const stale = explicitStale || staleStatus(metadataStatus(chunk.metadata_json)) || mismatch; + return { ref: evidence.ref, valid: true, resolved_by: "chunk", stale, reason: mismatch ? "source_version_mismatch" : stale ? "stale_chunk" : null }; } - return refs; -} -function conflictCitations(input) { - const citations = [{ - id: "conflict", - kind: "metadata", - ref: `knowledge-sync-conflict://${input.conflict.id}`, - hash: input.conflict.base_hash, - quote: `Conflict on ${input.conflict.entity_kind}:${input.conflict.entity_id}` - }]; - if (input.localRow) { - citations.push({ - id: "local-row", - kind: "row", - ref: `${input.conflict.entity_kind}:${input.conflict.entity_id}:local`, - hash: input.conflict.local_hash, - quote: JSON.stringify(input.localRow).slice(0, 300) - }); + const source = db.query("SELECT metadata_json FROM sources WHERE uri = ? LIMIT 1").get(evidence.ref); + if (source) { + const stale = explicitStale || staleStatus(metadataStatus(source.metadata_json)); + return { ref: evidence.ref, valid: true, resolved_by: "source", stale, reason: stale ? "stale_source" : null }; } - if (input.remoteRow) { - citations.push({ - id: "remote-row", - kind: "row", - ref: `${input.conflict.entity_kind}:${input.conflict.entity_id}:remote`, - hash: input.conflict.remote_hash, - quote: JSON.stringify(input.remoteRow).slice(0, 300) - }); + const runMatch = evidence.ref.match(/^knowledge:\/\/project\/runs\/([^/?#]+)/); + if (runMatch) { + const run = db.query("SELECT id FROM runs WHERE id = ?").get(decodeURIComponent(runMatch[1])); + if (!run) + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "run_not_found" }; + return { ref: evidence.ref, valid: true, resolved_by: "run", stale: explicitStale, reason: explicitStale ? "expired_evidence" : null }; } - input.sourceRefs.slice(0, 10).forEach((ref, index) => { - citations.push({ - id: `source-${index + 1}`, - kind: ref.startsWith("file://") || ref.startsWith("s3://") ? "artifact" : "source_ref", - ref, - hash: null, - quote: null - }); - }); - return citations; + return { + ref: evidence.ref, + valid: true, + resolved_by: "external_uri", + stale: explicitStale, + reason: explicitStale ? "expired_evidence" : null + }; } -function getKnowledgeSyncConflictEvidence(dbPath, id) { - const conflict = getKnowledgeSyncConflict(dbPath, id); - if (!conflict) - throw new Error(`Sync conflict not found: ${id}`); - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - try { - const localRow = sanitizeConflictEvidenceRow(catalogRowForConflict(db, conflict)); - const remoteRow = rowFromMetadata(conflict.metadata, ["remote_row", "source_row", "incoming_row"]); - const refs = collectSourceRefs({ - conflict: { - entity_kind: conflict.entity_kind, - entity_id: conflict.entity_id, - metadata: conflict.metadata - }, - local_row: localRow, - remote_row: remoteRow - }); - const sourceRefs = [...refs].slice(0, 25); - const readOnlyTools = [ - { - name: "knowledge_sync_conflict_get", - input: { id }, - output_summary: `${conflict.entity_kind}:${conflict.entity_id} status=${conflict.status}` - }, - { - name: "knowledge_catalog_row_get", - input: { table: conflict.entity_kind, key: conflict.entity_id }, - output_summary: localRow ? "local row found" : "local row unavailable" - }, - { - name: "knowledge_source_ref_extract", - input: { id }, - output_summary: `${sourceRefs.length} source/artifact ref(s) found` - } - ]; - return { - conflict, - local_row: localRow, - remote_row: remoteRow, - source_refs: sourceRefs, - citations: conflictCitations({ conflict, localRow, remoteRow, sourceRefs }), - read_only_tools: readOnlyTools - }; - } finally { - db.close(); +function candidateById(db, id) { + return db.query("SELECT * FROM knowledge_promotion_candidates WHERE id = ?").get(id) ?? null; +} +function assessCandidate(db, row, now) { + const evidence = parseJson3(row.evidence_refs_json, []); + const sourceRefs = parseJson3(row.source_refs_json, []); + const metadata = parseJson3(row.metadata_json, {}); + const checks3 = emptyChecks(); + checks3.invalid_source_refs = sourceRefs.filter((ref) => !validReference(ref)); + checks3.citations.entries = evidence.map((entry) => inspectCitation(db, entry, now)); + checks3.citations.provided = evidence.length; + checks3.citations.valid = checks3.citations.entries.filter((entry) => entry.valid).length; + checks3.citations.invalid = checks3.citations.entries.length - checks3.citations.valid; + checks3.stale_refs = checks3.citations.entries.filter((entry) => entry.stale).map((entry) => entry.ref); + checks3.duplicate_record_ids = db.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND content_hash = ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(row.record_kind, row.content_hash).map((entry) => entry.id); + checks3.duplicate_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND content_hash = ? AND status NOT IN ('rejected') + ORDER BY created_at`).all(row.id, row.record_kind, row.content_hash).map((entry) => entry.id); + checks3.conflicting_record_ids = db.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + checks3.conflicting_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND canonical_key = ? AND content_hash <> ? + AND status IN ('ready', 'needs_approval', 'promoted') + ORDER BY created_at`).all(row.id, row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + const duplicateOf = checks3.duplicate_record_ids[0] ?? checks3.duplicate_candidate_ids[0] ?? null; + const blocked = sourceRefs.length === 0 || evidence.length === 0 || checks3.invalid_source_refs.length > 0 || checks3.citations.invalid > 0; + if (row.record_kind === "decision" || row.record_kind === "claim") + checks3.approval_reasons.push(`${row.record_kind}_requires_review`); + if (metadata.requested_approval === true) + checks3.approval_reasons.push("explicit_approval_request"); + if (checks3.stale_refs.length > 0) + checks3.approval_reasons.push("stale_evidence"); + if (checks3.conflicting_record_ids.length > 0 || checks3.conflicting_candidate_ids.length > 0) { + checks3.approval_reasons.push("conflicting_knowledge"); } + const requiresApproval = checks3.approval_reasons.length > 0; + const status = duplicateOf ? "duplicate" : blocked ? "blocked" : requiresApproval ? "needs_approval" : "ready"; + db.run(`UPDATE knowledge_promotion_candidates + SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, [status, requiresApproval ? 1 : 0, JSON.stringify(checks3), duplicateOf, now, now, row.id]); + return asCandidate(candidateById(db, row.id)); } -function proposeKnowledgeSyncConflictResolution(dbPath, id) { - const conflict = getKnowledgeSyncConflict(dbPath, id); - if (!conflict) - throw new Error(`Sync conflict not found: ${id}`); - const proposedStrategy = conflict.entity_kind === "wiki_pages" ? "manual-merge" : "review-and-select"; - const summary = [ - `Conflict ${conflict.id} affects ${conflict.entity_kind}:${conflict.entity_id}.`, - `Local machine ${conflict.local_machine_id} has ${conflict.local_hash ?? "unknown hash"}.`, - `Remote machine ${conflict.remote_machine_id} has ${conflict.remote_hash ?? "unknown hash"}.` - ].join(" "); - const mergePrompt = [ - "Review this knowledge sync conflict before any durable write.", - `Entity: ${conflict.entity_kind}:${conflict.entity_id}`, - `Local machine/hash: ${conflict.local_machine_id} / ${conflict.local_hash ?? "unknown"}`, - `Remote machine/hash: ${conflict.remote_machine_id} / ${conflict.remote_hash ?? "unknown"}`, - `Base hash: ${conflict.base_hash ?? "unknown"}`, - `Metadata: ${JSON.stringify(conflict.metadata)}`, - "Return a concise merge recommendation with citations to the competing records. Do not write changes without approval." - ].join(` -`); - return { - ok: true, - conflict, - requires_approval: true, - mode: "deterministic", - proposed_strategy: proposedStrategy, - summary, - merge_prompt: mergePrompt, - proposed_patch: null, - citations: conflictCitations({ conflict, localRow: null, remoteRow: null, sourceRefs: [] }), - confidence: null, - agent: null, - warnings: conflict.status === "resolved" ? ["conflict_already_resolved"] : [], - message: `Prepared approval-gated merge proposal for ${conflict.id}` +function enqueueKnowledgePromotion(dbPath, input) { + const kinds = ["lesson", "decision", "claim"]; + const sourceKinds = ["memento", "session", "report"]; + if (!kinds.includes(input.kind)) + throw new Error("Promotion kind must be lesson, decision, or claim."); + if (!sourceKinds.includes(input.sourceKind)) + throw new Error("Promotion source kind must be memento, session, or report."); + const titleResult = redactSecrets(normalizedText(input.title)); + const contentResult = redactSecrets(normalizedText(input.content)); + if (!titleResult.text) + throw new Error("Promotion title is required."); + if (!contentResult.text) + throw new Error("Promotion content is required."); + const sourceRefs = Array.from(new Set(input.sourceRefs.map(normalizedText).filter(Boolean))).sort(); + const evidenceRefs = input.evidenceRefs.map(normalizeEvidenceRef).filter((entry) => entry.ref.length > 0).sort((a, b) => a.ref.localeCompare(b.ref)); + const canonicalKey = normalizedKey(input.canonicalKey ?? titleResult.text); + if (!canonicalKey) + throw new Error("Promotion canonical key is empty after normalization."); + const contentHash = `sha256:${createHash14("sha256").update(`${input.kind}\x00${normalizedText(contentResult.text).toLowerCase()}`).digest("hex")}`; + const idempotencyKey = stableId7("promote", [ + input.sourceKind, + input.kind, + canonicalKey, + contentHash, + ...sourceRefs + ].join("\x00")); + const id = stableId7("promotion", idempotencyKey); + const now = (input.now ?? new Date).toISOString(); + const metadata = { + ...input.metadata ?? {}, + requested_approval: input.requiresApproval === true, + confidence: input.confidence ?? null, + valid_from: input.validFrom ?? now, + valid_to: input.validTo ?? null, + redactions: titleResult.findings.length + contentResult.findings.length }; -} -function resolveKnowledgeSyncConflict(dbPath, input) { migrateKnowledgeDb(dbPath); const db = openKnowledgeDb(dbPath); - const now = nowIso(); - try { - const existing = db.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(input.id); - if (!existing) - throw new Error(`Sync conflict not found: ${input.id}`); - db.query(` - UPDATE knowledge_sync_conflicts - SET status = 'resolved', - resolution_strategy = ?, - proposed_patch_uri = ?, - approved_by = ?, - resolved_at = ? - WHERE id = ? - `).run(input.strategy, input.proposedPatchUri ?? existing.proposed_patch_uri, input.approvedBy, now, input.id); - const row = db.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(input.id); - if (!row) - throw new Error(`Sync conflict not found after resolve: ${input.id}`); - return hydrateConflict(row); - } finally { - db.close(); - } -} -function syncTablesFromSnapshot(snapshot) { - return parseJson(snapshot.tables_json, {}); -} -function syncArtifactsFromSnapshot(snapshot) { - return parseJson(snapshot.artifact_hashes_json, []); -} - -// src/conflict-agent.ts -function estimateTokens2(value) { - const text = typeof value === "string" ? value : JSON.stringify(value); - const words = text.trim().split(/\s+/).filter(Boolean).length; - return Math.max(1, Math.ceil(words * 1.25)); -} -function insertConflictRun(options) { - const db = openKnowledgeDb(options.dbPath); try { - db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - options.runId, - "sync-conflict-proposal", - options.prompt, - options.status, - options.provider, - options.model, - JSON.stringify(options.metadata), - options.now, - options.now + const existing = db.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(idempotencyKey); + if (existing) + return { created: false, candidate: asCandidate(existing) }; + db.run(`INSERT INTO knowledge_promotion_candidates ( + id, record_kind, title, content, canonical_key, content_hash, source_kind, + source_refs_json, evidence_refs_json, status, requires_approval, checks_json, + idempotency_key, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`, [ + id, + input.kind, + titleResult.text, + contentResult.text, + canonicalKey, + contentHash, + input.sourceKind, + JSON.stringify(sourceRefs), + JSON.stringify(evidenceRefs), + idempotencyKey, + JSON.stringify(metadata), + now, + now ]); + const findings = [...titleResult.findings, ...contentResult.findings]; + if (findings.length > 0) { + recordRedactionFindings(db, { + source_uri: sourceRefs[0] ?? `knowledge://promotion/${id}`, + findings, + metadata: { promotion_candidate_id: id }, + created_at: now + }); + } + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "enqueue_promotion", + target_uri: `knowledge://promotion/${id}`, + decision: "info", + metadata: { record_kind: input.kind, source_kind: input.sourceKind, source_refs: sourceRefs }, + created_at: now + }); + return { created: true, candidate: assessCandidate(db, candidateById(db, id), now) }; } finally { db.close(); } } -function updateConflictRun(options) { - const db = openKnowledgeDb(options.dbPath); +function getKnowledgePromotion(dbPath, id) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); try { - db.run(`UPDATE runs - SET status = ?, provider = ?, model = ?, cost_tokens = ?, cost_usd = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`, [ - options.status, - options.provider, - options.model, - options.usage.input_tokens + options.usage.output_tokens, - options.usage.cost_usd, - JSON.stringify(options.metadata), - options.now, - options.runId - ]); + const row = candidateById(db, id); + return row ? asCandidate(row) : null; } finally { db.close(); } } -function addConflictRunEvent(options) { - const db = openKnowledgeDb(options.dbPath); +function listKnowledgePromotions(dbPath, options = {}) { + migrateKnowledgeDb(dbPath); + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const conditions = []; + const params = []; + if (options.status === "inbox" || !options.status) { + conditions.push("status IN ('ready', 'needs_approval', 'blocked')"); + } else { + conditions.push("status = ?"); + params.push(options.status); + } + if (options.kind) { + conditions.push("record_kind = ?"); + params.push(options.kind); + } + const db = openKnowledgeDb(dbPath); try { - db.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, [ - `event_${randomUUID8()}`, - options.runId, - options.level, - options.event, - JSON.stringify(options.metadata), - options.now - ]); + return db.query(`SELECT * FROM knowledge_promotion_candidates + WHERE ${conditions.join(" AND ")} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...params, limit).map(asCandidate); } finally { db.close(); } } -function recordUsage2(dbPath, runId, usage, now) { +function reviewKnowledgePromotion(dbPath, id, now = new Date) { + migrateKnowledgeDb(dbPath); const db = openKnowledgeDb(dbPath); try { - recordProviderUsage(db, { - ...usage, - run_id: runId, - created_at: now - }); + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted" || row.status === "rejected") + return asCandidate(row); + return assessCandidate(db, row, now.toISOString()); } finally { db.close(); } } -function promptForConflict(input) { - return [ - "Build an approval-gated merge proposal for this knowledge sync conflict.", - "Use only the supplied JSON evidence. Do not claim to inspect external files or write changes.", - "Return a patch recommendation that a human can review before approval.", - "", - `Deterministic proposal: -${JSON.stringify({ - proposed_strategy: input.deterministic.proposed_strategy, - summary: input.deterministic.summary, - warnings: input.deterministic.warnings - }, null, 2)}`, - "", - `Conflict evidence: -${JSON.stringify(input.evidence, null, 2)}` - ].join(` -`); -} -function normalizeConfidence(value) { - const number4 = typeof value === "number" && Number.isFinite(value) ? value : 0.5; - return Math.max(0, Math.min(1, number4)); -} -function normalizePatch(value, conflictTarget) { - const kind = value.kind === "choose_local" || value.kind === "choose_remote" || value.kind === "no_op" || value.kind === "custom" || value.kind === "manual_merge" ? value.kind : "manual_merge"; - return { - kind, - target: typeof value.target === "string" && value.target ? value.target : conflictTarget, - strategy: typeof value.strategy === "string" && value.strategy ? value.strategy : kind.replace("_", "-"), - summary: typeof value.summary === "string" && value.summary ? value.summary : "Review both sides before applying a merge.", - diff: typeof value.diff === "string" && value.diff ? value.diff : null, - metadata: value.metadata && typeof value.metadata === "object" && !Array.isArray(value.metadata) ? value.metadata : {} - }; -} -function fakePatch(input) { - const target = `${input.conflict.entity_kind}:${input.conflict.entity_id}`; - const hasBothRows = Boolean(input.local_row && input.remote_row); - return { - kind: hasBothRows ? "manual_merge" : "custom", - target, - strategy: hasBothRows ? "manual-merge" : "review-and-select", - summary: hasBothRows ? `Fake AI proposal: compare local and remote ${target} row snapshots, then apply a reviewed manual merge.` : `Fake AI proposal: inspect ${target} with available conflict metadata before selecting a side.`, - diff: hasBothRows ? [ - `--- ${target} local`, - `+++ ${target} remote`, - "@@ review-required @@", - JSON.stringify({ local: input.local_row, remote: input.remote_row }, null, 2).slice(0, 1200) - ].join(` -`) : null, - metadata: { - fake: true, - local_hash: input.conflict.local_hash, - remote_hash: input.conflict.remote_hash, - source_refs: input.source_refs - } - }; -} -async function proposeKnowledgeSyncConflictResolutionWithAi(options) { +function promoteKnowledgeCandidate(dbPath, id, options = {}) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); const now = (options.now ?? new Date).toISOString(); - migrateKnowledgeDb(options.dbPath); - const deterministic = proposeKnowledgeSyncConflictResolution(options.dbPath, options.id); - const evidence = getKnowledgeSyncConflictEvidence(options.dbPath, options.id); - const resolvedModelRef = resolveModelRef(options.modelRef ?? "default", options.config); - const parsed = parseModelRef(resolvedModelRef); - const runId = `run_${randomUUID8()}`; - const prompt = promptForConflict({ deterministic, evidence }); - insertConflictRun({ - dbPath: options.dbPath, - runId, - prompt, - provider: parsed.provider, - model: parsed.model, - status: options.fake ? "dry_run" : "running", - metadata: { - conflict_id: options.id, - mode: "ai", - fake: options.fake === true, - read_only_tools: evidence.read_only_tools.map((tool) => tool.name) - }, - now - }); - addConflictRunEvent({ - dbPath: options.dbPath, - runId, - level: "info", - event: "conflict_evidence_retrieved", - metadata: { - citations: evidence.citations.length, - source_refs: evidence.source_refs.length, - read_only_tools: evidence.read_only_tools - }, - now - }); - let patch; - let summary; - let confidence = 0.5; - let usage = { - input_tokens: estimateTokens2(prompt), - output_tokens: 0, - cost_usd: 0 - }; - if (options.fake) { - patch = fakePatch(evidence); - summary = patch.summary; - usage.output_tokens = estimateTokens2(summary) + estimateTokens2(patch.diff ?? ""); - } else { - try { - const { generateObject } = await import("ai"); - const { z: z2 } = await Promise.resolve().then(() => (init_zod(), exports_zod)); - const model = await languageModelFor(resolvedModelRef, { - config: options.config, - env: options.env - }); - const schema = z2.object({ - summary: z2.string(), - confidence: z2.number().min(0).max(1), - proposed_patch: z2.object({ - kind: z2.enum(["manual_merge", "choose_local", "choose_remote", "no_op", "custom"]), - target: z2.string(), - strategy: z2.string(), - summary: z2.string(), - diff: z2.string().nullable(), - metadata: z2.record(z2.string(), z2.unknown()).default({}) - }) - }); - const result = await generateObject({ - model, - schema, - system: "You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.", - prompt - }); - summary = result.object.summary; - confidence = normalizeConfidence(result.object.confidence); - patch = normalizePatch(result.object.proposed_patch, `${evidence.conflict.entity_kind}:${evidence.conflict.entity_id}`); - const normalized = normalizeAiSdkUsage({ - provider: parsed.provider, - model: parsed.model, - usage: result.usage, - providerMetadata: result.providerMetadata - }); - usage = { - input_tokens: normalized.input_tokens, - output_tokens: normalized.output_tokens, - cost_usd: normalized.cost_usd + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted" && row.promoted_record_id) { + const existingRecord = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(row.promoted_record_id); + return { + ok: true, + promoted: false, + requires_approval: row.requires_approval === 1, + candidate: asCandidate(row), + record: existingRecord ? asDurableRecord(existingRecord) : null, + approval_id: null, + reason: "already_promoted" }; - recordUsage2(options.dbPath, runId, normalized, now); - } catch (error51) { - addConflictRunEvent({ - dbPath: options.dbPath, - runId, - level: "error", - event: "conflict_proposal_generation_failed", - metadata: { message: error51 instanceof Error ? error51.message : String(error51) }, - now - }); - updateConflictRun({ - dbPath: options.dbPath, - runId, - status: "failed", - provider: parsed.provider, - model: parsed.model, - usage, - metadata: { - conflict_id: options.id, - mode: "ai", - error: error51 instanceof Error ? error51.message : String(error51) - }, - now - }); - throw error51; } - } - updateConflictRun({ - dbPath: options.dbPath, - runId, - status: options.fake ? "dry_run" : "completed", - provider: parsed.provider, - model: parsed.model, - usage, - metadata: { - conflict_id: options.id, - mode: "ai", - fake: options.fake === true, - confidence, - proposed_strategy: patch.strategy, - citation_count: evidence.citations.length - }, - now - }); - addConflictRunEvent({ - dbPath: options.dbPath, - runId, - level: "info", - event: options.fake ? "fake_conflict_proposal_generated" : "conflict_proposal_generated", - metadata: { - strategy: patch.strategy, - confidence, - patch_kind: patch.kind - }, - now - }); - return { - ...deterministic, - mode: "ai", - proposed_strategy: patch.strategy, - summary, - proposed_patch: patch, - citations: evidence.citations, - confidence, - agent: { - generated: true, - provider: parsed.provider, - model: parsed.model, - run_id: runId, - read_only_tools: evidence.read_only_tools, - usage - }, - warnings: [ - ...deterministic.warnings, - ...evidence.remote_row ? [] : ["remote_row_snapshot_unavailable"] - ], - message: `Prepared AI SDK approval-gated merge proposal for ${options.id}` - }; -} - -// src/outbox-consume.ts -import { createHash as createHash13, randomUUID as randomUUID9 } from "crypto"; -import { existsSync as existsSync10, readFileSync as readFileSync11 } from "fs"; -import { basename as basename4 } from "path"; -function stableId6(prefix, value) { - return `${prefix}_${createHash13("sha256").update(value).digest("hex").slice(0, 20)}`; -} -function asObject2(value) { - return value && typeof value === "object" && !Array.isArray(value) ? value : undefined; -} -function asString2(value) { - return typeof value === "string" && value.length > 0 ? value : undefined; -} -function buildSourceRef(event) { - const explicit = asString2(event.source_ref) ?? asString2(event.source_uri) ?? asString2(event.uri); - if (explicit) - return explicit; - const fileId = asString2(event.file_id); - if (fileId) { - const revision = asString2(event.revision_id) ?? asString2(event.revision); - const fileRef = `open-files://file/${encodeURIComponent(fileId)}`; - return revision ? `${fileRef}/revision/${encodeURIComponent(revision)}` : fileRef; - } - const sourceId = asString2(event.source_id); - const path = asString2(event.path); - if (sourceId && path) { - return `open-files://source/${encodeURIComponent(sourceId)}/path/${encodeURIComponent(path)}`; - } - throw new Error("Outbox event is missing source_ref, file_id, or source_id/path."); -} -function baseSourceUri2(sourceRef, parsed) { - if (parsed.kind === "open-files" && parsed.entity === "file" && parsed.revision_id) { - return sourceRef.replace(/\/revision\/[^/]+$/, ""); - } - return sourceRef; -} -function hashFromEvent(event) { - return asString2(event.hash) ?? asString2(event.checksum) ?? asString2(event.sha256) ?? null; -} -function revisionFromEvent(event, parsed, hash2) { - return asString2(event.revision_id) ?? asString2(event.revision) ?? asString2(event.version_id) ?? (parsed.kind === "open-files" ? parsed.revision_id : undefined) ?? hash2 ?? null; -} -function previousRevisionFromEvent(event) { - return asString2(event.previous_revision_id) ?? asString2(event.previous_revision) ?? asString2(event.previous_version_id) ?? null; -} -function eventType(event) { - return (asString2(event.event_type) ?? asString2(event.event) ?? asString2(event.type) ?? asString2(event.action) ?? asString2(event.change_type) ?? "changed").toLowerCase(); -} -function titleFromEvent(event) { - const path = asString2(event.path); - return asString2(event.title) ?? asString2(event.name) ?? (path ? basename4(path) : null); -} -function normalizeEvent(event, now) { - const sourceRef = buildSourceRef(event); - const parsed = parseSourceRef(sourceRef); - const hash2 = hashFromEvent(event); - return { - raw: event, - eventType: eventType(event), - sourceRef, - sourceUri: baseSourceUri2(sourceRef, parsed), - kind: parsed.kind, - title: titleFromEvent(event), - revision: revisionFromEvent(event, parsed, hash2), - previousRevision: previousRevisionFromEvent(event), - hash: hash2, - status: asString2(event.status)?.toLowerCase() ?? null, - updatedAt: asString2(event.updated_at) ?? now, - acl: event.permissions ?? event.acl ?? undefined - }; -} -function parseOutboxText(text) { - const trimmed = text.trim(); - if (!trimmed) - return []; - if (trimmed.startsWith("[")) { - const parsed = JSON.parse(trimmed); - if (!Array.isArray(parsed)) - throw new Error("Outbox array parse failed."); - return parsed.map((entry) => { - const event = asObject2(entry); - if (!event) - throw new Error("Outbox array entries must be objects."); - return event; - }); - } - if (trimmed.startsWith("{")) { - try { - const parsed = JSON.parse(trimmed); - const object2 = asObject2(parsed); - if (!object2) - throw new Error("Outbox object parse failed."); - if (Array.isArray(object2.events)) { - return object2.events.map((entry) => { - const event = asObject2(entry); - if (!event) - throw new Error("Outbox events entries must be objects."); - return event; - }); - } - if ("source_ref" in object2 || "source_uri" in object2 || "file_id" in object2) - return [object2]; - } catch (error51) { - const lines = trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0); - if (lines.length <= 1) - throw error51; - return lines.map((line) => { - const event = asObject2(JSON.parse(line)); - if (!event) - throw new Error("Outbox JSONL entries must be objects."); - return event; - }); + if (row.status === "rejected") + throw new Error(`Promotion candidate ${id} was rejected.`); + const candidate = assessCandidate(db, row, now); + if (candidate.status === "duplicate") { + return { ok: true, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "duplicate" }; + } + if (candidate.status === "blocked") { + return { ok: false, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "citation_check_failed" }; + } + if (candidate.requires_approval && !options.approveWrite) { + return { ok: false, promoted: false, requires_approval: true, candidate, record: null, approval_id: null, reason: "approval_required" }; + } + if (candidate.requires_approval && !options.approvedBy?.trim()) { + throw new Error("Promotion approval requires --approved-by <name>."); + } + const approvedBy = candidate.requires_approval ? options.approvedBy.trim() : null; + let approvalId = null; + if (candidate.requires_approval) { + approvalId = createApprovalGate(db, { + action: "promote_durable_knowledge", + target_uri: `knowledge://promotion/${candidate.id}`, + reason: candidate.checks.approval_reasons.join(", "), + approved_by: approvedBy, + metadata: { promotion_candidate_id: candidate.id, checks: candidate.checks }, + created_at: now + }).id; } + const recordId = stableId7("durable", candidate.id); + const metadata = { + ...candidate.metadata, + promotion_candidate_id: candidate.id, + source_kind: candidate.source_kind, + checks: candidate.checks, + approval_id: approvalId, + provenance: generatedArtifactProvenance({ + generated_from: `knowledge://promotion/${candidate.id}`, + artifact_key: `durable/${candidate.record_kind}/${candidate.canonical_key}`, + source_refs: candidate.source_refs, + citation_required: true + }) + }; + db.run(`INSERT INTO durable_knowledge_records ( + id, record_kind, title, content, canonical_key, content_hash, status, + source_refs_json, evidence_refs_json, confidence, valid_from, valid_to, + promoted_from_candidate_id, approved_by, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + recordId, + candidate.record_kind, + candidate.title, + candidate.content, + candidate.canonical_key, + candidate.content_hash, + candidate.checks.conflicting_record_ids.length > 0 ? "conflicted" : "active", + JSON.stringify(candidate.source_refs), + JSON.stringify(candidate.evidence_refs), + typeof candidate.metadata.confidence === "number" ? candidate.metadata.confidence : null, + typeof candidate.metadata.valid_from === "string" ? candidate.metadata.valid_from : now, + typeof candidate.metadata.valid_to === "string" ? candidate.metadata.valid_to : null, + candidate.id, + approvedBy, + JSON.stringify(metadata), + now, + now + ]); + db.run(`UPDATE knowledge_promotion_candidates + SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? + WHERE id = ?`, [approvedBy, recordId, now, now, candidate.id]); + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "promote_durable_knowledge", + target_uri: `knowledge://durable/${recordId}`, + decision: "allow", + metadata: { promotion_candidate_id: candidate.id, approval_id: approvalId, source_refs: candidate.source_refs }, + created_at: now + }); + const promotedCandidate = asCandidate(candidateById(db, candidate.id)); + const record2 = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(recordId); + return { + ok: true, + promoted: true, + requires_approval: candidate.requires_approval, + candidate: promotedCandidate, + record: asDurableRecord(record2), + approval_id: approvalId, + reason: null + }; + } finally { + db.close(); } - return trimmed.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => { - const event = asObject2(JSON.parse(line)); - if (!event) - throw new Error("Outbox JSONL entries must be objects."); - return event; - }); -} -async function readS3Text3(uri, config2, safetyPolicy) { - const parsed = new URL(uri); - const bucket = parsed.hostname; - const key = decodeURIComponent(parsed.pathname.replace(/^\/+/, "")); - if (!bucket || !key) - throw new Error(`Invalid S3 outbox URI: ${uri}`); - if (safetyPolicy) - assertS3ReadAllowed(uri, safetyPolicy); - const [{ S3Client, GetObjectCommand }, { fromIni }] = await Promise.all([ - import("@aws-sdk/client-s3"), - import("@aws-sdk/credential-providers") - ]); - const s3Config = config2?.storage.type === "s3" && config2.storage.s3?.bucket === bucket ? config2.storage.s3 : undefined; - const client = new S3Client({ - region: s3Config?.region, - credentials: s3Config?.profile ? fromIni({ profile: s3Config.profile }) : undefined, - maxAttempts: s3Config?.max_attempts - }); - const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key })); - if (!response.Body) - return ""; - return await response.Body.transformToString(); -} -async function readOutboxInput(input, config2, safetyPolicy) { - if (input.startsWith("s3://")) - return readS3Text3(input, config2, safetyPolicy); - if (!existsSync10(input)) - throw new Error(`Outbox not found: ${input}`); - return readFileSync11(input, "utf8"); } -function mergeJson(existing, patch) { - let base = {}; - if (existing) { - try { - base = asObject2(JSON.parse(existing)) ?? {}; - } catch { - base = {}; - } +function rejectKnowledgePromotion(dbPath, id, options = {}) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = (options.now ?? new Date).toISOString(); + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted") + throw new Error(`Promotion candidate ${id} is already promoted.`); + db.run(`UPDATE knowledge_promotion_candidates + SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, [options.rejectedBy?.trim() || null, now, now, id]); + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "reject_promotion", + target_uri: `knowledge://promotion/${id}`, + decision: "deny", + metadata: { rejected_by: options.rejectedBy ?? null }, + created_at: now + }); + return asCandidate(candidateById(db, id)); + } finally { + db.close(); } - return JSON.stringify({ ...base, ...patch }); -} -function ensureSource(db, event, now) { - const id = stableId6("src", event.sourceUri); - db.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(uri) DO UPDATE SET - kind = excluded.kind, - title = COALESCE(excluded.title, sources.title), - updated_at = excluded.updated_at`, [ - id, - event.sourceUri, - event.kind, - event.title, - JSON.stringify({ source_ref: event.sourceRef, source_uri: event.sourceUri, status: event.status, last_outbox_event: event.eventType }), - JSON.stringify(event.acl ?? {}), - now, - event.updatedAt - ]); - const row = db.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get(event.sourceUri); - if (!row) - throw new Error(`Failed to upsert source for outbox event: ${event.sourceUri}`); - const patch = { - source_ref: event.sourceRef, - source_uri: event.sourceUri, - last_outbox_event: event.eventType, - last_outbox_at: event.updatedAt - }; - if (event.status) - patch.status = event.status; - if (asString2(event.raw.path)) - patch.path = event.raw.path; - db.run("UPDATE sources SET metadata_json = ?, acl_json = CASE WHEN ? IS NULL THEN acl_json ELSE ? END, updated_at = ? WHERE id = ?", [ - mergeJson(row.metadata_json, patch), - event.acl === undefined ? null : JSON.stringify(event.acl), - event.acl === undefined ? null : JSON.stringify(event.acl), - event.updatedAt, - row.id - ]); - return row.id; -} -function ensureRevision(db, sourceId, event, now) { - if (!event.revision) - return null; - const id = stableId6("rev", `${sourceId}\x00${event.revision}`); - const metadata = { - source_ref: event.sourceRef, - source_uri: event.sourceUri, - status: event.status, - last_outbox_event: event.eventType, - reindex_required: true - }; - db.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(source_id, revision) DO UPDATE SET - hash = COALESCE(excluded.hash, source_revisions.hash), - metadata_json = excluded.metadata_json`, [id, sourceId, event.revision, event.hash, asString2(event.raw.extracted_text_ref) ?? null, JSON.stringify(metadata), now]); - const row = db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(sourceId, event.revision); - return row?.id ?? null; } -function revisionIdsForEvent(db, sourceId, event) { - if (event.previousRevision) { - const previous = db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(sourceId, event.previousRevision).map((row) => row.id); - if (previous.length > 0) - return previous; +function listDurableKnowledgeRecords(dbPath, options = {}) { + migrateKnowledgeDb(dbPath); + const conditions = []; + const params = []; + if (options.kind) { + conditions.push("record_kind = ?"); + params.push(options.kind); } - if (event.revision) { - return db.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(sourceId, event.revision).map((row) => row.id); + if (options.status) { + conditions.push("status = ?"); + params.push(options.status); } - if (event.hash) { - return db.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all(sourceId, event.hash).map((row) => row.id); + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const db = openKnowledgeDb(dbPath); + try { + return db.query(`SELECT * FROM durable_knowledge_records + ${conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...params, limit).map(asDurableRecord); + } finally { + db.close(); } - return db.query("SELECT id FROM source_revisions WHERE source_id = ?").all(sourceId).map((row) => row.id); } -function invalidateRevision(db, revisionId) { - const chunks = db.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(revisionId); - let embeddingsDeleted = 0; - let vectorEntriesDeleted = 0; - for (const chunk of chunks) { - const row = db.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(chunk.id); - embeddingsDeleted += row?.n ?? 0; - const vectorRow = db.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(chunk.id); - vectorEntriesDeleted += vectorRow?.n ?? 0; - db.run("DELETE FROM vector_index_entries WHERE chunk_id = ?", [chunk.id]); - db.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?", [chunk.id]); - db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [chunk.id]); - } - db.run("DELETE FROM chunks WHERE source_revision_id = ?", [revisionId]); - const revision = db.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get(revisionId); - db.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?", [mergeJson(revision?.metadata_json, { reindex_required: true, invalidated_at: new Date().toISOString() }), revisionId]); - return { chunksDeleted: chunks.length, embeddingsDeleted, vectorEntriesDeleted }; + +// src/reindex.ts +import { createHash as createHash15, randomUUID as randomUUID10 } from "crypto"; +function stableId8(prefix, value) { + return `${prefix}_${createHash15("sha256").update(value).digest("hex").slice(0, 20)}`; } -function isDeleteEvent(eventType2, status) { - return status === "deleted" || ["delete", "deleted", "remove", "removed"].includes(eventType2); +function queueCounts(dbPath) { + const db = openKnowledgeDb(dbPath); + try { + const rows = db.query(`SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status`).all(); + return Object.fromEntries(rows.map((row) => [row.status, row.n])); + } finally { + db.close(); + } } -function isMoveEvent(eventType2) { - return ["move", "moved", "rename", "renamed", "path_changed", "canonical_key_changed"].includes(eventType2); +function missingEmbeddingRows(dbPath, options) { + const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); + const parsed = parseModelRef(modelRef); + const db = openKnowledgeDb(dbPath); + try { + return db.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri + FROM chunks c + LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id + LEFT JOIN sources s ON s.id = sr.source_id + LEFT JOIN vector_index_entries v ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? + WHERE v.id IS NULL + ORDER BY c.created_at ASC, c.ordinal ASC`).all(parsed.provider, parsed.model); + } finally { + db.close(); + } } -function isPermissionEvent(eventType2) { - return ["permission", "permissions", "permission_changed", "acl_changed", "acl_revoked"].includes(eventType2); +function reindexHealth(options) { + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + try { + const version2 = db.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version ?? 0; + const chunks = db.query("SELECT COUNT(*) AS n FROM chunks").get()?.n ?? 0; + const vectorEntries = db.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n ?? 0; + const missing = missingEmbeddingRows(options.dbPath, options).length; + const stale = db.query(`SELECT COUNT(*) AS n FROM source_revisions + WHERE metadata_json LIKE '%"reindex_required":true%' OR metadata_json LIKE '%"status":"stale"%'`).get()?.n ?? 0; + return { + schema_version: version2, + chunks, + vector_entries: vectorEntries, + missing_embeddings: missing, + queued: queueCounts(options.dbPath), + stale_revisions: stale + }; + } finally { + db.close(); + } } -async function consumeOpenFilesOutbox(options) { - const now = (options.now ?? new Date).toISOString(); - if (options.safetyPolicy) - assertWriteAllowed(options.dbPath, options.safetyPolicy); +function enqueueMissingEmbeddings(options) { migrateKnowledgeDb(options.dbPath); - const text = await readOutboxInput(options.input, options.config, options.safetyPolicy); - const events = parseOutboxText(text); + const now = (options.now ?? new Date).toISOString(); + const reason = options.reason ?? "missing_embedding"; + const rows = missingEmbeddingRows(options.dbPath, options); const db = openKnowledgeDb(options.dbPath); - const runId = `run_${randomUUID9()}`; + let enqueued = 0; + let alreadyQueued = 0; try { - return db.transaction(() => { - db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - runId, - "open-files-outbox", - options.input, - "completed", - "local", - "open-files-outbox", - JSON.stringify({ path: options.input, events: events.length }), - now, - now - ]); - const sourcesTouched = new Set; - const revisionsTouched = new Set; - let chunksDeleted = 0; - let embeddingsDeleted = 0; - let vectorEntriesDeleted = 0; - let staleRevisions = 0; - let deletedSources = 0; - let movedSources = 0; - let permissionUpdates = 0; - recordAuditEvent(db, { - event_type: "source_read", - action: options.input.startsWith("s3://") ? "s3_outbox_read" : "local_outbox_read", - target_uri: options.input, - decision: "allow", - metadata: { events: events.length, read_only: true }, - created_at: now - }); - events.forEach((raw, index) => { - const event = normalizeEvent(raw, now); - const sourceId = ensureSource(db, event, now); - sourcesTouched.add(sourceId); - const createdRevisionId = ensureRevision(db, sourceId, event, now); - if (createdRevisionId) - revisionsTouched.add(createdRevisionId); - const affectedRevisionIds = revisionIdsForEvent(db, sourceId, event); - for (const revisionId of affectedRevisionIds) { - revisionsTouched.add(revisionId); - const invalidation = invalidateRevision(db, revisionId); - chunksDeleted += invalidation.chunksDeleted; - embeddingsDeleted += invalidation.embeddingsDeleted; - vectorEntriesDeleted += invalidation.vectorEntriesDeleted; - staleRevisions += 1; + const write = db.transaction(() => { + for (const row of rows) { + const id = stableId8("rq", `embedding\x00${row.chunk_id}\x00${reason}`); + const before = db.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding", row.chunk_id, reason); + if (before) { + alreadyQueued += 1; + continue; } - if (isDeleteEvent(event.eventType, event.status)) - deletedSources += 1; - if (isMoveEvent(event.eventType)) - movedSources += 1; - if (isPermissionEvent(event.eventType) || event.acl !== undefined) - permissionUpdates += 1; - db.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, [ - stableId6("evt", `${runId}\x00${index}\x00${event.sourceRef}\x00${event.eventType}`), - runId, - "info", - event.eventType, - JSON.stringify({ - source_ref: event.sourceRef, - source_uri: event.sourceUri, - revision: event.revision, - hash: event.hash, - status: event.status, - affected_revisions: affectedRevisionIds.length - }), - event.updatedAt + db.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + id, + "embedding", + row.chunk_id, + row.source_uri, + reason, + "pending", + JSON.stringify({ source_revision_id: row.source_revision_id }), + now, + now ]); - }); - db.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`, [ - stableId6("usage", runId), - runId, - "local", - "open-files-outbox", - JSON.stringify({ note: "No model provider used for outbox invalidation." }), - now - ]); - recordAuditEvent(db, { - event_type: "write", - action: "knowledge_outbox_invalidation", - target_uri: options.dbPath, - decision: "allow", - metadata: { - run_id: runId, - events: events.length, - sources: sourcesTouched.size, - revisions: revisionsTouched.size, - chunks_deleted: chunksDeleted, - embeddings_deleted: embeddingsDeleted, - vector_entries_deleted: vectorEntriesDeleted - }, - created_at: now - }); - return { - path: options.input, - db_path: options.dbPath, - run_id: runId, - events_seen: events.length, - sources_touched: sourcesTouched.size, - revisions_touched: revisionsTouched.size, - chunks_deleted: chunksDeleted, - embeddings_deleted: embeddingsDeleted, - vector_entries_deleted: vectorEntriesDeleted, - stale_revisions: staleRevisions, - deleted_sources: deletedSources, - moved_sources: movedSources, - permission_updates: permissionUpdates - }; - })(); + enqueued += 1; + } + }); + write(); + } finally { + db.close(); + } + return { enqueued, already_queued: alreadyQueued, reason }; +} +function clearEmbeddingIndex(dbPath) { + const db = openKnowledgeDb(dbPath); + try { + const embeddings = db.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n ?? 0; + const vectorEntries = db.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n ?? 0; + db.run("DELETE FROM vector_index_entries"); + db.run("DELETE FROM chunk_embeddings"); + return { embeddings, vectorEntries }; + } finally { + db.close(); + } +} +function completeIndexedQueueItems(dbPath, options, now) { + const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); + const parsed = parseModelRef(modelRef); + const db = openKnowledgeDb(dbPath); + try { + const result = db.run(`UPDATE reindex_queue + SET status = ?, updated_at = ? + WHERE kind = ? + AND status = ? + AND EXISTS ( + SELECT 1 FROM vector_index_entries v + WHERE v.chunk_id = reindex_queue.target_id + AND v.provider = ? + AND v.model = ? + )`, ["completed", now, "embedding", "pending", parsed.provider, parsed.model]); + return result.changes; } finally { db.close(); } } - -// src/machines.ts -import { spawnSync } from "child_process"; -import { hostname as hostname4, platform, userInfo } from "os"; -var KNOWLEDGE_MACHINES_ADAPTER_CONTRACT_VERSION = 1; -var KNOWLEDGE_MACHINES_ADAPTER_PACKAGE = "@hasna/machines"; -var KNOWLEDGE_MACHINES_ADAPTER_ENTRYPOINT = "@hasna/machines/consumer"; -function asString3(value) { - return typeof value === "string" && value.length > 0 ? value : null; +async function refreshEmbeddingIndex(options) { + migrateKnowledgeDb(options.dbPath); + const now = (options.now ?? new Date).toISOString(); + const runId = `run_${randomUUID10()}`; + const deleted = options.full ? clearEmbeddingIndex(options.dbPath) : { embeddings: 0, vectorEntries: 0 }; + const queued = enqueueMissingEmbeddings({ ...options, reason: options.full ? "full_embedding_rebuild" : "missing_embedding" }); + const db = openKnowledgeDb(options.dbPath); + try { + db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + runId, + "embedding-refresh", + options.full ? "full" : "incremental", + "running", + "local", + resolveEmbeddingModelRef(options.modelRef, options.config), + JSON.stringify({ full: options.full === true, queued }), + now, + now + ]); + } finally { + db.close(); + } + const indexed = await indexKnowledgeEmbeddings({ + dbPath: options.dbPath, + config: options.config, + env: options.env, + modelRef: options.modelRef, + dimensions: options.dimensions, + fake: options.fake, + limit: options.limit, + now: options.now + }); + const completedQueueItems = completeIndexedQueueItems(options.dbPath, options, now); + const doneDb = openKnowledgeDb(options.dbPath); + try { + doneDb.run(`UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?`, [ + "completed", + JSON.stringify({ full: options.full === true, queued, indexed, completed_queue_items: completedQueueItems }), + now, + runId + ]); + doneDb.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, [ + `evt_${randomUUID10()}`, + runId, + "info", + "embedding_refresh_completed", + JSON.stringify({ queued, indexed, completed_queue_items: completedQueueItems }), + now + ]); + } finally { + doneDb.close(); + } + return { + run_id: runId, + full: options.full === true, + deleted_embeddings: deleted.embeddings, + deleted_vector_entries: deleted.vectorEntries, + queued, + indexed, + completed_queue_items: completedQueueItems + }; +} + +// src/rules-provenance.ts +import { createHash as createHash16 } from "crypto"; +import { existsSync as existsSync11, lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync13, statSync as statSync3 } from "fs"; +import { basename as basename5, extname as extname2, join as join7, relative as relative4, resolve as resolve4, sep as sep4 } from "path"; +import { pathToFileURL as pathToFileURL3 } from "url"; +var DEFAULT_MAX_ITEMS2 = 100; +var DEFAULT_EVIDENCE_LIMIT = 25; +var DEFAULT_MAX_BYTES_PER_FILE = 256 * 1024; +var WALK_MAX_DEPTH = 5; +var TEXT_EXTENSIONS = new Set([".md", ".mdx", ".txt", ".json", ".jsonc", ".toml", ".yaml", ".yml"]); +var ROOT_RULE_DOCS = new Set(["CODEWITH.md", "AGENTS.md", "CLAUDE.md", "RULES.md", "INSTRUCTIONS.md"]); +var SKIP_DIRECTORIES = new Set([ + ".git", + "node_modules", + "dist", + "build", + ".codewith-worktrees", + ".connect", + ".secrets", + ".tmp", + "tmp", + "auth_profiles", + "profiles", + "preserved", + "backup", + "backups", + "cache", + "logs", + "runs" +]); +var SENSITIVE_PATH_RE = /(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i; +var SELECTED_PROMPT_OR_PLAN_RE = /(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i; +function sha256Text2(text) { + return `sha256:${createHash16("sha256").update(text).digest("hex")}`; +} +function sha256Bytes(bytes) { + return `sha256:${createHash16("sha256").update(bytes).digest("hex")}`; } -function asStringArray(value) { - return Array.isArray(value) ? value.filter((item) => typeof item === "string") : []; +function normalizePath(value) { + return value.split(sep4).join("/"); } -function asRecord(value) { - return value && typeof value === "object" && !Array.isArray(value) ? value : {}; +function relativePath(root, absPath) { + const rel = relative4(root, absPath); + return rel ? normalizePath(rel) : basename5(absPath); } -function asBooleanOrNull(value) { - return typeof value === "boolean" ? value : null; +function isTextSource(path) { + return TEXT_EXTENSIONS.has(extname2(path).toLowerCase()); } -function asNumberOrNull(value) { - return typeof value === "number" && Number.isFinite(value) ? value : null; +function hasSensitivePathPart(path) { + return normalizePath(path).split("/").some((part) => SENSITIVE_PATH_RE.test(part)); } -function normalizePlatform(value = platform()) { - const normalized = value.toLowerCase(); - if (normalized === "darwin" || normalized === "macos") - return "macos"; - if (normalized === "win32" || normalized === "windows") - return "windows"; - if (normalized === "linux") - return "linux"; - return value; +function boundedPreview(text, max = 220) { + const normalized = text.normalize("NFKC").trim().replace(/\s+/g, " "); + if (normalized.length <= max) + return normalized; + return `${normalized.slice(0, Math.max(0, max - 1)).trim()}...`; } -function defaultRunner(command) { - const result = spawnSync("bash", ["-c", command], { - encoding: "utf8", - env: process.env - }); +function lineCount(text) { + if (!text) + return 0; + return text.split(/\r\n|\n|\r/).length; +} +function citationFor2(input) { return { - stdout: result.stdout || "", - stderr: result.stderr || "", - exitCode: result.status ?? 1 + source_ref: input.sourceRef, + source_path: input.sourcePath, + line_start: input.lineCount > 0 ? 1 : 0, + line_end: input.lineCount, + content_hash: input.contentHash }; } -async function runCommand(runner, command) { - return await runner(command); -} -async function hasCommand(command, runner) { - const result = await runCommand(runner, `command -v ${command} >/dev/null 2>&1`); - return result.exitCode === 0; +function ruleSpecs() { + return [ + { + base: ".", + maxDepth: 0, + spec: { + family: "rule_doc", + owner: "repository", + scope: "global", + precedence: { rank: 10, label: "root-rule-doc" }, + tags: ["global-rules", "rule-doc"], + include: (path) => ROOT_RULE_DOCS.has(path) + } + }, + { + base: ".codewith", + spec: { + family: "codewith", + owner: "codewith", + scope: "global", + precedence: { rank: 20, label: "codewith" }, + tags: ["global-rules", "codewith", "agent-instructions"], + include: (path) => { + const normalized = normalizePath(path); + const name = basename5(normalized); + if (ROOT_RULE_DOCS.has(name) || normalized === "config.toml") + return true; + if (normalized.endsWith("/SKILL.md")) + return true; + if (/^(rules|instructions|prompts|plans)\//.test(normalized) && isTextSource(normalized)) + return true; + return false; + } + } + }, + { + base: ".claude", + spec: { + family: "claude", + owner: "claude", + scope: "global", + precedence: { rank: 30, label: "claude-rules" }, + tags: ["global-rules", "claude", "agent-instructions"], + include: (path) => { + const normalized = normalizePath(path); + return normalized === "CLAUDE.md" || /^rules\//.test(normalized) && isTextSource(normalized); + } + } + }, + { + base: ".codex", + spec: { + family: "codex", + owner: "codex", + scope: "global", + precedence: { rank: 40, label: "codex" }, + tags: ["global-rules", "codex", "agent-instructions"], + include: (path) => { + const normalized = normalizePath(path); + const name = basename5(normalized); + if (ROOT_RULE_DOCS.has(name) || name === "config.toml") + return true; + return /^(rules|instructions|prompts)\//.test(normalized) && isTextSource(normalized); + } + } + }, + { + base: ".opencode", + spec: { + family: "opencode", + owner: "opencode", + scope: "global", + precedence: { rank: 50, label: "opencode" }, + tags: ["global-rules", "opencode", "agent-instructions"], + include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) + } + }, + { + base: ".", + maxDepth: 0, + spec: { + family: "opencode", + owner: "opencode", + scope: "global", + precedence: { rank: 50, label: "opencode-config" }, + tags: ["global-rules", "opencode", "config"], + include: (path) => ["opencode.json", "opencode.jsonc", "opencode.toml", "opencode.yaml", "opencode.yml"].includes(path) + } + }, + { + base: ".hasna/prompts", + spec: { + family: "prompt", + owner: "hasna", + scope: "global", + precedence: { rank: 60, label: "selected-prompts" }, + tags: ["global-rules", "prompt"], + include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) + } + }, + { + base: ".hasna/plans", + spec: { + family: "plan", + owner: "hasna", + scope: "global", + precedence: { rank: 65, label: "selected-plans" }, + tags: ["global-rules", "plan"], + include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) + } + }, + { + base: "docs", + spec: { + family: "rule_doc", + owner: "repository", + scope: "global", + precedence: { rank: 70, label: "rule-docs" }, + tags: ["global-rules", "rule-doc"], + include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) + } + } + ]; } -function parseTailscaleStatus(raw) { - try { - const parsed = JSON.parse(raw); - if (!parsed || typeof parsed !== "object") - return null; - return parsed; - } catch { - return null; +function collectFiles(root, skipped) { + const candidates = new Map; + for (const entry of ruleSpecs()) { + const basePath = resolve4(root, entry.base); + if (!existsSync11(basePath)) + continue; + const rootStats = statSync3(basePath); + if (rootStats.isFile()) { + const rel = basename5(basePath); + if (entry.spec.include(rel)) { + candidates.set(basePath, { + ...entry.spec, + absPath: basePath + }); + } + continue; + } + walkRuleDirectory({ + basePath, + depth: 0, + maxDepth: entry.maxDepth ?? WALK_MAX_DEPTH, + spec: entry.spec, + candidates, + skipped + }); } + return [...candidates.values()].sort((a, b) => { + if (a.precedence.rank !== b.precedence.rank) + return a.precedence.rank - b.precedence.rank; + return a.absPath.localeCompare(b.absPath); + }); } -function peerKey(peer) { - if (!peer) - return null; - return peer.HostName ?? peer.DNSName?.split(".")[0] ?? null; -} -async function loadTailscalePeers(runner, warnings) { - const peers = new Map; - if (!await hasCommand("tailscale", runner)) { - warnings.push("tailscale_not_available"); - return { peers, selfKey: null }; - } - const result = await runCommand(runner, "tailscale status --json"); - if (result.exitCode !== 0) { - warnings.push(`tailscale_status_failed:${result.stderr.trim() || result.exitCode}`); - return { peers, selfKey: null }; - } - const status = parseTailscaleStatus(result.stdout); - if (!status) { - warnings.push("tailscale_status_invalid_json"); - return { peers, selfKey: null }; +function walkRuleDirectory(input) { + const rootBasePath = input.rootBasePath ?? input.basePath; + if (input.depth > input.maxDepth) + return; + for (const dirent of readdirSync2(input.basePath, { withFileTypes: true })) { + const absPath = join7(input.basePath, dirent.name); + const rel = relativePath(rootBasePath, absPath); + if (dirent.isSymbolicLink()) + continue; + if (dirent.isDirectory()) { + if (SKIP_DIRECTORIES.has(dirent.name)) { + continue; + } + if (hasSensitivePathPart(rel)) { + input.skipped.push({ source_family: input.spec.family, source_path: absPath, reason: "sensitive_path" }); + continue; + } + walkRuleDirectory({ + ...input, + rootBasePath, + basePath: absPath, + depth: input.depth + 1 + }); + continue; + } + if (!dirent.isFile()) + continue; + const sourceRelativePath = relativePath(resolve4(rootBasePath), absPath); + if (hasSensitivePathPart(sourceRelativePath)) { + input.skipped.push({ source_family: input.spec.family, source_path: absPath, reason: "sensitive_path" }); + continue; + } + if (!input.spec.include(sourceRelativePath)) + continue; + if (!isTextSource(absPath)) + continue; + input.candidates.set(absPath, { + ...input.spec, + absPath + }); } - const addPeer = (peer) => { - const key = peerKey(peer); - if (key && peer) - peers.set(key, peer); - }; - addPeer(status.Self); - for (const peer of Object.values(status.Peer ?? {})) - addPeer(peer); - return { peers, selfKey: peerKey(status.Self) }; } -function localMachineId(fallback) { - return process.env.HASNA_MACHINE_ID ?? process.env.OPEN_MACHINES_MACHINE_ID ?? process.env.MACHINE_ID ?? fallback ?? hostname4(); +function legacyRuleLike(item) { + const tags = (item.tags ?? []).map((tag) => tag.toLowerCase()); + if (tags.some((tag) => ["rule", "rules", "agent", "instructions", "global-rules", "global-agent-rules"].includes(tag))) { + return true; + } + const haystack = `${item.title} +${item.content.slice(0, 500)}`.toLowerCase(); + return /\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(haystack); } -function buildLocalEntry(input) { - const local = input.machineId === input.localMachineId || input.machineId === hostname4(); - const dnsName = input.peer?.DNSName?.replace(/\.$/, "") ?? null; - const tailscaleTarget = dnsName ?? input.peer?.TailscaleIPs?.[0] ?? null; - const hints = []; - if (local) - hints.push({ kind: "local", target: "localhost", reachable: true }); - if (tailscaleTarget) - hints.push({ kind: "tailscale", target: tailscaleTarget, reachable: input.peer?.Online ?? null }); - const selectedRoute = hints.find((hint) => hint.kind === "local") ?? hints.find((hint) => hint.kind === "tailscale") ?? null; +function manifestItemForRecord(record2, text) { + const ruleProvenance = { + source_path: record2.source_path, + source_path_ref: record2.source_path_ref, + source_ref: record2.source_ref, + owner: record2.owner, + scope: record2.scope, + precedence: record2.precedence, + source_hash: record2.source_hash, + content_hash: record2.content_hash, + discovered_at: record2.discovered_at, + tags: record2.tags, + redaction_status: record2.redaction_status, + citations: record2.citations + }; return { - machine_id: input.machineId, - hostname: input.peer?.HostName ?? (local ? hostname4() : input.machineId), - local, - platform: input.peer?.OS ? normalizePlatform(input.peer.OS) : local ? normalizePlatform() : null, - os: input.peer?.OS ?? (local ? platform() : null), - user: local ? userInfo().username : null, - workspace_path: null, - manifest_declared: false, - heartbeat_status: "unknown", - last_heartbeat_at: null, - tailscale: { - dns_name: dnsName, - ips: input.peer?.TailscaleIPs ?? [], - online: input.peer?.Online ?? null, - active: input.peer?.Active ?? null, - last_seen: input.peer?.LastSeen ?? null - }, - ssh: { - address: null, - route: selectedRoute?.kind === "local" ? "local" : selectedRoute?.kind === "tailscale" ? "tailscale" : "unknown", - command_target: selectedRoute?.target ?? null + source_ref: record2.source_ref, + name: record2.title, + mime: "text/markdown", + size: Buffer.byteLength(text), + hash: record2.content_hash, + revision: record2.content_hash, + status: "active", + updated_at: record2.discovered_at, + permissions: { + mode: "read_only", + allowed_purposes: ["knowledge_index", "knowledge_answer", "agent_context"] }, - route_hints: hints, - tags: [], - metadata: {}, - source: "local" + rule_provenance: ruleProvenance, + source_family: record2.source_family, + source_path_ref: record2.source_path_ref, + owner: record2.owner, + scope: record2.scope, + precedence: record2.precedence, + tags: record2.tags, + redaction_status: record2.redaction_status, + legacy_json_id: record2.legacy_json_id ?? null, + extracted_text: text }; } -function normalizeRouteHints(value) { - if (!Array.isArray(value)) - return []; - return value.map((entry) => { - const record2 = asRecord(entry); - const kind = asString3(record2.kind) ?? "unknown"; - const routeKind = kind === "local" || kind === "lan" || kind === "tailscale" || kind === "ssh" ? kind : "unknown"; - return { - kind: routeKind, - target: asString3(record2.target) ?? "", - reachable: asBooleanOrNull(record2.reachable) +function prepareFileRecord(input) { + const stats = lstatSync2(input.candidate.absPath); + const sourcePath = input.candidate.absPath; + const sourcePathRef = relativePath(input.root, sourcePath); + if (stats.size > input.maxBytesPerFile) { + const sourceRef2 = pathToFileURL3(sourcePath).href; + const evidence2 = { + source_family: input.candidate.family, + title: basename5(sourcePath), + source_path: sourcePath, + source_path_ref: sourcePathRef, + source_ref: sourceRef2, + owner: input.candidate.owner, + scope: input.candidate.scope, + precedence: input.candidate.precedence, + source_hash: "sha256:skipped-too-large", + content_hash: "sha256:skipped-too-large", + discovered_at: input.discoveredAt, + tags: [...input.candidate.tags, "skipped"], + redaction_status: "refused", + redactions: [], + citations: [], + bytes: stats.size, + line_count: 0, + importable: false, + skipped_reason: "max_bytes_exceeded", + preview: null }; - }).filter((entry) => entry.target.length > 0); -} -function normalizeOpenMachinesEntry(entry, localMachineId2) { - const machineId = asString3(entry.machine_id) ?? asString3(entry.hostname) ?? "unknown"; - const tailscale = asRecord(entry.tailscale); - const ssh = asRecord(entry.ssh); - const heartbeatStatus = asString3(entry.heartbeat_status); - const route = asString3(ssh.route); + return { evidence: evidence2, text: "", manifest: null }; + } + const bytes = readFileSync13(sourcePath); + const rawText = bytes.toString("utf8"); + const redacted = redactSecrets(rawText, input.safetyPolicy); + const highSeverity = redacted.findings.some((finding) => finding.severity === "high"); + const redactionStatus = highSeverity ? "refused" : redacted.findings.length > 0 ? "redacted" : "clean"; + const contentHash = sha256Text2(redacted.text); + const sourceRef = pathToFileURL3(sourcePath).href; + const lines = lineCount(redacted.text); + const evidence = { + source_family: input.candidate.family, + title: basename5(sourcePath), + source_path: sourcePath, + source_path_ref: sourcePathRef, + source_ref: sourceRef, + owner: input.candidate.owner, + scope: input.candidate.scope, + precedence: input.candidate.precedence, + source_hash: sha256Bytes(bytes), + content_hash: contentHash, + discovered_at: input.discoveredAt, + tags: [...input.candidate.tags], + redaction_status: redactionStatus, + redactions: redacted.findings.map((finding) => ({ type: finding.type, severity: finding.severity })), + citations: [citationFor2({ sourceRef, sourcePath, lineCount: lines, contentHash })], + bytes: bytes.byteLength, + line_count: lines, + importable: redactionStatus !== "refused", + skipped_reason: redactionStatus === "refused" ? "secret_refused" : null, + preview: redactionStatus === "refused" ? null : boundedPreview(redacted.text) + }; return { - machine_id: machineId, - hostname: asString3(entry.hostname), - local: machineId === localMachineId2, - platform: asString3(entry.platform), - os: asString3(entry.os), - user: asString3(entry.user), - workspace_path: asString3(entry.workspace_path), - manifest_declared: entry.manifest_declared === true, - heartbeat_status: heartbeatStatus === "online" || heartbeatStatus === "offline" ? heartbeatStatus : "unknown", - last_heartbeat_at: asString3(entry.last_heartbeat_at), - tailscale: { - dns_name: asString3(tailscale.dns_name), - ips: asStringArray(tailscale.ips), - online: asBooleanOrNull(tailscale.online), - active: asBooleanOrNull(tailscale.active), - last_seen: asString3(tailscale.last_seen) - }, - ssh: { - address: asString3(ssh.address), - route: route === "local" || route === "lan" || route === "tailscale" ? route : "unknown", - command_target: asString3(ssh.command_target) - }, - route_hints: normalizeRouteHints(entry.route_hints), - tags: asStringArray(entry.tags), - metadata: asRecord(entry.metadata), - source: "open-machines" + evidence, + text: redacted.text, + manifest: evidence.importable ? manifestItemForRecord(evidence, redacted.text) : null + }; +} +function prepareLegacyRecord(input) { + const redacted = redactSecrets(input.item.content, input.safetyPolicy); + const highSeverity = redacted.findings.some((finding) => finding.severity === "high"); + const redactionStatus = highSeverity ? "refused" : redacted.findings.length > 0 ? "redacted" : "clean"; + const sourceRef = `open-files://source/legacy-json/path/${encodeURIComponent(input.item.id)}`; + const contentHash = sha256Text2(redacted.text); + const sourceHash = sha256Text2(input.item.content); + const lines = lineCount(redacted.text); + const evidence = { + source_family: "legacy_json", + title: input.item.title, + source_path: input.legacyStorePath, + source_path_ref: `legacy-json:${input.item.id}`, + source_ref: sourceRef, + owner: "legacy-json", + scope: input.scope, + precedence: { rank: 90, label: "legacy-json-note" }, + source_hash: sourceHash, + content_hash: contentHash, + discovered_at: input.discoveredAt, + tags: [...new Set(["global-rules", "legacy-json", ...input.item.tags ?? []])], + redaction_status: redactionStatus, + redactions: redacted.findings.map((finding) => ({ type: finding.type, severity: finding.severity })), + citations: [citationFor2({ sourceRef, sourcePath: input.legacyStorePath, lineCount: lines, contentHash })], + bytes: Buffer.byteLength(input.item.content), + line_count: lines, + importable: redactionStatus !== "refused", + skipped_reason: redactionStatus === "refused" ? "secret_refused" : null, + preview: redactionStatus === "refused" ? null : boundedPreview(redacted.text), + legacy_json_id: input.item.id }; -} -function topologyMessage(source, count3) { - return `${count3} machine${count3 === 1 ? "" : "s"} discovered via ${source}`; -} -function optionalModuleError(error51) { - const message = error51 instanceof Error ? error51.message : String(error51); - return message.includes("Cannot find module '@hasna/machines'") || message.includes("Cannot find module '@hasna/machines/consumer'") ? "module_not_found" : message; -} -function adapterMode(options) { - return options.adapterMode ?? "auto"; -} -function contractVersion(mod) { - const fromContract = mod?.MACHINES_CONSUMER_CONTRACT?.schema_version; - if (typeof fromContract === "number") - return fromContract; - const direct = mod?.MACHINES_CONSUMER_CONTRACT_VERSION; - return typeof direct === "number" ? direct : null; -} -function payloadContractVersion(value) { - return typeof value.schema_version === "number" ? value.schema_version : null; -} -function unsupportedContractVersion(version2) { - return typeof version2 === "number" && version2 > KNOWLEDGE_MACHINES_ADAPTER_CONTRACT_VERSION ? version2 : null; -} -function adapterStatus(input) { return { - package: KNOWLEDGE_MACHINES_ADAPTER_PACKAGE, - entrypoint: KNOWLEDGE_MACHINES_ADAPTER_ENTRYPOINT, - mode: input.mode, - implementation: input.implementation, - contract_version: input.contractVersion ?? null, - available: input.available, - error: input.error ?? null + evidence, + text: redacted.text, + manifest: evidence.importable ? manifestItemForRecord(evidence, redacted.text) : null }; } -function disabledAdapterStatus(mode2, error51 = "adapter_disabled") { - return adapterStatus({ - mode: mode2, - implementation: "disabled", - available: false, - error: error51 - }); -} -function unsupportedContractAdapterStatus(mode2, mod) { - const version2 = unsupportedContractVersion(contractVersion(mod)); - if (!version2) - return null; - return adapterStatus({ - mode: mode2, - implementation: "disabled", - available: false, - error: `unsupported_contract_version:${version2}`, - contractVersion: version2 - }); -} -function cliAdapterStatus(mode2) { - return adapterStatus({ - mode: mode2, - implementation: "cli", - available: true - }); -} -function sdkAdapterStatus(mode2, mod) { - return adapterStatus({ - mode: mode2, - implementation: "sdk", - available: true, - contractVersion: contractVersion(mod) +function deprecateLegacyNotes(input) { + if (!input.legacyStorePath || !existsSync11(input.legacyStorePath)) + return 0; + const byId = new Map(input.records.filter((record2) => record2.legacy_json_id && record2.importable).map((record2) => [record2.legacy_json_id, record2])); + if (byId.size === 0) + return 0; + return withLock(input.legacyStorePath, () => { + const store = loadStoreIfExists(input.legacyStorePath); + if (!store.exists) + return 0; + let deprecated = 0; + for (const item of store.items) { + const record2 = byId.get(item.id); + if (!record2) + continue; + const metadata = item.metadata ?? {}; + item.archived = true; + item.metadata = { + ...metadata, + knowledge_rules_import: { + status: "deprecated_after_source_backed_promotion", + deprecated_at: input.now, + source_ref: record2.source_ref, + source_hash: record2.source_hash, + content_hash: record2.content_hash, + data_loss: false + } + }; + item.tags = [...new Set([...item.tags ?? [], "deprecated:knowledge-rules-import"])]; + item.updated_at = input.now; + deprecated += 1; + } + if (deprecated > 0) + saveStore(input.legacyStorePath, { items: store.items }); + return deprecated; }); } -function parseJson2(value) { - try { - return JSON.parse(value); - } catch { - return null; +async function importRulesProvenance(options = {}) { + const root = resolve4(options.root ?? process.cwd()); + const scope = options.scope ?? "global"; + const owner = options.owner ?? "global-agent-rules-standard"; + const dryRun = options.dryRun !== false; + const discoveredAt = (options.now ?? new Date).toISOString(); + const maxItems = Math.max(1, Math.min(options.maxItems ?? DEFAULT_MAX_ITEMS2, 1000)); + const evidenceLimit = Math.max(1, Math.min(options.limit ?? DEFAULT_EVIDENCE_LIMIT, 100)); + const maxBytesPerFile = Math.max(1024, Math.min(options.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE, 2 * 1024 * 1024)); + const skipped = []; + const files = collectFiles(root, skipped).slice(0, maxItems); + const fileRecords = files.map((candidate) => prepareFileRecord({ + root, + candidate: { + ...candidate, + owner: candidate.owner === "repository" ? owner : candidate.owner, + scope + }, + discoveredAt, + maxBytesPerFile, + safetyPolicy: options.safetyPolicy + })); + const legacyStore = options.includeLegacy === false || !options.legacyStorePath ? { exists: false, items: [] } : loadStoreIfExists(options.legacyStorePath); + const legacyItems = legacyStore.items.filter((item) => item.archived !== true && legacyRuleLike(item)).slice(0, maxItems); + const legacyRecords = legacyItems.map((item) => prepareLegacyRecord({ + item, + legacyStorePath: options.legacyStorePath, + discoveredAt, + scope, + safetyPolicy: options.safetyPolicy + })); + const prepared = [...fileRecords, ...legacyRecords].slice(0, maxItems); + const allEvidence = prepared.map((record2) => record2.evidence); + const importableRecords = prepared.filter((record2) => record2.manifest); + const manifests = importableRecords.map((record2) => record2.manifest); + const refused = allEvidence.filter((record2) => record2.redaction_status === "refused").length; + const evidence = allEvidence.slice(0, evidenceLimit); + const boundedSkipped = skipped.slice(0, evidenceLimit); + let importResult = null; + let deprecated = 0; + if (!dryRun) { + if (!options.dbPath) + throw new Error("rules provenance apply mode requires dbPath."); + if (manifests.length > 0) { + importResult = await ingestOpenFilesManifestItems({ + dbPath: options.dbPath, + items: manifests, + sourceLabel: "knowledge://rules-provenance/global-agent-rules", + readAction: "rules_provenance_import", + allowFileSourceRefs: true, + safetyPolicy: options.safetyPolicy, + now: options.now, + maxItems + }); + } + if (options.deprecateLegacy !== false) { + deprecated = deprecateLegacyNotes({ + legacyStorePath: options.legacyStorePath, + records: allEvidence, + now: discoveredAt + }); + } } -} -function shellQuote(value) { - return `'${value.replace(/'/g, "'\\''")}'`; -} -function machinesCliCommand(args) { - return ["machines", ...args].map(shellQuote).join(" "); -} -function preflightTargetIsLocal(machineId) { - return machineId === "local" || machineId === "localhost" || machineId === hostname4() || machineId === process.env.HASNA_MACHINE_ID || machineId === process.env.OPEN_MACHINES_MACHINE_ID || machineId === process.env.MACHINE_ID; -} -function defaultPreflightRunner(machineId, command) { - const local = preflightTargetIsLocal(machineId); - const shellCommand = local ? command : `ssh ${shellQuote(machineId)} ${shellQuote(command)}`; - const result = spawnSync("bash", ["-c", shellCommand], { - encoding: "utf8", - env: process.env - }); return { - stdout: result.stdout || "", - stderr: result.stderr || "", - exitCode: result.status ?? 1, - source: local ? "local" : "ssh" + ok: refused === 0 || manifests.length > 0 || dryRun, + workflow: "global-rules-provenance-import", + dry_run: dryRun, + writes_performed: !dryRun, + root, + scope, + owner, + discovered_at: discoveredAt, + max_items: maxItems, + evidence_limit: evidenceLimit, + records_seen: allEvidence.length, + records_importable: manifests.length, + records_refused: refused, + records_skipped: skipped.length, + evidence_truncated: allEvidence.length > evidence.length, + skipped_truncated: skipped.length > boundedSkipped.length, + evidence, + skipped: boundedSkipped, + import_result: importResult, + legacy: { + store_path: options.legacyStorePath ?? null, + candidates: legacyItems.length, + promoted: legacyRecords.filter((record2) => record2.manifest).length, + deprecated, + data_loss: false + }, + message: dryRun ? `Discovered ${allEvidence.length} rule source(s); ${manifests.length} importable, ${refused} refused` : `Imported ${importResult?.items_seen ?? 0} rule source(s); ${deprecated} legacy note(s) deprecated` }; } -async function runPreflightCommand(runner, machineId, command) { - return await runner(machineId, command); -} -function preflightStatus(required2, ok) { - if (ok) - return "ok"; - return required2 === false ? "warn" : "fail"; -} -function preflightId(value) { - return value.replace(/[^a-zA-Z0-9_.@/-]+/g, "-").replace(/^-+|-+$/g, ""); -} -function packageCommand(name) { - if (name === "@hasna/knowledge") - return "knowledge"; - if (name === "@hasna/machines") - return "machines"; - return name.split("/").pop() ?? name; + +// src/web-search.ts +import { createHash as createHash17, randomUUID as randomUUID11 } from "crypto"; +function stableHash(value) { + return `sha256:${createHash17("sha256").update(value).digest("hex")}`; } -function firstLine(value) { - return value.trim().split(/\r?\n/).find(Boolean) ?? ""; +function estimateTokens3(text) { + const words = text.trim().split(/\s+/).filter(Boolean).length; + return Math.max(1, Math.ceil(words * 1.25)); } -function extractVersion(value) { - const match = value.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/); - return match?.[0] ?? null; +function asRecord2(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : {}; } -function parseKeyValue(stdout) { - const result = {}; - for (const line of stdout.split(/\r?\n/)) { - const idx = line.indexOf("="); - if (idx <= 0) - continue; - result[line.slice(0, idx)] = line.slice(idx + 1); - } - return result; +function asString4(value) { + return typeof value === "string" && value.length > 0 ? value : null; } -function makePreflightCheck(input) { +function sourceFromRecord(value) { + const record2 = asRecord2(value); + const url2 = asString4(record2.url) ?? asString4(record2.uri) ?? asString4(record2.sourceUrl); + if (!url2) + return null; return { - id: input.id, - kind: input.kind, - status: input.status, - target: input.target, - expected: input.expected ?? null, - actual: input.actual ?? null, - detail: input.detail, - source: input.source + url: url2, + title: asString4(record2.title) ?? asString4(record2.name), + snippet: asString4(record2.snippet) ?? asString4(record2.text) ?? asString4(record2.description), + provider_metadata: record2 }; } -async function inspectPreflightCommand(machineId, spec, runner) { - const script = [ - `cmd=${shellQuote(spec.command)}`, - 'path="$(command -v "$cmd" 2>/dev/null || true)"', - 'printf "path=%s\\n" "$path"', - `if [ -n "$path" ]; then version="$("$cmd" ${spec.versionArgs ?? "--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi` - ].join("; "); - const result = await runPreflightCommand(runner, machineId, script); - const parsed = parseKeyValue(result.stdout); - return { - path: parsed.path || null, - version: parsed.version ? firstLine(parsed.version) : null, - stderr: result.stderr, - source: result.source ?? (preflightTargetIsLocal(machineId) ? "local" : "ssh") - }; +function collectSources(value, output) { + if (Array.isArray(value)) { + for (const entry of value) + collectSources(entry, output); + return; + } + const source = sourceFromRecord(value); + if (source) + output.set(source.url, source); + const record2 = asRecord2(value); + for (const key of ["sources", "results", "citations", "annotations", "output"]) { + if (record2[key]) + collectSources(record2[key], output); + } } -function jsonFieldCommand(field) { - const regex = field === "name" ? String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p` : String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`; - return [ - `if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${field} ?? '')" "$pkg" 2>/dev/null`, - `elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${field} || '')" "$pkg" 2>/dev/null`, - `else sed -n '${regex}' "$pkg" | head -n 1`, - "fi" - ].join("; "); +function fakeSources(query2, limit) { + return Array.from({ length: Math.min(limit, 3) }, (_, index) => ({ + url: `https://example.com/knowledge-web-${index + 1}`, + title: `Fake web source ${index + 1}`, + snippet: `Deterministic web-search fixture for "${query2}"`, + provider_metadata: { fake: true, rank: index + 1 } + })); } -async function inspectPreflightWorkspace(machineId, spec, runner) { - const script = [ - `path=${shellQuote(spec.path)}`, - 'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"', - 'pkg="$path/package.json"', - 'printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"', - `if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${jsonFieldCommand("name")})"; printf "version=%s\\n" "$(${jsonFieldCommand("version")})"; fi` - ].join("; "); - const result = await runPreflightCommand(runner, machineId, script); - const parsed = parseKeyValue(result.stdout); - return { - exists: parsed.exists === "yes", - packageJson: parsed.package_json === "yes", - packageName: parsed.package_name || null, - version: parsed.version || null, - stderr: result.stderr, - source: result.source ?? (preflightTargetIsLocal(machineId) ? "local" : "ssh") - }; +async function openAiWebSearch(input) { + const { generateText } = await import("ai"); + const { createOpenAI } = await import("@ai-sdk/openai"); + const settings = providerSettings(input.config, "openai"); + const openai = createOpenAI({ + apiKey: input.env[settings.api_key_env], + baseURL: settings.base_url + }); + const webSearch = openai.tools?.webSearch; + if (!webSearch) + throw new Error("OpenAI provider does not expose tools.webSearch."); + return generateText({ + model: openai(input.model), + prompt: input.query, + tools: { + web_search: webSearch({ + externalWebAccess: true, + searchContextSize: "medium", + ...input.domains.length > 0 ? { allowedDomains: input.domains } : {} + }) + }, + toolChoice: { type: "tool", toolName: "web_search" } + }); } -async function fallbackCommandChecks(machineId, spec, runner) { - const inspection = await inspectPreflightCommand(machineId, spec, runner); - const found = Boolean(inspection.path); - const checks3 = [ - makePreflightCheck({ - id: `command:${preflightId(spec.command)}:path`, - kind: "command", - status: preflightStatus(spec.required, found), - target: spec.command, - expected: "available", - actual: inspection.path ?? "missing", - detail: found ? `found at ${inspection.path}` : inspection.stderr || "command missing", - source: inspection.source - }) - ]; - if (spec.expectedVersion) { - const actualVersion = extractVersion(inspection.version ?? ""); - checks3.push(makePreflightCheck({ - id: `command:${preflightId(spec.command)}:version`, - kind: "command", - status: actualVersion === spec.expectedVersion ? "ok" : preflightStatus(spec.required, false), - target: spec.command, - expected: spec.expectedVersion, - actual: actualVersion ?? inspection.version ?? "missing", - detail: actualVersion ? `version output: ${inspection.version}` : "version unavailable", - source: inspection.source - })); - } - return checks3; +async function anthropicWebSearch(input) { + const { generateText } = await import("ai"); + const { createAnthropic } = await import("@ai-sdk/anthropic"); + const settings = providerSettings(input.config, "anthropic"); + const anthropic = createAnthropic({ + apiKey: input.env[settings.api_key_env], + baseURL: settings.base_url + }); + const factory = anthropic.tools?.webSearch_20250305 ?? anthropic.tools?.webSearch; + if (!factory) + throw new Error("Anthropic provider does not expose a web search tool."); + return generateText({ + model: anthropic(input.model), + prompt: input.query, + tools: { + web_search: factory({ + maxUses: input.maxUses, + ...input.domains.length > 0 ? { allowedDomains: input.domains } : {} + }) + } + }); } -async function fallbackPackageChecks(machineId, spec, runner) { - const command = spec.command ?? packageCommand(spec.name); - const inspection = await inspectPreflightCommand(machineId, { command, expectedVersion: spec.expectedVersion, required: spec.required }, runner); - const found = Boolean(inspection.path); - const checks3 = [ - makePreflightCheck({ - id: `package:${preflightId(spec.name)}:command`, - kind: "package", - status: preflightStatus(spec.required, found), - target: spec.name, - expected: command, - actual: inspection.path ?? "missing", - detail: found ? `${command} found at ${inspection.path}` : `${command} command missing`, - source: inspection.source - }) - ]; - if (spec.expectedVersion) { - const actualVersion = extractVersion(inspection.version ?? ""); - checks3.push(makePreflightCheck({ - id: `package:${preflightId(spec.name)}:version`, - kind: "package", - status: actualVersion === spec.expectedVersion ? "ok" : preflightStatus(spec.required, false), - target: spec.name, - expected: spec.expectedVersion, - actual: actualVersion ?? inspection.version ?? "missing", - detail: actualVersion ? `version output: ${inspection.version}` : "version unavailable", - source: inspection.source - })); - } - return checks3; +async function fileWebSources(options, sources, now) { + if (!options.fileResults || sources.length === 0) + return 0; + const items = sources.map((source) => { + const text = [source.title, source.snippet, source.url].filter(Boolean).join(` +`); + const hash2 = stableHash(text); + return { + source_ref: source.url, + name: source.title ?? source.url, + url: source.url, + mime: "text/plain", + hash: hash2, + revision: hash2, + status: "active", + updated_at: now, + permissions: { mode: "read_only", allowed_purposes: ["knowledge_answer", "knowledge_index"] }, + metadata: { + source_ref: source.url, + content_source: "provider_web_search", + provider_metadata: source.provider_metadata + }, + extracted_text: text + }; + }); + const result = await ingestOpenFilesManifestItems({ + dbPath: options.dbPath, + items, + sourceLabel: `web-search:${options.query}`, + readAction: "provider_web_search_file_results", + safetyPolicy: options.safetyPolicy, + now: new Date(now) + }); + return result.sources_upserted; } -async function fallbackWorkspaceChecks(machineId, spec, runner) { - const inspection = await inspectPreflightWorkspace(machineId, spec, runner); - const target = spec.label ?? spec.path; - const checks3 = [ - makePreflightCheck({ - id: `workspace:${preflightId(target)}:path`, - kind: "workspace", - status: preflightStatus(spec.required, inspection.exists), - target, - expected: spec.path, - actual: inspection.exists ? "exists" : "missing", - detail: inspection.exists ? `workspace exists at ${spec.path}` : inspection.stderr || `workspace missing at ${spec.path}`, - source: inspection.source - }) - ]; - if (spec.expectedPackageName) { - checks3.push(makePreflightCheck({ - id: `workspace:${preflightId(target)}:package-name`, - kind: "workspace", - status: inspection.packageName === spec.expectedPackageName ? "ok" : preflightStatus(spec.required, false), - target, - expected: spec.expectedPackageName, - actual: inspection.packageName ?? (inspection.packageJson ? "missing-name" : "missing-package-json"), - detail: inspection.packageJson ? "package.json inspected" : "package.json missing", - source: inspection.source - })); +async function runProviderWebSearch(options) { + const query2 = options.query.trim(); + if (!query2) + throw new Error("Web search query is required."); + const env = options.env ?? process.env; + const now = (options.now ?? new Date).toISOString(); + const limit = Math.max(1, Math.min(options.limit ?? 5, 20)); + const maxUses = Math.max(1, Math.min(options.maxUses ?? 3, 10)); + const domains = options.domains ?? []; + const modelRef = resolveModelRef(options.modelRef ?? (options.provider ? `${options.provider}:${providerSettings(options.config, options.provider).default_model}` : "default"), options.config); + const parsed = parseModelRef(modelRef); + const provider = options.provider ?? parsed.provider; + const model = parsed.provider === provider ? parsed.model : providerSettings(options.config, provider).default_model; + const runId = `run_${randomUUID11()}`; + if (!options.fake && options.safetyPolicy) + assertWebSearchAllowed(options.safetyPolicy); + if (!options.fake && provider !== "openai" && provider !== "anthropic") { + throw new Error(`Provider ${provider} does not expose native web search yet.`); } - if (spec.expectedVersion) { - checks3.push(makePreflightCheck({ - id: `workspace:${preflightId(target)}:version`, - kind: "workspace", - status: inspection.version === spec.expectedVersion ? "ok" : preflightStatus(spec.required, false), - target, - expected: spec.expectedVersion, - actual: inspection.version ?? (inspection.packageJson ? "missing-version" : "missing-package-json"), - detail: inspection.packageJson ? "package.json inspected" : "package.json missing", - source: inspection.source - })); + if (!options.fake) + assertProviderCredentials(provider, options.config, env); + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + try { + db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + runId, + "provider-web-search", + query2, + "running", + provider, + model, + JSON.stringify({ domains, max_uses: maxUses, fake: options.fake === true }), + now, + now + ]); + recordAuditEvent(db, { + event_type: "source_read", + action: options.fake ? "fake_provider_web_search" : "provider_web_search", + target_uri: query2, + decision: "allow", + metadata: { provider, model, domains, max_uses: maxUses }, + created_at: now + }); + } finally { + db.close(); } - return checks3; -} -function withKnowledgeContext(topology, options) { - return { - ...topology, - knowledge: { - scope: options.knowledge?.scope ?? "global", - app_path: HASNA_KNOWLEDGE_APP_PATH, - workspace_home: options.knowledge?.workspace_home ?? null - }, - message: topologyMessage(topology.source, topology.machines.length) - }; -} -async function loadOpenMachinesModule() { + let answer = ""; + let sources = []; + let usage = { input_tokens: estimateTokens3(query2), output_tokens: 0, cost_usd: 0 }; + const warnings = []; + if (options.fake) { + sources = fakeSources(query2, limit); + answer = `Fake web search answer for: ${query2}`; + usage.output_tokens = estimateTokens3(answer); + } else { + const result = provider === "openai" ? await openAiWebSearch({ query: query2, model, config: options.config, env, maxUses, domains }) : await anthropicWebSearch({ query: query2, model, config: options.config, env, maxUses, domains }); + answer = result.text; + const collected = new Map; + collectSources(result.sources, collected); + collectSources(result.toolResults, collected); + sources = Array.from(collected.values()).slice(0, limit); + const normalized = normalizeAiSdkUsage({ + provider, + model, + usage: result.usage, + providerMetadata: result.providerMetadata + }); + usage = { + input_tokens: normalized.input_tokens, + output_tokens: normalized.output_tokens, + cost_usd: normalized.cost_usd + }; + } + const filedSources = await fileWebSources(options, sources, now); + const writeDb = openKnowledgeDb(options.dbPath); try { - const specifier = "@hasna/machines/consumer"; - return await import(specifier); - } catch (error51) { - if (optionalModuleError(error51) !== "module_not_found") - throw error51; - const specifier = "@hasna/machines"; - return await import(specifier); + writeDb.run(`UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?`, [ + "completed", + JSON.stringify({ domains, max_uses: maxUses, sources: sources.length, filed_sources: filedSources, fake: options.fake === true }), + now, + runId + ]); + writeDb.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, [ + `evt_${randomUUID11()}`, + runId, + "info", + "provider_web_search_completed", + JSON.stringify({ sources: sources.length, filed_sources: filedSources }), + now + ]); + recordProviderUsage(writeDb, { + run_id: runId, + provider, + model, + input_tokens: usage.input_tokens, + output_tokens: usage.output_tokens, + cost_usd: usage.cost_usd, + metadata: { web_search: true, sources: sources.length, filed_sources: filedSources }, + created_at: now + }); + } finally { + writeDb.close(); } -} -function normalizeOpenMachinesTopology(value, options, adapter) { - const raw = asRecord(value); - if (unsupportedContractVersion(payloadContractVersion(raw))) - return null; - const machines = Array.isArray(raw.machines) ? raw.machines : null; - const localMachine = asString3(raw.local_machine_id); - if (!machines || !localMachine) - return null; - const topology = { - ok: true, - source: "open-machines", - generated_at: asString3(raw.generated_at) ?? (options.now ?? new Date).toISOString(), - local_machine_id: localMachine, - local_hostname: asString3(raw.local_hostname) ?? hostname4(), - current_platform: asString3(raw.current_platform) ?? normalizePlatform(), - machines: machines.map((machine) => normalizeOpenMachinesEntry(machine, localMachine)), - warnings: asStringArray(raw.warnings), - adapter - }; - return withKnowledgeContext(topology, options); -} -function normalizeRouteKind(value) { - return value === "local" || value === "lan" || value === "tailscale" || value === "ssh" || value === "unknown" ? value : null; -} -function normalizeResolverCacheability(value) { - const raw = asRecord(value); - const observedAt = asString3(raw.observed_at); - const sourceAuthority = asString3(raw.source_authority); - if (!observedAt || !sourceAuthority) - return null; + if (sources.length === 0) + warnings.push("no_web_sources_returned"); return { - observed_at: observedAt, - verified_at: asString3(raw.verified_at), - expires_at: asString3(raw.expires_at), - ttl_ms: asNumberOrNull(raw.ttl_ms), - source_authority: sourceAuthority, - confidence: asString3(raw.confidence), - cacheable: raw.cacheable === true, - stale: raw.stale === true, - reasons: asStringArray(raw.reasons) + run_id: runId, + query: query2, + provider, + model, + answer, + sources, + filed_sources: filedSources, + usage, + warnings }; } -function normalizeOpenMachinesRoute(value, adapter) { - const raw = asRecord(value); - if (unsupportedContractVersion(payloadContractVersion(raw))) - return null; - const target = asString3(raw.target) ?? asString3(raw.command_target); - if (raw.ok !== true || !target) - return null; - const evidence = typeof raw.evidence === "object" && raw.evidence !== null ? raw.evidence : null; - const selectedHint = typeof evidence?.selected_hint === "object" && evidence.selected_hint !== null ? evidence.selected_hint : null; - return { - target, - route: normalizeRouteKind(raw.route), - targetKind: normalizeRouteKind(selectedHint?.kind) ?? normalizeRouteKind(raw.source) ?? normalizeRouteKind(raw.route), - confidence: asString3(raw.confidence), - source: "open-machines", - adapter, - evidence, - cacheability: normalizeResolverCacheability(raw.cacheability), - warnings: asStringArray(raw.warnings) - }; + +// src/wiki-compiler.ts +import { createHash as createHash18, randomUUID as randomUUID12 } from "crypto"; +function stableId9(prefix, value) { + return `${prefix}_${createHash18("sha256").update(value).digest("hex").slice(0, 20)}`; } -function pathRecord(value) { - const raw = asRecord(value); +function slugify3(value) { + const slug = value.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80); + return slug || "knowledge-page"; +} +function todayParts(now) { return { - path: asString3(raw.path), - source: asString3(raw.source) ?? "unresolved" + year: String(now.getUTCFullYear()), + month: String(now.getUTCMonth() + 1).padStart(2, "0"), + day: String(now.getUTCDate()).padStart(2, "0") }; } -function normalizeWorkspaceDiagnostics(value) { - if (!Array.isArray(value)) - return []; - return value.flatMap((entry) => { - const raw = asRecord(entry); - const id = asString3(raw.id); - const status = asString3(raw.status); - const severity = asString3(raw.severity); - const message = asString3(raw.message); - if (!id || !status || !severity || !message) - return []; - return [{ - id, - status, - severity, - message, - path: asString3(raw.path), - source: asString3(raw.source) ?? "unknown", - path_exists: asBooleanOrNull(raw.path_exists) - }]; - }); -} -function normalizeWorkspaceRepairHints(value) { - if (!Array.isArray(value)) - return []; - return value.flatMap((entry) => { - const raw = asRecord(entry); - const id = asString3(raw.id); - const reason = asString3(raw.reason); - const command = asStringArray(raw.command); - const shellCommand = asString3(raw.shell_command); - const applyCommand = asStringArray(raw.apply_command); - const applyShellCommand = asString3(raw.apply_shell_command); - if (!id || !reason || !command.length || !shellCommand || !applyCommand.length || !applyShellCommand) - return []; - return [{ - id, - reason, - command, - shell_command: shellCommand, - apply_command: applyCommand, - apply_shell_command: applyShellCommand - }]; - }); -} -function fallbackWorkspaceRepairHints(input) { - const needsRepair = input.projectRootSource === "inferred" || input.openFilesRootSource === "inferred" || input.trustStatus === "untrusted" || input.authStatus === "unknown" || input.warnings.some((warning) => warning.includes("inferred") || warning.includes("untrusted") || warning.includes("unknown_auth") || warning.includes("missing")); - if (!needsRepair) - return []; - const command = [ - "machines", - "workspace", - "repair", - "--machine", - input.requestedMachineId, - "--project", - input.projectId, - "--repo", - input.repoName, - "--open-files-repo", - input.openFilesRepoName ?? "open-files", - "--json" - ]; - const applyCommand = [...command, "--apply"]; - return [{ - id: "machines_workspace_repair", - reason: "Workspace paths or trust metadata need confirmation before remote knowledge sync.", - command, - shell_command: command.map(shellQuote).join(" "), - apply_command: applyCommand, - apply_shell_command: applyCommand.map(shellQuote).join(" ") - }]; +function estimateTokenCount3(text) { + const words = text.trim().split(/\s+/).filter(Boolean).length; + return Math.max(1, Math.ceil(words * 1.25)); } -function normalizeOpenMachinesWorkspace(value, options, adapter) { - const raw = asRecord(value); - if (unsupportedContractVersion(payloadContractVersion(raw))) - return null; - const paths = asRecord(raw.paths); - const project = asRecord(raw.project); - const machine = asRecord(raw.machine); - const projectRoot = pathRecord(paths.project_root); - const workspaceRoot = pathRecord(paths.workspace_root); - const openFilesRoot = pathRecord(paths.open_files_root); - if (raw.ok !== true || !projectRoot.path) - return null; - const evidence = typeof raw.evidence === "object" && raw.evidence !== null ? raw.evidence : null; - const requestedMachineId = asString3(raw.requested_machine_id) ?? options.machineId; - const projectId = asString3(project.project_id) ?? options.projectId ?? "open-knowledge"; - const repoName = asString3(project.repo_name) ?? options.repoName ?? options.projectId ?? "open-knowledge"; - const trustStatus = asString3(machine.trust_status) ?? "unknown"; - const authStatus = asString3(machine.auth_status) ?? "unknown"; - const warnings = asStringArray(raw.warnings); - const diagnostics = normalizeWorkspaceDiagnostics(raw.diagnostics); - const repairHints = normalizeWorkspaceRepairHints(raw.repair_hints); - return { - ok: true, - source: "open-machines", - adapter, - requested_machine_id: requestedMachineId, - machine_id: asString3(raw.machine_id), - project_id: projectId, - repo_name: repoName, - project_root: projectRoot.path, - project_root_source: projectRoot.source, - workspace_root: workspaceRoot.path, - workspace_root_source: workspaceRoot.source, - open_files_root: openFilesRoot.path, - open_files_root_source: openFilesRoot.source, - trust_status: trustStatus, - auth_status: authStatus, - current: machine.current === true, - primary: machine.primary === true, - diagnostics, - repair_hints: repairHints.length ? repairHints : fallbackWorkspaceRepairHints({ - requestedMachineId, - projectId, - repoName, - openFilesRepoName: options.openFilesRepoName, - warnings, - projectRootSource: projectRoot.source, - openFilesRootSource: openFilesRoot.source, - trustStatus, - authStatus - }), - evidence, - cacheability: normalizeResolverCacheability(raw.cacheability), - warnings - }; +function parseJsonObject6(value) { + if (!value) + return {}; + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } } -async function discoverOpenMachinesCliTopology(options, adapter) { - const runner = options.runner ?? defaultRunner; - if (!await hasCommand("machines", runner)) - return null; - const args = ["topology", "--json"]; - if (options.includeTailscale === false) - args.push("--no-tailscale"); - const result = await runCommand(runner, machinesCliCommand(args)); - if (result.exitCode !== 0) - return null; - return normalizeOpenMachinesTopology(parseJson2(result.stdout), options, adapter); +function queryTerms3(query2) { + return Array.from(new Set((query2 ?? "").toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [])).slice(0, 12); } -async function discoverLocalTopology(options, adapter) { - const warnings = []; - if (adapter.error) - warnings.push(`open_machines_unavailable:${adapter.error}`); - const runner = options.runner ?? defaultRunner; - const tailscale = options.includeTailscale === false ? { peers: new Map, selfKey: null } : await loadTailscalePeers(runner, warnings); - const localId = localMachineId(tailscale.selfKey); - const machineIds = new Set([localId, ...tailscale.peers.keys()]); - const machines = [...machineIds].sort().map((machineId) => buildLocalEntry({ - machineId, - localMachineId: localId, - peer: tailscale.peers.get(machineId) - })); - return withKnowledgeContext({ - ok: true, - source: "local", - generated_at: (options.now ?? new Date).toISOString(), - local_machine_id: localId, - local_hostname: hostname4(), - current_platform: normalizePlatform(), - machines, - warnings, - adapter - }, options); +function escapeLike(value) { + return value.replace(/[\\%_]/g, (char) => `\\${char}`); } -async function discoverKnowledgeMachineTopology(options = {}) { - const mode2 = adapterMode(options); - if (mode2 === "disabled") - return await discoverLocalTopology(options, disabledAdapterStatus(mode2)); - const cliStatus = cliAdapterStatus(mode2); - try { - if (mode2 !== "cli") { - const loader = options.loadOpenMachines ?? loadOpenMachinesModule; - const mod = await loader(); - const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); - if (unsupportedStatus) - return await discoverLocalTopology(options, unsupportedStatus); - const sdkStatus = sdkAdapterStatus(mode2, mod); - if (mod?.discoverMachineTopology) { - const topology = mod.discoverMachineTopology({ - includeTailscale: options.includeTailscale, - runner: options.runner, - now: options.now - }); - const normalized = normalizeOpenMachinesTopology(topology, options, sdkStatus); - if (normalized) - return normalized; - if (mode2 === "sdk") - return await discoverLocalTopology(options, disabledAdapterStatus(mode2, "invalid_topology_shape")); - return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, "invalid_topology_shape")); - } - if (mode2 === "sdk") - return await discoverLocalTopology(options, disabledAdapterStatus(mode2, "missing_discoverMachineTopology")); - return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, "missing_discoverMachineTopology")); +function selectSourceChunks(db, options) { + const limit = Math.max(1, Math.min(options.limit ?? 10, 50)); + const sourceRefs = options.sourceRefs ?? []; + const terms = queryTerms3(options.query); + const where = ["c.kind = 'source'"]; + const params = []; + if (sourceRefs.length > 0) { + where.push(`(${sourceRefs.map(() => "(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`); + for (const ref of sourceRefs) { + params.push(ref, `%${escapeLike(ref)}%`); } - return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, "machines_cli_unavailable")); - } catch (error51) { - if (mode2 === "sdk") - return await discoverLocalTopology(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); - return await discoverOpenMachinesCliTopology(options, cliStatus) ?? await discoverLocalTopology(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); } + if (terms.length > 0) { + where.push(`(${terms.map(() => "lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`); + for (const term of terms) + params.push(`%${escapeLike(term)}%`); + } + params.push(limit); + return db.query(`SELECT + c.id AS chunk_id, + c.text, + c.start_offset, + c.end_offset, + c.metadata_json, + c.source_revision_id, + sr.revision, + sr.hash, + s.uri AS source_uri, + s.title AS source_title + FROM chunks c + JOIN source_revisions sr ON sr.id = c.source_revision_id + JOIN sources s ON s.id = sr.source_id + WHERE ${where.join(" AND ")} + ORDER BY c.created_at ASC, c.ordinal ASC + LIMIT ?`).all(...params); } -async function resolveOpenMachinesCliRoute(options, adapter) { - const runner = options.runner ?? defaultRunner; - if (!await hasCommand("machines", runner)) - return null; - const args = ["route", "--machine", options.machineId, "--json"]; - if (options.includeTailscale === false) - args.push("--no-tailscale"); - const result = await runCommand(runner, machinesCliCommand(args)); - if (result.exitCode !== 0) - return null; - return normalizeOpenMachinesRoute(parseJson2(result.stdout), adapter); +function excerpt(text, max = 420) { + const normalized = text.replace(/\s+/g, " ").trim(); + return normalized.length <= max ? normalized : `${normalized.slice(0, max - 1).trim()}...`; +} +function titleFor(options, rows) { + if (options.title?.trim()) + return options.title.trim(); + if (options.query?.trim()) + return options.query.trim(); + return rows[0]?.source_title ?? "Compiled Knowledge"; +} +function compileBody(title, rows, now) { + const sourceLines = rows.map((row, index) => { + const label = `S${index + 1}`; + return `- [${label}] ${row.source_title ?? row.source_uri ?? "Source"} (${row.source_uri ?? "unknown"}, revision ${row.revision ?? "unknown"}, hash ${row.hash ?? "unknown"})`; + }); + const noteLines = rows.map((row, index) => { + const label = `S${index + 1}`; + return [ + `## ${row.source_title ?? `Source ${index + 1}`}`, + "", + excerpt(row.text), + "", + `Citation: [${label}]` + ].join(` +`); + }); + return [ + `# ${title}`, + "", + `Generated at: ${now}`, + "", + "## Sources", + "", + ...sourceLines, + "", + ...noteLines, + "" + ].join(` +`); } -function rawMachineRoute(machineId, adapter) { +async function writeArtifact2(store, entry) { + const written = await store.put(entry); return { - target: machineId, - route: null, - targetKind: null, - confidence: null, - source: "raw", - adapter, - evidence: null, - cacheability: null, - warnings: [] + key: written.key, + uri: written.uri, + kind: entry.key.startsWith("logs/") ? "log" : "wiki_page", + content_type: entry.content_type, + modified_at: written.modified_at, + ...hashArtifactBody(entry.body), + metadata: { + ...entry.metadata ?? {} + } }; } -async function resolveKnowledgeMachineRoute(options) { - const mode2 = adapterMode(options); - if (mode2 === "disabled") - return rawMachineRoute(options.machineId, disabledAdapterStatus(mode2)); - const cliStatus = cliAdapterStatus(mode2); +async function appendLog2(store, event, now) { + const { year, month, day } = todayParts(now); + const key = `logs/${year}/${month}/${day}.jsonl`; + let existing = ""; try { - if (mode2 !== "cli") { - const loader = options.loadOpenMachines ?? loadOpenMachinesModule; - const mod = await loader(); - const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); - if (unsupportedStatus) - return rawMachineRoute(options.machineId, unsupportedStatus); - const sdkStatus = sdkAdapterStatus(mode2, mod); - if (mod?.resolveMachineRoute) { - const normalized = normalizeOpenMachinesRoute(mod.resolveMachineRoute(options.machineId, { - includeTailscale: options.includeTailscale, - runner: options.runner, - now: options.now - }), sdkStatus); - if (normalized) - return normalized; - if (mode2 === "sdk") - return rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "invalid_route_shape")); - return await resolveOpenMachinesCliRoute(options, cliStatus) ?? rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "invalid_route_shape")); - } - if (mode2 === "sdk") - return rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "missing_resolveMachineRoute")); - return await resolveOpenMachinesCliRoute(options, cliStatus) ?? rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "missing_resolveMachineRoute")); - } - return await resolveOpenMachinesCliRoute(options, cliStatus) ?? rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, "machines_cli_unavailable")); - } catch (error51) { - if (mode2 === "sdk") { - return { - ...rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, optionalModuleError(error51))), - warnings: [optionalModuleError(error51)] - }; - } - return await resolveOpenMachinesCliRoute(options, cliStatus) ?? { - ...rawMachineRoute(options.machineId, disabledAdapterStatus(mode2, optionalModuleError(error51))), - warnings: [optionalModuleError(error51)] - }; + existing = await store.getText(key); + } catch { + existing = ""; } + return writeArtifact2(store, { + key, + body: `${existing}${JSON.stringify(event)} +`, + content_type: "application/x-ndjson", + metadata: { + provenance: generatedArtifactProvenance({ + generated_from: String(event.event ?? "wiki_log"), + artifact_key: key + }) + } + }); } -async function resolveOpenMachinesCliWorkspace(options, adapter) { - const runner = options.runner ?? defaultRunner; - if (!await hasCommand("machines", runner)) - return null; - const projectId = options.projectId ?? "open-knowledge"; - const repoName = options.repoName ?? "open-knowledge"; - const args = [ - "workspace", - "resolve", - "--machine", - options.machineId, - "--project", - projectId, - "--repo", - repoName, - "--open-files-repo", - options.openFilesRepoName ?? "open-files", - "--json" - ]; - if (options.includeTailscale === false) - args.push("--no-tailscale"); - const result = await runCommand(runner, machinesCliCommand(args)); - if (result.exitCode !== 0) - return null; - return normalizeOpenMachinesWorkspace(parseJson2(result.stdout), options, adapter); +function upsertWikiPage(db, input) { + db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(path) DO UPDATE SET + title = excluded.title, + artifact_uri = excluded.artifact_uri, + content_hash = excluded.content_hash, + status = excluded.status, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at`, [ + input.pageId, + input.path, + input.title, + input.artifactUri, + input.contentHash, + "active", + JSON.stringify({ + artifact_key: input.path, + provenance: input.provenance + }), + input.now, + input.now + ]); + const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(input.pageId); + for (const row of existing) + db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); + db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [input.pageId]); + const chunkId = stableId9("chk", `${input.pageId}\x00${input.contentHash}`); + db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + chunkId, + input.pageId, + "wiki", + 0, + input.body, + estimateTokenCount3(input.body), + 0, + input.body.length, + JSON.stringify({ + artifact_key: input.path, + artifact_uri: input.artifactUri, + content_hash: input.contentHash, + provenance: input.provenance + }), + input.now + ]); + db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [ + chunkId, + input.body, + input.title, + input.artifactUri + ]); } -function argumentMachineWorkspace(options) { - const peerWorkspace = options.peerWorkspace?.trim(); - if (!peerWorkspace) - return null; - const adapter = disabledAdapterStatus(adapterMode(options), "argument_override"); - return { - ok: true, - source: "argument", - adapter, - requested_machine_id: options.machineId, - machine_id: options.machineId, - project_id: options.projectId ?? "open-knowledge", - repo_name: options.repoName ?? "open-knowledge", - project_root: peerWorkspace, - project_root_source: "argument", - workspace_root: null, - workspace_root_source: "unresolved", - open_files_root: null, - open_files_root_source: "unresolved", - trust_status: "unknown", - auth_status: "unknown", - current: false, - primary: false, - diagnostics: [], - repair_hints: [], - evidence: null, - cacheability: null, - warnings: [] - }; +function replacePageCitations(db, pageId, citations, now) { + db.run("DELETE FROM citations WHERE wiki_page_id = ?", [pageId]); + for (const citation of citations) { + db.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + stableId9("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID12()}`), + pageId, + citation.chunk_id, + citation.source_uri, + citation.quote, + citation.start_offset, + citation.end_offset, + JSON.stringify(citation.metadata), + now + ]); + } + return citations.length; } -function unresolvedMachineWorkspace(options, warnings, adapter) { - return { - ok: false, - source: "raw", - adapter, - requested_machine_id: options.machineId, - machine_id: null, - project_id: options.projectId ?? "open-knowledge", - repo_name: options.repoName ?? "open-knowledge", - project_root: null, - project_root_source: "unresolved", - workspace_root: null, - workspace_root_source: "unresolved", - open_files_root: null, - open_files_root_source: "unresolved", - trust_status: "unknown", - auth_status: "unknown", - current: false, - primary: false, - diagnostics: [], - repair_hints: [], - evidence: null, - cacheability: null, - warnings - }; +function upsertIndex(db, input) { + db.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(kind, name, shard_key) DO UPDATE SET + artifact_uri = excluded.artifact_uri, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at`, [ + stableId9("idx", `wiki-topic\x00${input.path}`), + "wiki_topic", + input.title, + input.artifactUri, + input.path, + JSON.stringify({ + artifact_key: input.path, + content_hash: input.contentHash + }), + input.now, + input.now + ]); + return 1; } -async function resolveKnowledgeMachineWorkspace(options) { - const argument = argumentMachineWorkspace(options); - if (argument) - return argument; - const mode2 = adapterMode(options); - if (mode2 === "disabled") - return unresolvedMachineWorkspace(options, ["adapter_disabled"], disabledAdapterStatus(mode2)); - const cliStatus = cliAdapterStatus(mode2); +function firstConcept(title) { + return title.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0] ?? "knowledge"; +} +async function compileWikiPage(options) { + const nowDate = options.now ?? new Date; + const now = nowDate.toISOString(); + migrateKnowledgeDb(options.dbPath); + const readDb = openKnowledgeDb(options.dbPath); + let rows; try { - if (mode2 !== "cli") { - const loader = options.loadOpenMachines ?? loadOpenMachinesModule; - const mod = await loader(); - const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); - if (unsupportedStatus) - return unresolvedMachineWorkspace(options, [`unsupported_contract_version:${unsupportedStatus.contract_version}`], unsupportedStatus); - const sdkStatus = sdkAdapterStatus(mode2, mod); - if (mod?.resolveMachineWorkspace) { - const normalized = normalizeOpenMachinesWorkspace(mod.resolveMachineWorkspace({ - machineId: options.machineId, - projectId: options.projectId ?? "open-knowledge", - repoName: options.repoName ?? "open-knowledge", - openFilesRepoName: options.openFilesRepoName ?? "open-files", - includeTailscale: options.includeTailscale, - runner: options.runner, - now: options.now - }), options, sdkStatus); - if (normalized) - return normalized; - if (mode2 === "sdk") - return unresolvedMachineWorkspace(options, ["invalid_workspace_shape"], disabledAdapterStatus(mode2, "invalid_workspace_shape")); - return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, ["invalid_workspace_shape"], disabledAdapterStatus(mode2, "invalid_workspace_shape")); - } - if (mode2 === "sdk") - return unresolvedMachineWorkspace(options, ["missing_resolveMachineWorkspace"], disabledAdapterStatus(mode2, "missing_resolveMachineWorkspace")); - return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, ["missing_resolveMachineWorkspace"], disabledAdapterStatus(mode2, "missing_resolveMachineWorkspace")); + rows = selectSourceChunks(readDb, options); + } finally { + readDb.close(); + } + if (rows.length === 0) + throw new Error("No source chunks matched wiki compile input."); + const title = titleFor(options, rows); + const slug = slugify3(title); + const path = `wiki/generated/${slug}.md`; + const body = compileBody(title, rows, now); + const sourceRefs = rows.map((row) => { + const metadata = parseJsonObject6(row.metadata_json); + return typeof metadata.source_ref === "string" ? metadata.source_ref : row.source_uri; + }).filter((ref) => Boolean(ref)); + const provenance = generatedArtifactProvenance({ + generated_from: "wiki_compile", + artifact_key: path, + source_refs: sourceRefs + }); + const pageArtifact = await writeArtifact2(options.store, { + key: path, + body, + content_type: "text/markdown", + metadata: { generated_from: "wiki_compile" } + }); + const pageId = stableId9("wiki", path); + const citations = rows.map((row) => ({ + chunk_id: row.chunk_id, + source_uri: row.source_uri ?? "unknown", + quote: excerpt(row.text, 240), + start_offset: row.start_offset, + end_offset: row.end_offset, + metadata: { + source_revision_id: row.source_revision_id, + revision: row.revision, + hash: row.hash, + source_ref: parseJsonObject6(row.metadata_json).source_ref ?? row.source_uri } - return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, ["machines_cli_unavailable"], disabledAdapterStatus(mode2, "machines_cli_unavailable")); - } catch (error51) { - if (mode2 === "sdk") - return unresolvedMachineWorkspace(options, [optionalModuleError(error51)], disabledAdapterStatus(mode2, optionalModuleError(error51))); - return await resolveOpenMachinesCliWorkspace(options, cliStatus) ?? unresolvedMachineWorkspace(options, [optionalModuleError(error51)], disabledAdapterStatus(mode2, optionalModuleError(error51))); + })); + const concept = firstConcept(title); + const conceptPath = `wiki/concepts/${slugify3(concept)}.md`; + const conceptBody = [`# ${concept}`, "", `Related page: [[${path}]]`, ""].join(` +`); + const conceptProvenance = generatedArtifactProvenance({ + generated_from: "wiki_compile_concept", + artifact_key: conceptPath, + source_refs: sourceRefs + }); + const conceptArtifact = await writeArtifact2(options.store, { + key: conceptPath, + body: conceptBody, + content_type: "text/markdown", + metadata: { generated_from: "wiki_compile_concept" } + }); + const conceptPageId = stableId9("wiki", conceptPath); + const log = await appendLog2(options.store, { + ts: now, + event: "wiki_compile_completed", + page_key: path, + source_refs: sourceRefs, + chunks_seen: rows.length + }, nowDate); + const db = openKnowledgeDb(options.dbPath); + try { + recordStorageObjects(db, [pageArtifact, conceptArtifact, log], nowDate); + upsertWikiPage(db, { + pageId, + path, + title, + artifactUri: pageArtifact.uri, + contentHash: pageArtifact.hash ?? "", + body, + provenance, + now + }); + upsertWikiPage(db, { + pageId: conceptPageId, + path: conceptPath, + title: concept, + artifactUri: conceptArtifact.uri, + contentHash: conceptArtifact.hash ?? "", + body: conceptBody, + provenance: conceptProvenance, + now + }); + db.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) + VALUES (?, ?, ?, ?)`, [pageId, conceptPageId, "concept", now]); + const citationsWritten = replacePageCitations(db, pageId, citations, now); + const indexesUpdated = upsertIndex(db, { + title, + path, + artifactUri: pageArtifact.uri, + contentHash: pageArtifact.hash ?? "", + now + }); + return { + page_id: pageId, + path, + artifact_uri: pageArtifact.uri, + content_hash: pageArtifact.hash ?? "", + chunks_seen: rows.length, + citations_written: citationsWritten, + concept_page_id: conceptPageId, + indexes_updated: indexesUpdated, + log_key: log.key, + warnings: [] + }; + } finally { + db.close(); } } -function withPreflightKnowledgeContext(report, options) { - return { - ...report, - knowledge: { - scope: options.knowledge?.scope ?? "global", - app_path: HASNA_KNOWLEDGE_APP_PATH, - workspace_home: options.knowledge?.workspace_home ?? null - }, - message: report.ok ? `Machine ${report.machine_id} passed knowledge preflight` : `Machine ${report.machine_id} failed knowledge preflight: ${report.summary.fail} failing check(s)` - }; -} -function normalizeOpenMachinesPreflight(value, options, adapter) { - const raw = asRecord(value); - if (unsupportedContractVersion(payloadContractVersion(raw))) - return null; - const checksRaw = Array.isArray(raw.checks) ? raw.checks : null; - const machineId = asString3(raw.machine_id) ?? asString3(raw.machineId); - if (!checksRaw || !machineId) - return null; - const checks3 = checksRaw.map((entry) => { - const record2 = asRecord(entry); - const status = asString3(record2.status); - const kind = asString3(record2.kind); - const source = asString3(record2.source); - return makePreflightCheck({ - id: asString3(record2.id) ?? "unknown", - kind: kind === "command" || kind === "package" || kind === "workspace" ? kind : "command", - status: status === "ok" || status === "warn" || status === "fail" ? status : "fail", - target: asString3(record2.target) ?? "unknown", - expected: asString3(record2.expected), - actual: asString3(record2.actual), - detail: asString3(record2.detail) ?? "", - source: source === "local" || source === "ssh" || source === "open-machines" ? source : "open-machines" +async function fileAnswerToWiki(options) { + if (!options.approveWrite) { + return { + approved: false, + durable_writes_performed: false, + page_id: null, + path: null, + artifact_uri: null, + citations_written: 0, + log_key: null, + message: "Dry-run: answer filing requires --approve-write." + }; + } + const nowDate = options.now ?? new Date; + const now = nowDate.toISOString(); + const title = options.prompt.length > 80 ? `${options.prompt.slice(0, 77)}...` : options.prompt; + const slug = slugify3(title); + const path = `wiki/answers/${slug}.md`; + const citations = options.context.citations; + const body = [ + `# ${title}`, + "", + options.answer, + "", + "## Citations", + "", + ...citations.map((citation, index) => `- [C${index + 1}] ${citation.source_ref ?? citation.source_uri ?? citation.artifact_path ?? citation.artifact_uri ?? "unknown"} ${citation.hash ? `(hash ${citation.hash})` : ""}`), + "" + ].join(` +`); + const sourceRefs = citations.map((citation) => citation.source_ref ?? citation.source_uri).filter((ref) => Boolean(ref)); + const provenance = generatedArtifactProvenance({ + generated_from: "knowledge_answer", + artifact_key: path, + source_refs: sourceRefs + }); + const artifact = await writeArtifact2(options.store, { + key: path, + body, + content_type: "text/markdown", + metadata: { generated_from: "knowledge_answer" } + }); + const log = await appendLog2(options.store, { + ts: now, + event: "wiki_answer_filed", + page_key: path, + prompt: options.prompt, + citations: citations.length + }, nowDate); + const pageId = stableId9("wiki", path); + const db = openKnowledgeDb(options.dbPath); + try { + recordStorageObjects(db, [artifact, log], nowDate); + upsertWikiPage(db, { + pageId, + path, + title, + artifactUri: artifact.uri, + contentHash: artifact.hash ?? "", + body, + provenance, + now + }); + const written = replacePageCitations(db, pageId, citations.map((citation) => ({ + chunk_id: citation.chunk_id, + source_uri: citation.source_uri ?? citation.artifact_uri ?? "unknown", + quote: citation.quote, + start_offset: citation.start_offset, + end_offset: citation.end_offset, + metadata: { + source_ref: citation.source_ref, + artifact_path: citation.artifact_path, + revision: citation.revision, + hash: citation.hash + } + })), now); + upsertIndex(db, { + title, + path, + artifactUri: artifact.uri, + contentHash: artifact.hash ?? "", + now }); - }); - const summary = { - ok: checks3.filter((check2) => check2.status === "ok").length, - warn: checks3.filter((check2) => check2.status === "warn").length, - fail: checks3.filter((check2) => check2.status === "fail").length - }; - return withPreflightKnowledgeContext({ - ok: summary.fail === 0, - source: "open-machines", - machine_id: machineId, - generated_at: asString3(raw.generated_at) ?? (options.now ?? new Date).toISOString(), - checks: checks3, - summary, - adapter - }, options); -} -function machinesCliPreflightRunner(options) { - if (!options.runner) - return defaultRunner; - return async (command) => { - const result = await options.runner?.("local", command); return { - stdout: result?.stdout ?? "", - stderr: result?.stderr ?? "", - exitCode: result?.exitCode ?? 1 + approved: true, + durable_writes_performed: true, + page_id: pageId, + path, + artifact_uri: artifact.uri, + citations_written: written, + log_key: log.key, + message: `Filed answer to ${path}` }; - }; -} -function machinesCliPackageSpec(spec) { - return [spec.name, spec.command, spec.expectedVersion].filter((value) => Boolean(value)).join(":"); -} -function machinesCliWorkspaceSpec(spec) { - const suffix = [spec.expectedPackageName, spec.expectedVersion].filter((value) => Boolean(value)).join(":"); - const path = suffix ? `${spec.path}:${suffix}` : spec.path; - return spec.label ? `${spec.label}=${path}` : path; -} -async function preflightOpenMachinesCli(options, adapter) { - const runner = machinesCliPreflightRunner(options); - if (!await hasCommand("machines", runner)) - return null; - const args = [ - "compatibility", - "--json", - "--machine", - options.machineId ?? "local" - ]; - for (const spec of options.commands ?? []) { - args.push("--command", spec.expectedVersion ? `${spec.command}:${spec.expectedVersion}` : spec.command); + } finally { + db.close(); } - for (const spec of options.packages ?? []) - args.push("--package", machinesCliPackageSpec(spec)); - for (const spec of options.workspaces ?? []) - args.push("--workspace", machinesCliWorkspaceSpec(spec)); - const result = await runCommand(runner, machinesCliCommand(args)); - if (result.exitCode !== 0) - return null; - return normalizeOpenMachinesPreflight(parseJson2(result.stdout), options, adapter); } -async function fallbackPreflight(options, adapter) { - const machineId = options.machineId ?? hostname4(); - const runner = options.runner ?? defaultPreflightRunner; - const commands = options.commands ?? [{ command: "bun", required: true }, { command: "knowledge", required: true }]; - const packages = options.packages ?? [{ name: "@hasna/knowledge", command: "knowledge", required: true }]; - const workspaces = options.workspaces ?? []; - const checks3 = []; - for (const spec of commands) - checks3.push(...await fallbackCommandChecks(machineId, spec, runner)); - for (const spec of packages) - checks3.push(...await fallbackPackageChecks(machineId, spec, runner)); - for (const spec of workspaces) - checks3.push(...await fallbackWorkspaceChecks(machineId, spec, runner)); - if (adapter.error) { - checks3.push(makePreflightCheck({ - id: "adapter:@hasna/machines", - kind: "package", - status: "warn", - target: "@hasna/machines", - expected: "optional", - actual: adapter.error, - detail: "Using knowledge local/ssh compatibility fallback", - source: preflightTargetIsLocal(machineId) ? "local" : "ssh" - })); - } - const summary = { - ok: checks3.filter((check2) => check2.status === "ok").length, - warn: checks3.filter((check2) => check2.status === "warn").length, - fail: checks3.filter((check2) => check2.status === "fail").length - }; - return withPreflightKnowledgeContext({ - ok: summary.fail === 0, - source: "local", - machine_id: machineId, - generated_at: (options.now ?? new Date).toISOString(), - checks: checks3, - summary, - adapter - }, options); +function addIssue(issues, issue2) { + issues.push(issue2); } -async function preflightKnowledgeMachine(options = {}) { - const mode2 = adapterMode(options); - if (mode2 === "disabled") - return await fallbackPreflight(options, disabledAdapterStatus(mode2)); - const cliStatus = cliAdapterStatus(mode2); +function lintWiki(options) { + migrateKnowledgeDb(options.dbPath); + const db = openKnowledgeDb(options.dbPath); + const issues = []; try { - if (mode2 !== "cli") { - const loader = options.loadOpenMachines ?? loadOpenMachinesModule; - const mod = await loader(); - const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); - if (unsupportedStatus) - return await fallbackPreflight(options, unsupportedStatus); - const sdkStatus = sdkAdapterStatus(mode2, mod); - if (mod?.checkMachineCompatibility) { - const report = mod.checkMachineCompatibility({ - machineId: options.machineId, - commands: options.commands, - packages: options.packages, - workspaces: options.workspaces, - runner: options.runner, - now: options.now - }); - const normalized = normalizeOpenMachinesPreflight(report, options, sdkStatus); - if (normalized) - return normalized; - if (mode2 === "sdk") - return await fallbackPreflight(options, disabledAdapterStatus(mode2, "invalid_compatibility_shape")); - return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, "invalid_compatibility_shape")); - } - if (mode2 === "sdk") - return await fallbackPreflight(options, disabledAdapterStatus(mode2, "missing_checkMachineCompatibility")); - return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, "missing_checkMachineCompatibility")); + const activePages = db.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n ?? 0; + const citationCount = db.query("SELECT COUNT(*) AS n FROM citations").get()?.n ?? 0; + const backlinkCount = db.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n ?? 0; + const missingCitations = db.query(`SELECT wp.id, wp.path + FROM wiki_pages wp + LEFT JOIN citations c ON c.wiki_page_id = wp.id + WHERE wp.status = 'active' AND wp.path LIKE 'wiki/generated/%' + GROUP BY wp.id + HAVING COUNT(c.id) = 0`).all(); + for (const page of missingCitations) { + addIssue(issues, { type: "missing_citation", severity: "error", page_id: page.id, path: page.path, message: "Generated wiki page has no citations." }); } - return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, "machines_cli_unavailable")); - } catch (error51) { - if (mode2 === "sdk") - return await fallbackPreflight(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); - return await preflightOpenMachinesCli(options, cliStatus) ?? await fallbackPreflight(options, disabledAdapterStatus(mode2, optionalModuleError(error51))); - } -} -function mergeAdapterTopologyOptions(defaults, options = {}) { - return { - ...options, - adapterMode: defaults.mode ?? "auto", - includeTailscale: options.includeTailscale ?? defaults.includeTailscale, - runner: options.runner ?? defaults.runner, - now: options.now ?? defaults.now, - loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines - }; -} -function mergeAdapterRouteOptions(defaults, options) { - return { - ...options, - adapterMode: defaults.mode ?? "auto", - includeTailscale: options.includeTailscale ?? defaults.includeTailscale, - runner: options.runner ?? defaults.runner, - now: options.now ?? defaults.now, - loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines - }; -} -function mergeAdapterWorkspaceOptions(defaults, options) { - return { - ...options, - adapterMode: defaults.mode ?? "auto", - includeTailscale: options.includeTailscale ?? defaults.includeTailscale, - runner: options.runner ?? defaults.runner, - now: options.now ?? defaults.now, - loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines - }; -} -function mergeAdapterPreflightOptions(defaults, options = {}) { - return { - ...options, - adapterMode: defaults.mode ?? "auto", - commands: options.commands, - packages: options.packages, - workspaces: options.workspaces, - runner: options.runner ?? defaults.preflightRunner, - now: options.now ?? defaults.now, - loadOpenMachines: options.loadOpenMachines ?? defaults.loadOpenMachines - }; -} -function createKnowledgeMachinesAdapter(defaults = {}) { - const mode2 = defaults.mode ?? "auto"; - return { - mode: mode2, - async status() { - if (mode2 === "disabled") - return disabledAdapterStatus(mode2); - if (mode2 === "cli") - return cliAdapterStatus(mode2); - try { - const loader = defaults.loadOpenMachines ?? loadOpenMachinesModule; - const mod = await loader(); - const unsupportedStatus = unsupportedContractAdapterStatus(mode2, mod); - if (unsupportedStatus) - return unsupportedStatus; - if (mod) - return sdkAdapterStatus(mode2, mod); - if (mode2 === "sdk") - return disabledAdapterStatus(mode2, "module_not_found"); - return cliAdapterStatus(mode2); - } catch (error51) { - return disabledAdapterStatus(mode2, optionalModuleError(error51)); - } - }, - topology(options = {}) { - return discoverKnowledgeMachineTopology(mergeAdapterTopologyOptions(defaults, options)); - }, - route(options) { - return resolveKnowledgeMachineRoute(mergeAdapterRouteOptions(defaults, options)); - }, - workspace(options) { - return resolveKnowledgeMachineWorkspace(mergeAdapterWorkspaceOptions(defaults, options)); - }, - preflight(options = {}) { - return preflightKnowledgeMachine(mergeAdapterPreflightOptions(defaults, options)); + const stale = db.query(`SELECT wp.id AS page_id, wp.path, c.source_uri, c.chunk_id + FROM citations c + JOIN wiki_pages wp ON wp.id = c.wiki_page_id + LEFT JOIN chunks ch ON ch.id = c.chunk_id + WHERE ch.metadata_json LIKE '%"stale":true%' OR ch.metadata_json LIKE '%"status":"stale"%' OR ch.metadata_json LIKE '%"status":"deleted"%'`).all(); + for (const row of stale) { + addIssue(issues, { type: "stale_citation", severity: "warn", page_id: row.page_id, path: row.path, source_uri: row.source_uri, chunk_id: row.chunk_id ?? undefined, message: "Page cites a stale or deleted source chunk." }); } - }; + const duplicates = db.query(`SELECT lower(title) AS title, COUNT(*) AS n + FROM wiki_pages + WHERE status = 'active' + GROUP BY lower(title) + HAVING COUNT(*) > 1`).all(); + for (const row of duplicates) { + addIssue(issues, { type: "duplicate_page", severity: "warn", message: `Duplicate active wiki title: ${row.title} (${row.n} pages).` }); + } + const orphans = db.query(`SELECT wp.id, wp.path + FROM wiki_pages wp + LEFT JOIN wiki_backlinks wb1 ON wb1.from_page_id = wp.id + LEFT JOIN wiki_backlinks wb2 ON wb2.to_page_id = wp.id + WHERE wp.status = 'active' + AND wp.path NOT IN ('wiki/README.md') + GROUP BY wp.id + HAVING COUNT(wb1.to_page_id) = 0 AND COUNT(wb2.from_page_id) = 0`).all(); + for (const page of orphans) { + addIssue(issues, { type: "orphan_page", severity: "info", page_id: page.id, path: page.path, message: "Wiki page has no backlinks." }); + } + const unresolved = db.query(`SELECT wp.id AS page_id, wp.path, c.source_uri + FROM citations c + JOIN wiki_pages wp ON wp.id = c.wiki_page_id + LEFT JOIN sources s ON s.uri = c.source_uri + WHERE s.id IS NULL AND c.source_uri NOT LIKE 'file://%' AND c.source_uri NOT LIKE 's3://%' AND c.source_uri NOT LIKE 'https://%' AND c.source_uri NOT LIKE 'open-files://%'`).all(); + for (const row of unresolved) { + addIssue(issues, { type: "unresolved_source_ref", severity: "error", page_id: row.page_id, path: row.path, source_uri: row.source_uri, message: "Citation source URI cannot be resolved to a known or allowed source ref." }); + } + const contradictions = db.query(`SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'`).all(); + for (const page of contradictions) { + addIssue(issues, { type: "contradiction_marker", severity: "warn", page_id: page.id, path: page.path, message: "Page metadata contains a contradiction marker." }); + } + const newArticleCandidates = db.query(`SELECT c.id AS chunk_id, s.uri AS source_uri + FROM chunks c + JOIN source_revisions sr ON sr.id = c.source_revision_id + JOIN sources s ON s.id = sr.source_id + LEFT JOIN citations cit ON cit.chunk_id = c.id + WHERE c.kind = 'source' + GROUP BY c.id + HAVING COUNT(cit.id) = 0 + LIMIT 25`).all(); + for (const row of newArticleCandidates) { + addIssue(issues, { type: "new_article_candidate", severity: "info", chunk_id: row.chunk_id, source_uri: row.source_uri ?? undefined, message: "Source chunk is indexed but not cited by any wiki page yet." }); + } + return { + ok: issues.every((issue2) => issue2.severity !== "error"), + issue_count: issues.length, + issues, + counts: { + active_pages: activePages, + citations: citationCount, + backlinks: backlinkCount, + new_article_candidates: newArticleCandidates.length + } + }; + } finally { + db.close(); + } } -// src/promotion-inbox.ts -import { createHash as createHash14 } from "crypto"; -function stableId7(prefix, value, length = 24) { - return `${prefix}_${createHash14("sha256").update(value).digest("hex").slice(0, length)}`; -} -function normalizedText(value) { - return value.normalize("NFKC").trim().replace(/\s+/g, " "); +// src/item-store.ts +import { existsSync as existsSync12 } from "fs"; +class VersionHistoryUnsupportedError extends Error { + location; + code = "version_history_unsupported"; + constructor(location) { + super("Version history is not kept by the local JSON knowledge store " + `(${location}). It has no version line, so an empty history here would be a claim, not a measurement. ` + "Entry versioning lives in the Postgres-backed store: point this CLI at it " + "(HASNA_KNOWLEDGE_STORAGE_MODE=postgres plus the API url/key) and re-run."); + this.location = location; + this.name = "VersionHistoryUnsupportedError"; + } } -function normalizedKey(value) { - return normalizedText(value).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, ""); +function matchesId(item, idOrShort) { + return item.id === idOrShort || item.short_id === idOrShort; } -function parseJson3(value, fallback) { - try { - return JSON.parse(value); - } catch { - return fallback; + +class LocalItemStore { + storePath; + kind = "local"; + supportsVersions = false; + constructor(storePath) { + this.storePath = storePath; + } + async listVersions() { + throw new VersionHistoryUnsupportedError(this.storePath); + } + async getVersion() { + throw new VersionHistoryUnsupportedError(this.storePath); + } + get location() { + return this.storePath; + } + get exists() { + return existsSync12(this.storePath); + } + async listAll() { + const store = loadStoreIfExists(this.storePath); + return { items: store.items, exists: store.exists }; + } + async get(idOrShort) { + const store = loadStoreIfExists(this.storePath); + return store.items.find((item) => matchesId(item, idOrShort)) ?? null; + } + async create(input) { + return withLock(this.storePath, () => { + const db = loadStore(this.storePath); + const now = new Date().toISOString(); + const id = input.id ?? makeId(); + const item = { + id, + short_id: makeShortId(id), + title: input.title, + content: input.content, + url: input.url ?? null, + tags: input.tags ?? [], + metadata: input.metadata ?? {}, + archived: false, + created_at: now, + updated_at: now + }; + db.items.push(item); + saveStore(this.storePath, db); + return item; + }, { createParent: true }); + } + async update(idOrShort, patch) { + return withLock(this.storePath, () => { + const db = loadStore(this.storePath); + const idx = db.items.findIndex((item2) => matchesId(item2, idOrShort)); + if (idx === -1) + return null; + const item = db.items[idx]; + if (patch.title !== undefined) + item.title = patch.title; + if (patch.content !== undefined) + item.content = patch.content; + if (patch.url !== undefined) + item.url = patch.url; + if (patch.tags !== undefined) + item.tags = patch.tags; + if (patch.metadata !== undefined) + item.metadata = patch.metadata; + if (patch.archived !== undefined) + item.archived = patch.archived; + item.updated_at = new Date().toISOString(); + db.items[idx] = item; + saveStore(this.storePath, db); + return item; + }, { createParent: true }); + } + async delete(idOrShort) { + return withLock(this.storePath, () => { + const db = loadStore(this.storePath); + const before = db.items.length; + db.items = db.items.filter((item) => !matchesId(item, idOrShort)); + const removed = before !== db.items.length; + if (removed) + saveStore(this.storePath, db); + return removed; + }, { createParent: true }); + } + async deleteMany(idsOrShorts) { + if (idsOrShorts.length === 0) + return 0; + const targets = new Set(idsOrShorts); + return withLock(this.storePath, () => { + const db = loadStore(this.storePath); + const before = db.items.length; + db.items = db.items.filter((item) => !targets.has(item.id) && !(item.short_id != null && targets.has(item.short_id))); + const removed = before - db.items.length; + if (removed > 0) + saveStore(this.storePath, db); + return removed; + }, { createParent: true }); } } -function asCandidate(row) { - return { - ...row, - record_kind: row.record_kind, - source_kind: row.source_kind, - status: row.status, - source_refs: parseJson3(row.source_refs_json, []), - evidence_refs: parseJson3(row.evidence_refs_json, []), - requires_approval: row.requires_approval === 1, - checks: parseJson3(row.checks_json, emptyChecks()), - metadata: parseJson3(row.metadata_json, {}) - }; -} -function asDurableRecord(row) { - return { - ...row, - record_kind: row.record_kind, - source_refs: parseJson3(row.source_refs_json, []), - evidence_refs: parseJson3(row.evidence_refs_json, []), - metadata: parseJson3(row.metadata_json, {}) - }; + +class ApiItemStore { + cloud; + kind = "api"; + exists = true; + supportsVersions = true; + constructor(cloud) { + this.cloud = cloud; + } + async listVersions(idOrShort, options = {}) { + return this.cloud.listVersions(idOrShort, options); + } + async getVersion(idOrShort, version2) { + return this.cloud.getVersion(idOrShort, version2); + } + get location() { + return this.cloud.baseUrl; + } + async listAll() { + return { items: await fetchAllCloudItems(this.cloud), exists: true }; + } + async get(idOrShort) { + return this.cloud.get(idOrShort); + } + async create(input) { + return this.cloud.create({ + ...input.id ? { id: input.id } : {}, + title: input.title, + content: input.content, + url: input.url ?? null, + tags: input.tags ?? [], + ...input.metadata ? { metadata: input.metadata } : {} + }); + } + async update(idOrShort, patch, options = {}) { + return this.cloud.update(idOrShort, patch, { expectedVersion: options.expectedVersion }); + } + async delete(idOrShort) { + return this.cloud.delete(idOrShort); + } + async deleteMany(idsOrShorts) { + let removed = 0; + for (const id of idsOrShorts) { + if (await this.cloud.delete(id)) + removed += 1; + } + return removed; + } } -function emptyChecks() { - return { - citations: { provided: 0, valid: 0, invalid: 0, entries: [] }, - invalid_source_refs: [], - stale_refs: [], - duplicate_record_ids: [], - duplicate_candidate_ids: [], - conflicting_record_ids: [], - conflicting_candidate_ids: [], - approval_reasons: [] - }; +function resolveItemStore(options) { + const cloud = options.storePathOverridden ? null : resolveKnowledgeCloudStore(options.env ?? process.env); + if (cloud) + return new ApiItemStore(cloud); + return new LocalItemStore(options.storePath); } -function normalizeEvidenceRef(input) { - const value = typeof input === "string" ? { ref: input } : input; - return { - ref: normalizedText(value.ref), - citation_id: value.citation_id ?? null, - chunk_id: value.chunk_id ?? null, - revision: value.revision ?? null, - hash: value.hash ?? null, - observed_at: value.observed_at ?? null, - expires_at: value.expires_at ?? null, - status: value.status ?? null - }; + +// src/wiki-layout.ts +import { createHash as createHash19 } from "crypto"; +function todayParts2(now) { + const year = String(now.getUTCFullYear()); + const month = String(now.getUTCMonth() + 1).padStart(2, "0"); + const day = String(now.getUTCDate()).padStart(2, "0"); + return { year, month, day }; } -function validReference(ref) { - try { - const parsed = new URL(ref); - return parsed.protocol.length > 1 && (parsed.hostname.length > 0 || parsed.pathname.length > 0); - } catch { - return /^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(ref); - } +function stableId10(prefix, value) { + return `${prefix}_${createHash19("sha256").update(value).digest("hex").slice(0, 20)}`; } -function staleStatus(status) { - return ["deleted", "stale", "invalidated", "reindex_required", "expired", "superseded"].includes((status ?? "").toLowerCase()); +function estimateTokenCount4(text) { + const words = text.trim().split(/\s+/).filter(Boolean).length; + return Math.max(1, Math.ceil(words * 1.25)); } -function metadataStatus(value) { - if (!value) - return null; - const metadata = parseJson3(value, {}); - if (metadata.stale === true) - return "stale"; - return typeof metadata.status === "string" ? metadata.status : null; +function agentSchemaTemplate() { + return `# Knowledge Agent Schema v1 + +## Source Rules + +- Treat open-files source references as the preferred source of truth. +- Do not copy raw source files into knowledge. +- Cite every durable fact with a source URI, revision/hash when available, and optional span. +- Mark uncertainty explicitly when sources disagree or are incomplete. + +## Wiki Rules + +- Write generated knowledge as Markdown pages under wiki/. +- Keep root indexes small; use topic, team, project, and machine-readable shards for scale. +- Preserve backlinks between related pages and decisions. +- Prefer updating existing pages over creating near-duplicates. + +## Query Rules + +- Search wiki pages first, then source chunks, then deeper read-only source refs. +- Use web search only when requested or when current external context is required. +- File useful answers back into the wiki only after approval or approved auto-write mode. + +## Lint Rules + +- Flag stale pages, missing citations, contradictions, orphan pages, duplicate pages, and unresolved source refs. +`; } -function citationIdentifier(evidence) { - if (evidence.citation_id) - return evidence.citation_id; - const match = evidence.ref.match(/^(?:cite|citation):(.+)$/); - return match?.[1] ?? null; +function rootIndexTemplate() { + return `# Knowledge Index + +This is a compact orientation index for agents. It is not the full search index. + +## Shards + +- wiki/ +- indexes/ +- schemas/ +- logs/ + +## Source Ownership + +Raw source files are resolved through open-files. This app stores source refs, +citations, chunks, generated wiki artifacts, indexes, and run records. +`; } -function chunkIdentifier(evidence) { - if (evidence.chunk_id) - return evidence.chunk_id; - const match = evidence.ref.match(/^chunk:(.+)$/); - return match?.[1] ?? null; +function wikiReadmeTemplate() { + return `# Wiki + +Generated durable knowledge pages live here. + +Pages should be concise, cited, and organized for both humans and agents. +`; } -function inspectCitation(db, evidence, now) { - const explicitStale = staleStatus(evidence.status) || Boolean(evidence.expires_at && evidence.expires_at <= now); - if (!evidence.ref || !validReference(evidence.ref)) { - return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "invalid_reference" }; - } - const citationId = citationIdentifier(evidence); - const citation = db.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, - sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, - sr.source_id, sr.created_at AS revision_created_at, - (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at - FROM citations c - LEFT JOIN chunks ch ON ch.id = c.chunk_id - LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id - WHERE c.id = ? OR c.source_uri = ? - ORDER BY c.created_at DESC - LIMIT 1`).get(citationId, evidence.ref); - if (citation) { - const hashMismatch = Boolean(evidence.hash && citation.revision_hash && evidence.hash !== citation.revision_hash); - const revisionMismatch = Boolean(evidence.revision && citation.revision && evidence.revision !== citation.revision); - const oldRevision = Boolean(citation.revision_created_at && citation.latest_revision_at && citation.revision_created_at < citation.latest_revision_at); - const stale = explicitStale || staleStatus(metadataStatus(citation.chunk_metadata_json)) || hashMismatch || revisionMismatch || oldRevision; +async function initializeWikiLayout(store, now = new Date) { + const { year, month, day } = todayParts2(now); + const schemaKey = "schemas/v1.md"; + const rootIndexKey = "indexes/root.md"; + const wikiReadmeKey = "wiki/README.md"; + const logKey = `logs/${year}/${month}/${day}.jsonl`; + const event = { + ts: now.toISOString(), + event: "wiki_layout_initialized", + schema_key: schemaKey, + root_index_key: rootIndexKey, + wiki_readme_key: wikiReadmeKey + }; + const entries = [ + { key: schemaKey, body: agentSchemaTemplate(), content_type: "text/markdown" }, + { key: rootIndexKey, body: rootIndexTemplate(), content_type: "text/markdown" }, + { key: wikiReadmeKey, body: wikiReadmeTemplate(), content_type: "text/markdown" }, + { key: logKey, body: `${JSON.stringify(event)} +`, content_type: "application/x-ndjson" } + ]; + const artifacts = await Promise.all(entries.map(async (entry) => { + const result = await store.put(entry); return { - ref: evidence.ref, - valid: true, - resolved_by: "citation", - stale, - reason: hashMismatch ? "hash_mismatch" : revisionMismatch ? "revision_mismatch" : oldRevision ? "newer_source_revision" : stale ? "stale_citation" : null + key: result.key, + uri: result.uri, + kind: artifactKindForKey(entry.key), + content_type: entry.content_type, + modified_at: result.modified_at, + metadata: { + provenance: generatedArtifactProvenance({ + generated_from: "wiki_layout_init", + artifact_key: entry.key, + citation_required: entry.key.startsWith("wiki/") || entry.key.startsWith("indexes/") + }) + }, + ...hashArtifactBody(entry.body) }; - } - const chunkId = chunkIdentifier(evidence); - if (chunkId) { - const chunk = db.query(`SELECT ch.metadata_json, sr.hash, sr.revision - FROM chunks ch LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id - WHERE ch.id = ?`).get(chunkId); - if (!chunk) - return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "chunk_not_found" }; - const mismatch = Boolean(evidence.hash && chunk.hash && evidence.hash !== chunk.hash || evidence.revision && chunk.revision && evidence.revision !== chunk.revision); - const stale = explicitStale || staleStatus(metadataStatus(chunk.metadata_json)) || mismatch; - return { ref: evidence.ref, valid: true, resolved_by: "chunk", stale, reason: mismatch ? "source_version_mismatch" : stale ? "stale_chunk" : null }; - } - const source = db.query("SELECT metadata_json FROM sources WHERE uri = ? LIMIT 1").get(evidence.ref); - if (source) { - const stale = explicitStale || staleStatus(metadataStatus(source.metadata_json)); - return { ref: evidence.ref, valid: true, resolved_by: "source", stale, reason: stale ? "stale_source" : null }; - } - const runMatch = evidence.ref.match(/^knowledge:\/\/project\/runs\/([^/?#]+)/); - if (runMatch) { - const run = db.query("SELECT id FROM runs WHERE id = ?").get(decodeURIComponent(runMatch[1])); - if (!run) - return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "run_not_found" }; - return { ref: evidence.ref, valid: true, resolved_by: "run", stale: explicitStale, reason: explicitStale ? "expired_evidence" : null }; - } + })); return { - ref: evidence.ref, - valid: true, - resolved_by: "external_uri", - stale: explicitStale, - reason: explicitStale ? "expired_evidence" : null + schema_key: schemaKey, + root_index_key: rootIndexKey, + wiki_readme_key: wikiReadmeKey, + log_key: logKey, + artifacts, + written: [schemaKey, rootIndexKey, wikiReadmeKey, logKey] }; } -function candidateById(db, id) { - return db.query("SELECT * FROM knowledge_promotion_candidates WHERE id = ?").get(id) ?? null; -} -function assessCandidate(db, row, now) { - const evidence = parseJson3(row.evidence_refs_json, []); - const sourceRefs = parseJson3(row.source_refs_json, []); - const metadata = parseJson3(row.metadata_json, {}); - const checks3 = emptyChecks(); - checks3.invalid_source_refs = sourceRefs.filter((ref) => !validReference(ref)); - checks3.citations.entries = evidence.map((entry) => inspectCitation(db, entry, now)); - checks3.citations.provided = evidence.length; - checks3.citations.valid = checks3.citations.entries.filter((entry) => entry.valid).length; - checks3.citations.invalid = checks3.citations.entries.length - checks3.citations.valid; - checks3.stale_refs = checks3.citations.entries.filter((entry) => entry.stale).map((entry) => entry.ref); - checks3.duplicate_record_ids = db.query(`SELECT id FROM durable_knowledge_records - WHERE record_kind = ? AND content_hash = ? AND status IN ('active', 'conflicted') - ORDER BY created_at`).all(row.record_kind, row.content_hash).map((entry) => entry.id); - checks3.duplicate_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates - WHERE id <> ? AND record_kind = ? AND content_hash = ? AND status NOT IN ('rejected') - ORDER BY created_at`).all(row.id, row.record_kind, row.content_hash).map((entry) => entry.id); - checks3.conflicting_record_ids = db.query(`SELECT id FROM durable_knowledge_records - WHERE record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('active', 'conflicted') - ORDER BY created_at`).all(row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); - checks3.conflicting_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates - WHERE id <> ? AND record_kind = ? AND canonical_key = ? AND content_hash <> ? - AND status IN ('ready', 'needs_approval', 'promoted') - ORDER BY created_at`).all(row.id, row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); - const duplicateOf = checks3.duplicate_record_ids[0] ?? checks3.duplicate_candidate_ids[0] ?? null; - const blocked = sourceRefs.length === 0 || evidence.length === 0 || checks3.invalid_source_refs.length > 0 || checks3.citations.invalid > 0; - if (row.record_kind === "decision" || row.record_kind === "claim") - checks3.approval_reasons.push(`${row.record_kind}_requires_review`); - if (metadata.requested_approval === true) - checks3.approval_reasons.push("explicit_approval_request"); - if (checks3.stale_refs.length > 0) - checks3.approval_reasons.push("stale_evidence"); - if (checks3.conflicting_record_ids.length > 0 || checks3.conflicting_candidate_ids.length > 0) { - checks3.approval_reasons.push("conflicting_knowledge"); +function provenanceFor(artifact) { + const existing = artifact.metadata?.provenance; + if (existing && typeof existing === "object" && !Array.isArray(existing)) { + return existing; } - const requiresApproval = checks3.approval_reasons.length > 0; - const status = duplicateOf ? "duplicate" : blocked ? "blocked" : requiresApproval ? "needs_approval" : "ready"; - db.run(`UPDATE knowledge_promotion_candidates - SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? - WHERE id = ?`, [status, requiresApproval ? 1 : 0, JSON.stringify(checks3), duplicateOf, now, now, row.id]); - return asCandidate(candidateById(db, row.id)); + return generatedArtifactProvenance({ + generated_from: "wiki_layout_init", + artifact_key: artifact.key + }); } -function enqueueKnowledgePromotion(dbPath, input) { - const kinds = ["lesson", "decision", "claim"]; - const sourceKinds = ["memento", "session", "report"]; - if (!kinds.includes(input.kind)) - throw new Error("Promotion kind must be lesson, decision, or claim."); - if (!sourceKinds.includes(input.sourceKind)) - throw new Error("Promotion source kind must be memento, session, or report."); - const titleResult = redactSecrets(normalizedText(input.title)); - const contentResult = redactSecrets(normalizedText(input.content)); - if (!titleResult.text) - throw new Error("Promotion title is required."); - if (!contentResult.text) - throw new Error("Promotion content is required."); - const sourceRefs = Array.from(new Set(input.sourceRefs.map(normalizedText).filter(Boolean))).sort(); - const evidenceRefs = input.evidenceRefs.map(normalizeEvidenceRef).filter((entry) => entry.ref.length > 0).sort((a, b) => a.ref.localeCompare(b.ref)); - const canonicalKey = normalizedKey(input.canonicalKey ?? titleResult.text); - if (!canonicalKey) - throw new Error("Promotion canonical key is empty after normalization."); - const contentHash = `sha256:${createHash14("sha256").update(`${input.kind}\x00${normalizedText(contentResult.text).toLowerCase()}`).digest("hex")}`; - const idempotencyKey = stableId7("promote", [ - input.sourceKind, - input.kind, - canonicalKey, - contentHash, - ...sourceRefs - ].join("\x00")); - const id = stableId7("promotion", idempotencyKey); - const now = (input.now ?? new Date).toISOString(); - const metadata = { - ...input.metadata ?? {}, - requested_approval: input.requiresApproval === true, - confidence: input.confidence ?? null, - valid_from: input.validFrom ?? now, - valid_to: input.validTo ?? null, - redactions: titleResult.findings.length + contentResult.findings.length - }; - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - try { - const existing = db.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(idempotencyKey); - if (existing) - return { created: false, candidate: asCandidate(existing) }; - db.run(`INSERT INTO knowledge_promotion_candidates ( - id, record_kind, title, content, canonical_key, content_hash, source_kind, - source_refs_json, evidence_refs_json, status, requires_approval, checks_json, - idempotency_key, metadata_json, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`, [ - id, - input.kind, - titleResult.text, - contentResult.text, - canonicalKey, - contentHash, - input.sourceKind, - JSON.stringify(sourceRefs), - JSON.stringify(evidenceRefs), - idempotencyKey, - JSON.stringify(metadata), - now, - now +function recordWikiChunk(db, pageId, title, artifact, body, now) { + const provenance = provenanceFor(artifact); + const chunkId = stableId10("chk", `${pageId}\x00${artifact.hash ?? artifact.uri}`); + const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(pageId); + for (const row of existing) + db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); + db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [pageId]); + db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + chunkId, + pageId, + "wiki", + 0, + body, + estimateTokenCount4(body), + 0, + body.length, + JSON.stringify({ + artifact_key: artifact.key, + artifact_uri: artifact.uri, + content_hash: artifact.hash ?? null, + provenance + }), + now + ]); + db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [chunkId, body, title, artifact.uri]); +} +function recordWikiLayoutCatalog(db, artifacts, now = new Date) { + const timestamp = now.toISOString(); + const rootIndex = artifacts.find((artifact) => artifact.key.endsWith("indexes/root.md")); + const wikiReadme = artifacts.find((artifact) => artifact.key.endsWith("wiki/README.md")); + if (rootIndex) { + db.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(kind, name, shard_key) DO UPDATE SET + artifact_uri = excluded.artifact_uri, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at`, [ + stableId10("idx", "root:indexes/root.md"), + "root", + "root", + rootIndex.uri, + "root", + JSON.stringify({ + artifact_key: rootIndex.key, + content_hash: rootIndex.hash ?? null, + provenance: provenanceFor(rootIndex) + }), + timestamp, + timestamp ]); - const findings = [...titleResult.findings, ...contentResult.findings]; - if (findings.length > 0) { - recordRedactionFindings(db, { - source_uri: sourceRefs[0] ?? `knowledge://promotion/${id}`, - findings, - metadata: { promotion_candidate_id: id }, - created_at: now - }); - } - recordAuditEvent(db, { - event_type: "knowledge_promotion", - action: "enqueue_promotion", - target_uri: `knowledge://promotion/${id}`, - decision: "info", - metadata: { record_kind: input.kind, source_kind: input.sourceKind, source_refs: sourceRefs }, - created_at: now - }); - return { created: true, candidate: assessCandidate(db, candidateById(db, id), now) }; - } finally { - db.close(); + } + if (wikiReadme) { + const wikiPageId = stableId10("wiki", "wiki/README.md"); + db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(path) DO UPDATE SET + title = excluded.title, + artifact_uri = excluded.artifact_uri, + content_hash = excluded.content_hash, + status = excluded.status, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at`, [ + wikiPageId, + "wiki/README.md", + "Wiki", + wikiReadme.uri, + wikiReadme.hash ?? null, + "active", + JSON.stringify({ + artifact_key: wikiReadme.key, + provenance: provenanceFor(wikiReadme) + }), + timestamp, + timestamp + ]); + recordWikiChunk(db, wikiPageId, "Wiki", wikiReadme, wikiReadmeTemplate(), timestamp); } } -function getKnowledgePromotion(dbPath, id) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); + +// src/workspace-migration.ts +import { createHash as createHash20 } from "crypto"; +import { + cpSync, + chmodSync as chmodSync4, + existsSync as existsSync13, + lstatSync as lstatSync3, + mkdirSync as mkdirSync4, + readdirSync as readdirSync3, + readFileSync as readFileSync14, + renameSync as renameSync2, + rmSync, + writeFileSync as writeFileSync5 +} from "fs"; +import { dirname as dirname5, join as join8, relative as relative5 } from "path"; +function walkFiles(root, base = root) { + if (!existsSync13(root)) + return []; + const stat = lstatSync3(root); + if (stat.isFile()) + return [relative5(base, root) || "."]; + if (!stat.isDirectory()) + return []; + return readdirSync3(root).flatMap((entry) => walkFiles(join8(root, entry), base)).sort(); +} +function hashFiles(root, files) { + if (files.length === 0) + return { sha256: null, bytes: 0 }; + const tree = createHash20("sha256"); + let bytes = 0; + for (const file2 of files) { + const path = join8(root, file2); + const body = readFileSync14(path); + const fileHash = createHash20("sha256").update(body).digest("hex"); + bytes += body.byteLength; + tree.update(file2); + tree.update("\x00"); + tree.update(fileHash); + tree.update("\x00"); + } + return { sha256: tree.digest("hex"), bytes }; +} +function jsonItemCount(path) { + if (!existsSync13(path)) + return null; + const parsed = JSON.parse(readFileSync14(path, "utf8")); + return Array.isArray(parsed.items) ? parsed.items.length : null; +} +function sqliteSummary(path) { + if (!existsSync13(path)) { + return { exists: false, integrity_check: null, table_counts: {} }; + } + const db = openKnowledgeDbReadonly(path); try { - const row = candidateById(db, id); - return row ? asCandidate(row) : null; + const integrity = db.query("PRAGMA integrity_check").get(); + const integrityCheck = integrity ? Object.values(integrity)[0] ?? null : null; + const tables = db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(); + const tableCounts2 = {}; + for (const table of tables) { + const quoted = `"${table.name.replaceAll('"', '""')}"`; + const count3 = db.query(`SELECT COUNT(*) AS n FROM ${quoted}`).get(); + tableCounts2[table.name] = count3?.n ?? 0; + } + return { exists: true, integrity_check: integrityCheck, table_counts: tableCounts2 }; } finally { db.close(); } } -function listKnowledgePromotions(dbPath, options = {}) { - migrateKnowledgeDb(dbPath); - const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); - const conditions = []; - const params = []; - if (options.status === "inbox" || !options.status) { - conditions.push("status IN ('ready', 'needs_approval', 'blocked')"); - } else { - conditions.push("status = ?"); - params.push(options.status); - } - if (options.kind) { - conditions.push("record_kind = ?"); - params.push(options.kind); - } - const db = openKnowledgeDb(dbPath); +function summarizeWorkspaceTree(workspace, options = {}) { + const files = walkFiles(workspace.home); + const treeHash = hashFiles(workspace.home, files); + const artifactFiles = walkFiles(workspace.artifactsDir); + const artifactHash = hashFiles(workspace.artifactsDir, artifactFiles); + const sqliteExists = existsSync13(workspace.knowledgeDbPath); + return { + path: workspace.home, + exists: existsSync13(workspace.home), + file_count: files.length, + total_bytes: treeHash.bytes, + tree_sha256: treeHash.sha256, + json_items: jsonItemCount(workspace.jsonStorePath), + sqlite: options.includeSqlite === false ? { exists: sqliteExists, integrity_check: null, table_counts: {} } : sqliteSummary(workspace.knowledgeDbPath), + artifacts: { + exists: existsSync13(workspace.artifactsDir), + file_count: artifactFiles.length, + total_bytes: artifactHash.bytes, + tree_sha256: artifactHash.sha256 + }, + files + }; +} +function isDefaultScaffold(workspace, summary) { + if (!summary.exists) + return true; + const materialFiles = summary.files.filter((file2) => file2 !== "config.json"); + if (materialFiles.length > 0) + return false; + if (!summary.files.includes("config.json")) + return true; try { - return db.query(`SELECT * FROM knowledge_promotion_candidates - WHERE ${conditions.join(" AND ")} - ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(...params, limit).map(asCandidate); - } finally { - db.close(); + return JSON.stringify(JSON.parse(readFileSync14(workspace.configPath, "utf8"))) === JSON.stringify(defaultKnowledgeConfig()); + } catch { + return false; } } -function reviewKnowledgePromotion(dbPath, id, now = new Date) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - try { - const row = candidateById(db, id); - if (!row) - throw new Error(`Promotion candidate not found: ${id}`); - if (row.status === "promoted" || row.status === "rejected") - return asCandidate(row); - return assessCandidate(db, row, now.toISOString()); - } finally { - db.close(); +function summariesMatch(left, right) { + return left.file_count === right.file_count && left.total_bytes === right.total_bytes && left.tree_sha256 === right.tree_sha256 && left.json_items === right.json_items && left.sqlite.integrity_check === right.sqlite.integrity_check && JSON.stringify(left.sqlite.table_counts) === JSON.stringify(right.sqlite.table_counts) && left.artifacts.file_count === right.artifacts.file_count && left.artifacts.total_bytes === right.artifacts.total_bytes && left.artifacts.tree_sha256 === right.artifacts.tree_sha256; +} +function migrationTimestamp(now) { + return now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); +} +function stableJson2(value) { + if (Array.isArray(value)) + return `[${value.map(stableJson2).join(",")}]`; + if (value && typeof value === "object") { + return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson2(entry)}`).join(",")}}`; } + return JSON.stringify(value); } -function promoteKnowledgeCandidate(dbPath, id, options = {}) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - const now = (options.now ?? new Date).toISOString(); - try { - const row = candidateById(db, id); - if (!row) - throw new Error(`Promotion candidate not found: ${id}`); - if (row.status === "promoted" && row.promoted_record_id) { - const existingRecord = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(row.promoted_record_id); - return { - ok: true, - promoted: false, - requires_approval: row.requires_approval === 1, - candidate: asCandidate(row), - record: existingRecord ? asDurableRecord(existingRecord) : null, - approval_id: null, - reason: "already_promoted" - }; - } - if (row.status === "rejected") - throw new Error(`Promotion candidate ${id} was rejected.`); - const candidate = assessCandidate(db, row, now); - if (candidate.status === "duplicate") { - return { ok: true, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "duplicate" }; +function itemSignature(item) { + return stableJson2(item); +} +function itemShortId(item) { + return typeof item.short_id === "string" && item.short_id.trim().length > 0 ? item.short_id : null; +} +function readMergeStore(path) { + if (!existsSync13(path)) + return { items: [] }; + const parsed = JSON.parse(readFileSync14(path, "utf8")); + if (!parsed || !Array.isArray(parsed.items)) { + throw new Error(`Invalid knowledge JSON store shape at ${path}`); + } + return { items: parsed.items }; +} +function mergeStats(currentStore, legacyStore) { + const currentById = new Map(currentStore.items.map((item) => [item.id, item])); + const reservedKeys = new Map; + for (const item of currentStore.items) { + const existingId = reservedKeys.get(item.id); + if (existingId && existingId.item.id !== item.id) {} + reservedKeys.set(item.id, { item, keyKind: "id", source: "current" }); + const shortId = itemShortId(item); + if (shortId && !reservedKeys.has(shortId)) { + reservedKeys.set(shortId, { item, keyKind: "short_id", source: "current" }); } - if (candidate.status === "blocked") { - return { ok: false, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "citation_check_failed" }; + } + const conflicts = []; + let duplicateIdsIdentical = 0; + let duplicateIdsConflicting = 0; + let shortIdConflicts = 0; + const stranded = []; + for (const legacyItem of legacyStore.items) { + const currentItem = currentById.get(legacyItem.id); + if (currentItem) { + if (itemSignature(currentItem) === itemSignature(legacyItem)) { + duplicateIdsIdentical += 1; + } else { + duplicateIdsConflicting += 1; + conflicts.push({ + type: "id_conflict", + id: legacyItem.id, + legacy_title: legacyItem.title, + current_title: currentItem.title + }); + } + continue; } - if (candidate.requires_approval && !options.approveWrite) { - return { ok: false, promoted: false, requires_approval: true, candidate, record: null, approval_id: null, reason: "approval_required" }; + const keys = [ + { key: legacyItem.id, keyKind: "id" }, + ...itemShortId(legacyItem) ? [{ key: itemShortId(legacyItem), keyKind: "short_id" }] : [] + ]; + let itemHasConflict = false; + for (const { key, keyKind } of keys) { + const existing = reservedKeys.get(key); + if (!existing) + continue; + if (keyKind === "id" && existing.keyKind === "id") { + duplicateIdsConflicting += 1; + conflicts.push({ + type: "id_conflict", + id: key, + legacy_id: legacyItem.id, + current_id: existing.item.id, + legacy_title: legacyItem.title, + current_title: existing.item.title + }); + } else { + shortIdConflicts += 1; + conflicts.push({ + type: "short_id_conflict", + id: key, + legacy_id: legacyItem.id, + current_id: existing.item.id, + legacy_title: legacyItem.title, + current_title: existing.item.title + }); + } + itemHasConflict = true; } - if (candidate.requires_approval && !options.approvedBy?.trim()) { - throw new Error("Promotion approval requires --approved-by <name>."); + if (itemHasConflict) { + continue; } - const approvedBy = candidate.requires_approval ? options.approvedBy.trim() : null; - let approvalId = null; - if (candidate.requires_approval) { - approvalId = createApprovalGate(db, { - action: "promote_durable_knowledge", - target_uri: `knowledge://promotion/${candidate.id}`, - reason: candidate.checks.approval_reasons.join(", "), - approved_by: approvedBy, - metadata: { promotion_candidate_id: candidate.id, checks: candidate.checks }, - created_at: now - }).id; + stranded.push(legacyItem); + for (const { key, keyKind } of keys) { + reservedKeys.set(key, { item: legacyItem, keyKind, source: "legacy" }); } - const recordId = stableId7("durable", candidate.id); - const metadata = { - ...candidate.metadata, - promotion_candidate_id: candidate.id, - source_kind: candidate.source_kind, - checks: candidate.checks, - approval_id: approvalId, - provenance: generatedArtifactProvenance({ - generated_from: `knowledge://promotion/${candidate.id}`, - artifact_key: `durable/${candidate.record_kind}/${candidate.canonical_key}`, - source_refs: candidate.source_refs, - citation_required: true - }) - }; - db.run(`INSERT INTO durable_knowledge_records ( - id, record_kind, title, content, canonical_key, content_hash, status, - source_refs_json, evidence_refs_json, confidence, valid_from, valid_to, - promoted_from_candidate_id, approved_by, metadata_json, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - recordId, - candidate.record_kind, - candidate.title, - candidate.content, - candidate.canonical_key, - candidate.content_hash, - candidate.checks.conflicting_record_ids.length > 0 ? "conflicted" : "active", - JSON.stringify(candidate.source_refs), - JSON.stringify(candidate.evidence_refs), - typeof candidate.metadata.confidence === "number" ? candidate.metadata.confidence : null, - typeof candidate.metadata.valid_from === "string" ? candidate.metadata.valid_from : now, - typeof candidate.metadata.valid_to === "string" ? candidate.metadata.valid_to : null, - candidate.id, - approvedBy, - JSON.stringify(metadata), - now, - now - ]); - db.run(`UPDATE knowledge_promotion_candidates - SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? - WHERE id = ?`, [approvedBy, recordId, now, now, candidate.id]); - recordAuditEvent(db, { - event_type: "knowledge_promotion", - action: "promote_durable_knowledge", - target_uri: `knowledge://durable/${recordId}`, - decision: "allow", - metadata: { promotion_candidate_id: candidate.id, approval_id: approvalId, source_refs: candidate.source_refs }, - created_at: now - }); - const promotedCandidate = asCandidate(candidateById(db, candidate.id)); - const record2 = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(recordId); + } + const mergedStore = { items: [...currentStore.items, ...stranded] }; + return { + stats: { + current_items: currentStore.items.length, + legacy_items: legacyStore.items.length, + duplicate_ids_identical: duplicateIdsIdentical, + duplicate_ids_conflicting: duplicateIdsConflicting, + short_id_conflicts: shortIdConflicts, + stranded_items: stranded.length, + merged_items: conflicts.length === 0 ? stranded.length : 0, + expected_total_items: currentStore.items.length + stranded.length, + final_items: null + }, + conflicts, + mergedStore + }; +} +function withStoreLocks(paths, fn) { + const uniquePaths = [...new Set(paths)].sort(); + const run = (index) => { + if (index >= uniquePaths.length) + return fn(); + return withLock(uniquePaths[index], () => run(index + 1), { createParent: true }); + }; + return run(0); +} +function mergeLegacyKnowledgeWorkspace(options) { + const now = options.now ?? new Date; + const dryRun = options.approveWrite !== true; + const legacyBefore = summarizeWorkspaceTree(options.legacy); + const currentBefore = summarizeWorkspaceTree(options.current); + const checks3 = { + legacy_exists: legacyBefore.exists, + legacy_store_exists: existsSync13(options.legacy.jsonStorePath), + current_store_exists: existsSync13(options.current.jsonStorePath), + approval_present: options.approveWrite === true && Boolean(options.approvedBy), + legacy_backup_written: false, + no_conflicts: false, + final_count_matches_expected: false + }; + const warnings = []; + if (!legacyBefore.exists || !checks3.legacy_store_exists) { return { ok: true, - promoted: true, - requires_approval: candidate.requires_approval, - candidate: promotedCandidate, - record: asDurableRecord(record2), - approval_id: approvalId, - reason: null + dry_run: dryRun, + approval_required: false, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: null, + legacy_before: legacyBefore, + current_before: currentBefore, + backup_after: null, + current_after: currentBefore, + merge: { + current_items: readMergeStore(options.current.jsonStorePath).items.length, + legacy_items: 0, + duplicate_ids_identical: 0, + duplicate_ids_conflicting: 0, + short_id_conflicts: 0, + stranded_items: 0, + merged_items: 0, + expected_total_items: readMergeStore(options.current.jsonStorePath).items.length, + final_items: currentBefore.json_items + }, + conflicts: [], + checks: { + ...checks3, + no_conflicts: true, + final_count_matches_expected: true + }, + warnings, + message: `No legacy knowledge JSON store found at ${options.legacy.jsonStorePath}` }; - } finally { - db.close(); } -} -function rejectKnowledgePromotion(dbPath, id, options = {}) { - migrateKnowledgeDb(dbPath); - const db = openKnowledgeDb(dbPath); - const now = (options.now ?? new Date).toISOString(); - try { - const row = candidateById(db, id); - if (!row) - throw new Error(`Promotion candidate not found: ${id}`); - if (row.status === "promoted") - throw new Error(`Promotion candidate ${id} is already promoted.`); - db.run(`UPDATE knowledge_promotion_candidates - SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? - WHERE id = ?`, [options.rejectedBy?.trim() || null, now, now, id]); - recordAuditEvent(db, { - event_type: "knowledge_promotion", - action: "reject_promotion", - target_uri: `knowledge://promotion/${id}`, - decision: "deny", - metadata: { rejected_by: options.rejectedBy ?? null }, - created_at: now - }); - return asCandidate(candidateById(db, id)); - } finally { - db.close(); + const currentStore = readMergeStore(options.current.jsonStorePath); + const legacyStore = readMergeStore(options.legacy.jsonStorePath); + const planned = mergeStats(currentStore, legacyStore); + checks3.no_conflicts = planned.conflicts.length === 0; + if (planned.conflicts.length > 0) + warnings.push("merge_conflicts_detected"); + if (!checks3.approval_present) + warnings.push("write_approval_required"); + if (dryRun || !checks3.approval_present || planned.conflicts.length > 0) { + return { + ok: planned.conflicts.length === 0, + dry_run: true, + approval_required: !checks3.approval_present, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: `${options.legacy.home}.merge-backup-${migrationTimestamp(now)}`, + legacy_before: legacyBefore, + current_before: currentBefore, + backup_after: null, + current_after: null, + merge: planned.stats, + conflicts: planned.conflicts, + checks: checks3, + warnings, + message: planned.conflicts.length === 0 ? `Dry run: would merge ${planned.stats.stranded_items} legacy item(s) into ${options.current.jsonStorePath}` : `Refusing legacy merge with ${planned.conflicts.length} conflict(s)` + }; } + return withStoreLocks([options.current.jsonStorePath, options.legacy.jsonStorePath], () => { + const lockedCurrentStore = readMergeStore(options.current.jsonStorePath); + const lockedLegacyStore = readMergeStore(options.legacy.jsonStorePath); + const lockedPlan = mergeStats(lockedCurrentStore, lockedLegacyStore); + checks3.no_conflicts = lockedPlan.conflicts.length === 0; + if (lockedPlan.conflicts.length > 0) { + return { + ok: false, + dry_run: true, + approval_required: false, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: null, + legacy_before: summarizeWorkspaceTree(options.legacy), + current_before: summarizeWorkspaceTree(options.current), + backup_after: null, + current_after: null, + merge: lockedPlan.stats, + conflicts: lockedPlan.conflicts, + checks: checks3, + warnings: [...warnings, "merge_conflicts_detected_after_lock"], + message: `Refusing legacy merge with ${lockedPlan.conflicts.length} conflict(s)` + }; + } + if (lockedPlan.stats.stranded_items === 0) { + lockedPlan.stats.final_items = lockedCurrentStore.items.length; + checks3.final_count_matches_expected = lockedCurrentStore.items.length === lockedPlan.stats.expected_total_items; + return { + ok: checks3.no_conflicts && checks3.final_count_matches_expected, + dry_run: false, + approval_required: false, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: null, + legacy_before: summarizeWorkspaceTree(options.legacy), + current_before: summarizeWorkspaceTree(options.current), + backup_after: null, + current_after: summarizeWorkspaceTree(options.current), + merge: lockedPlan.stats, + conflicts: [], + checks: checks3, + warnings, + message: `Legacy merge already up to date for ${options.current.jsonStorePath}` + }; + } + const backupHome = `${options.legacy.home}.merge-backup-${migrationTimestamp(now)}`; + mkdirSync4(dirname5(backupHome), { recursive: true }); + cpSync(options.legacy.home, backupHome, { + recursive: true, + force: false, + errorOnExist: true, + preserveTimestamps: true + }); + const backupWorkspace = workspaceForHome(backupHome); + const backupAfter = summarizeWorkspaceTree(backupWorkspace); + checks3.legacy_backup_written = summariesMatch(summarizeWorkspaceTree(options.legacy), backupAfter); + if (!checks3.legacy_backup_written) { + throw new Error(`Legacy knowledge merge backup verification failed: ${backupHome}`); + } + saveStore(options.current.jsonStorePath, lockedPlan.mergedStore); + const finalStore = readMergeStore(options.current.jsonStorePath); + lockedPlan.stats.final_items = finalStore.items.length; + checks3.final_count_matches_expected = finalStore.items.length === lockedPlan.stats.expected_total_items; + const currentAfter = summarizeWorkspaceTree(options.current); + const ok = checks3.legacy_backup_written && checks3.no_conflicts && checks3.final_count_matches_expected; + return { + ok, + dry_run: false, + approval_required: false, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: backupHome, + legacy_before: legacyBefore, + current_before: currentBefore, + backup_after: backupAfter, + current_after: currentAfter, + merge: lockedPlan.stats, + conflicts: [], + checks: checks3, + warnings, + message: ok ? `Merged ${lockedPlan.stats.merged_items} legacy item(s) into ${options.current.jsonStorePath}` : `Merged legacy knowledge store, but verification failed for ${options.current.jsonStorePath}` + }; + }); } -function listDurableKnowledgeRecords(dbPath, options = {}) { - migrateKnowledgeDb(dbPath); - const conditions = []; - const params = []; - if (options.kind) { - conditions.push("record_kind = ?"); - params.push(options.kind); - } - if (options.status) { - conditions.push("status = ?"); - params.push(options.status); - } - const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); - const db = openKnowledgeDb(dbPath); - try { - return db.query(`SELECT * FROM durable_knowledge_records - ${conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""} - ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(...params, limit).map(asDurableRecord); - } finally { - db.close(); +function sleepSync2(milliseconds) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); +} +function isRetriableFsLock(error51) { + return error51 instanceof Error && /\b(EBUSY|EPERM)\b/.test(error51.message); +} +function removeWorkspaceWithRetries(path) { + let lastError; + for (let attempt = 0;attempt < 8; attempt += 1) { + try { + rmSync(path, { recursive: true, force: false }); + return; + } catch (error51) { + lastError = error51; + if (!isRetriableFsLock(error51)) + throw error51; + sleepSync2(50 * (attempt + 1)); + } } + throw lastError; } - -// src/reindex.ts -import { createHash as createHash15, randomUUID as randomUUID10 } from "crypto"; -function stableId8(prefix, value) { - return `${prefix}_${createHash15("sha256").update(value).digest("hex").slice(0, 20)}`; +function chmodOwnerOnlyTree(path) { + if (!existsSync13(path)) + return; + const stat = lstatSync3(path); + chmodSync4(path, stat.isDirectory() ? 448 : 384); + if (!stat.isDirectory()) + return; + for (const entry of readdirSync3(path)) + chmodOwnerOnlyTree(join8(path, entry)); } -function queueCounts(dbPath) { - const db = openKnowledgeDb(dbPath); +function isRetainedTombstoneFile(file2) { + return file2 === "TOMBSTONE.md" || file2 === "migration.json" || file2 === "knowledge.db" || file2 === "knowledge.db-shm" || file2 === "knowledge.db-wal" || file2 === "knowledge.db-journal"; +} +function prepareLegacyTombstoneDirectory(home) { + for (const file2 of readdirSync3(home)) { + if (file2 === "TOMBSTONE.md" || file2 === "migration.json") + continue; + try { + rmSync(join8(home, file2), { recursive: true, force: false }); + } catch (error51) { + if (!isRetriableFsLock(error51) || !file2.startsWith("knowledge.db")) + throw error51; + } + } +} +function moveWorkspace(sourceHome, targetHome) { try { - const rows = db.query(`SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status`).all(); - return Object.fromEntries(rows.map((row) => [row.status, row.n])); - } finally { - db.close(); + renameSync2(sourceHome, targetHome); + return; + } catch (error51) { + cpSync(sourceHome, targetHome, { + recursive: true, + force: false, + errorOnExist: true, + preserveTimestamps: true + }); + try { + removeWorkspaceWithRetries(sourceHome); + } catch (removeError) { + if (isRetriableFsLock(removeError)) { + prepareLegacyTombstoneDirectory(sourceHome); + return; + } + rmSync(targetHome, { recursive: true, force: true }); + throw removeError; + } + if (error51 instanceof Error && error51.message.includes("EXDEV")) + return; } } -function missingEmbeddingRows(dbPath, options) { - const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); - const parsed = parseModelRef(modelRef); - const db = openKnowledgeDb(dbPath); +function isMigrationTombstone(workspace, summary, currentHome) { + if (!summary.exists) + return false; + if (!summary.files.includes("TOMBSTONE.md") || !summary.files.includes("migration.json")) + return false; + if (summary.files.some((file2) => !isRetainedTombstoneFile(file2))) + return false; try { - return db.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri - FROM chunks c - LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id - LEFT JOIN sources s ON s.id = sr.source_id - LEFT JOIN vector_index_entries v ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? - WHERE v.id IS NULL - ORDER BY c.created_at ASC, c.ordinal ASC`).all(parsed.provider, parsed.model); - } finally { - db.close(); + const metadata = JSON.parse(readFileSync14(join8(workspace.home, "migration.json"), "utf8")); + return metadata.new_path === currentHome && typeof metadata.backup_path === "string"; + } catch { + return false; } } -function reindexHealth(options) { - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - try { - const version2 = db.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version ?? 0; - const chunks = db.query("SELECT COUNT(*) AS n FROM chunks").get()?.n ?? 0; - const vectorEntries = db.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n ?? 0; - const missing = missingEmbeddingRows(options.dbPath, options).length; - const stale = db.query(`SELECT COUNT(*) AS n FROM source_revisions - WHERE metadata_json LIKE '%"reindex_required":true%' OR metadata_json LIKE '%"status":"stale"%'`).get()?.n ?? 0; +function migrateLegacyKnowledgeWorkspace(options) { + const now = options.now ?? new Date; + const dryRun = options.approveWrite !== true; + const currentBefore = summarizeWorkspaceTree(options.current); + const currentIsDefaultScaffold = isDefaultScaffold(options.current, currentBefore); + const willMutateLegacy = options.approveWrite === true && Boolean(options.approvedBy) && (!currentBefore.exists || currentIsDefaultScaffold); + const legacyBefore = summarizeWorkspaceTree(options.legacy, { includeSqlite: !willMutateLegacy }); + const checks3 = { + legacy_exists: legacyBefore.exists, + current_absent_or_default_scaffold: !currentBefore.exists || currentIsDefaultScaffold, + approval_present: options.approveWrite === true && Boolean(options.approvedBy), + legacy_is_tombstone: false, + backup_matches_legacy: false, + migrated_matches_backup: false, + tombstone_written: false + }; + const warnings = []; + if (!legacyBefore.exists) { return { - schema_version: version2, - chunks, - vector_entries: vectorEntries, - missing_embeddings: missing, - queued: queueCounts(options.dbPath), - stale_revisions: stale + ok: true, + dry_run: dryRun, + approval_required: false, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: null, + tombstone_path: null, + legacy_before: legacyBefore, + current_before: currentBefore, + backup_after: null, + current_after: null, + checks: checks3, + warnings, + message: `No legacy knowledge workspace found at ${options.legacy.home}` }; - } finally { - db.close(); } -} -function enqueueMissingEmbeddings(options) { - migrateKnowledgeDb(options.dbPath); - const now = (options.now ?? new Date).toISOString(); - const reason = options.reason ?? "missing_embedding"; - const rows = missingEmbeddingRows(options.dbPath, options); - const db = openKnowledgeDb(options.dbPath); - let enqueued = 0; - let alreadyQueued = 0; - try { - const write = db.transaction(() => { - for (const row of rows) { - const id = stableId8("rq", `embedding\x00${row.chunk_id}\x00${reason}`); - const before = db.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding", row.chunk_id, reason); - if (before) { - alreadyQueued += 1; - continue; - } - db.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - id, - "embedding", - row.chunk_id, - row.source_uri, - reason, - "pending", - JSON.stringify({ source_revision_id: row.source_revision_id }), - now, - now - ]); - enqueued += 1; - } - }); - write(); - } finally { - db.close(); + checks3.legacy_is_tombstone = isMigrationTombstone(options.legacy, legacyBefore, options.current.home); + if (checks3.legacy_is_tombstone) { + return { + ok: true, + dry_run: dryRun, + approval_required: false, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: null, + tombstone_path: join8(options.legacy.home, "TOMBSTONE.md"), + legacy_before: legacyBefore, + current_before: currentBefore, + backup_after: null, + current_after: currentBefore, + checks: { + ...checks3, + tombstone_written: true + }, + warnings, + message: `Legacy knowledge workspace already migrated to ${options.current.home}` + }; } - return { enqueued, already_queued: alreadyQueued, reason }; -} -function clearEmbeddingIndex(dbPath) { - const db = openKnowledgeDb(dbPath); - try { - const embeddings = db.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n ?? 0; - const vectorEntries = db.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n ?? 0; - db.run("DELETE FROM vector_index_entries"); - db.run("DELETE FROM chunk_embeddings"); - return { embeddings, vectorEntries }; - } finally { - db.close(); + if (!checks3.current_absent_or_default_scaffold) { + warnings.push("current_workspace_contains_data"); } -} -function completeIndexedQueueItems(dbPath, options, now) { - const modelRef = resolveEmbeddingModelRef(options.modelRef, options.config); - const parsed = parseModelRef(modelRef); - const db = openKnowledgeDb(dbPath); - try { - const result = db.run(`UPDATE reindex_queue - SET status = ?, updated_at = ? - WHERE kind = ? - AND status = ? - AND EXISTS ( - SELECT 1 FROM vector_index_entries v - WHERE v.chunk_id = reindex_queue.target_id - AND v.provider = ? - AND v.model = ? - )`, ["completed", now, "embedding", "pending", parsed.provider, parsed.model]); - return result.changes; - } finally { - db.close(); + if (!checks3.approval_present) { + warnings.push("write_approval_required"); } -} -async function refreshEmbeddingIndex(options) { - migrateKnowledgeDb(options.dbPath); - const now = (options.now ?? new Date).toISOString(); - const runId = `run_${randomUUID10()}`; - const deleted = options.full ? clearEmbeddingIndex(options.dbPath) : { embeddings: 0, vectorEntries: 0 }; - const queued = enqueueMissingEmbeddings({ ...options, reason: options.full ? "full_embedding_rebuild" : "missing_embedding" }); - const db = openKnowledgeDb(options.dbPath); - try { - db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - runId, - "embedding-refresh", - options.full ? "full" : "incremental", - "running", - "local", - resolveEmbeddingModelRef(options.modelRef, options.config), - JSON.stringify({ full: options.full === true, queued }), - now, - now - ]); - } finally { - db.close(); + if (dryRun || !checks3.current_absent_or_default_scaffold || !checks3.approval_present) { + return { + ok: checks3.current_absent_or_default_scaffold, + dry_run: true, + approval_required: true, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: `${options.legacy.home}.backup-${migrationTimestamp(now)}`, + tombstone_path: join8(options.legacy.home, "TOMBSTONE.md"), + legacy_before: legacyBefore, + current_before: currentBefore, + backup_after: null, + current_after: null, + checks: checks3, + warnings, + message: checks3.current_absent_or_default_scaffold ? `Dry run: would migrate ${options.legacy.home} to ${options.current.home}` : `Cannot migrate while ${options.current.home} contains data` + }; } - const indexed = await indexKnowledgeEmbeddings({ - dbPath: options.dbPath, - config: options.config, - env: options.env, - modelRef: options.modelRef, - dimensions: options.dimensions, - fake: options.fake, - limit: options.limit, - now: options.now + const backupHome = `${options.legacy.home}.backup-${migrationTimestamp(now)}`; + mkdirSync4(dirname5(options.current.home), { recursive: true }); + mkdirSync4(dirname5(backupHome), { recursive: true }); + cpSync(options.legacy.home, backupHome, { + recursive: true, + force: false, + errorOnExist: true, + preserveTimestamps: true }); - const completedQueueItems = completeIndexedQueueItems(options.dbPath, options, now); - const doneDb = openKnowledgeDb(options.dbPath); - try { - doneDb.run(`UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?`, [ - "completed", - JSON.stringify({ full: options.full === true, queued, indexed, completed_queue_items: completedQueueItems }), - now, - runId - ]); - doneDb.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, [ - `evt_${randomUUID10()}`, - runId, - "info", - "embedding_refresh_completed", - JSON.stringify({ queued, indexed, completed_queue_items: completedQueueItems }), - now - ]); - } finally { - doneDb.close(); + chmodOwnerOnlyTree(backupHome); + const backupWorkspace = workspaceForHome(backupHome); + const backupSnapshot = summarizeWorkspaceTree(backupWorkspace, { includeSqlite: false }); + checks3.backup_matches_legacy = summariesMatch(legacyBefore, backupSnapshot); + if (!checks3.backup_matches_legacy) { + throw new Error(`Legacy knowledge backup verification failed: ${backupHome}`); } + if (currentBefore.exists && currentIsDefaultScaffold) { + rmSync(options.current.home, { recursive: true, force: true }); + } + moveWorkspace(options.legacy.home, options.current.home); + const currentSnapshot = summarizeWorkspaceTree(options.current, { includeSqlite: false }); + checks3.migrated_matches_backup = summariesMatch(backupSnapshot, currentSnapshot); + const backupAfter = summarizeWorkspaceTree(backupWorkspace); + const currentAfter = summarizeWorkspaceTree(options.current); + const legacyBeforeOutput = { ...backupAfter, path: options.legacy.home }; + mkdirSync4(options.legacy.home, { recursive: true }); + const tombstonePath = join8(options.legacy.home, "TOMBSTONE.md"); + writeFileSync5(tombstonePath, [ + "# Migrated OpenKnowledge Workspace", + "", + `Migrated at: ${now.toISOString()}`, + `Approved by: ${options.approvedBy}`, + `New path: ${options.current.home}`, + `Backup path: ${backupHome}`, + "", + "This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.", + "" + ].join(` +`), { mode: 384 }); + chmodSync4(tombstonePath, 384); + const migrationJsonPath = join8(options.legacy.home, "migration.json"); + writeFileSync5(migrationJsonPath, `${JSON.stringify({ + migrated_at: now.toISOString(), + approved_by: options.approvedBy, + new_path: options.current.home, + backup_path: backupHome, + legacy_before: legacyBeforeOutput, + backup_after: backupAfter, + current_after: currentAfter + }, null, 2)} +`, { mode: 384 }); + chmodSync4(migrationJsonPath, 384); + checks3.tombstone_written = existsSync13(tombstonePath); + const ok = checks3.backup_matches_legacy && checks3.migrated_matches_backup && checks3.tombstone_written; return { - run_id: runId, - full: options.full === true, - deleted_embeddings: deleted.embeddings, - deleted_vector_entries: deleted.vectorEntries, - queued, - indexed, - completed_queue_items: completedQueueItems - }; -} - -// src/rules-provenance.ts -import { createHash as createHash16 } from "crypto"; -import { existsSync as existsSync11, lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync12, statSync as statSync2 } from "fs"; -import { basename as basename5, extname as extname2, join as join6, relative as relative4, resolve as resolve4, sep as sep4 } from "path"; -import { pathToFileURL as pathToFileURL3 } from "url"; -var DEFAULT_MAX_ITEMS2 = 100; -var DEFAULT_EVIDENCE_LIMIT = 25; -var DEFAULT_MAX_BYTES_PER_FILE = 256 * 1024; -var WALK_MAX_DEPTH = 5; -var TEXT_EXTENSIONS = new Set([".md", ".mdx", ".txt", ".json", ".jsonc", ".toml", ".yaml", ".yml"]); -var ROOT_RULE_DOCS = new Set(["CODEWITH.md", "AGENTS.md", "CLAUDE.md", "RULES.md", "INSTRUCTIONS.md"]); -var SKIP_DIRECTORIES = new Set([ - ".git", - "node_modules", - "dist", - "build", - ".codewith-worktrees", - ".connect", - ".secrets", - ".tmp", - "tmp", - "auth_profiles", - "profiles", - "preserved", - "backup", - "backups", - "cache", - "logs", - "runs" -]); -var SENSITIVE_PATH_RE = /(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i; -var SELECTED_PROMPT_OR_PLAN_RE = /(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i; -function sha256Text2(text) { - return `sha256:${createHash16("sha256").update(text).digest("hex")}`; -} -function sha256Bytes(bytes) { - return `sha256:${createHash16("sha256").update(bytes).digest("hex")}`; -} -function normalizePath(value) { - return value.split(sep4).join("/"); -} -function relativePath(root, absPath) { - const rel = relative4(root, absPath); - return rel ? normalizePath(rel) : basename5(absPath); -} -function isTextSource(path) { - return TEXT_EXTENSIONS.has(extname2(path).toLowerCase()); -} -function hasSensitivePathPart(path) { - return normalizePath(path).split("/").some((part) => SENSITIVE_PATH_RE.test(part)); -} -function boundedPreview(text, max = 220) { - const normalized = text.normalize("NFKC").trim().replace(/\s+/g, " "); - if (normalized.length <= max) - return normalized; - return `${normalized.slice(0, Math.max(0, max - 1)).trim()}...`; -} -function lineCount(text) { - if (!text) - return 0; - return text.split(/\r\n|\n|\r/).length; -} -function citationFor2(input) { - return { - source_ref: input.sourceRef, - source_path: input.sourcePath, - line_start: input.lineCount > 0 ? 1 : 0, - line_end: input.lineCount, - content_hash: input.contentHash - }; -} -function ruleSpecs() { - return [ - { - base: ".", - maxDepth: 0, - spec: { - family: "rule_doc", - owner: "repository", - scope: "global", - precedence: { rank: 10, label: "root-rule-doc" }, - tags: ["global-rules", "rule-doc"], - include: (path) => ROOT_RULE_DOCS.has(path) - } - }, - { - base: ".codewith", - spec: { - family: "codewith", - owner: "codewith", - scope: "global", - precedence: { rank: 20, label: "codewith" }, - tags: ["global-rules", "codewith", "agent-instructions"], - include: (path) => { - const normalized = normalizePath(path); - const name = basename5(normalized); - if (ROOT_RULE_DOCS.has(name) || normalized === "config.toml") - return true; - if (normalized.endsWith("/SKILL.md")) - return true; - if (/^(rules|instructions|prompts|plans)\//.test(normalized) && isTextSource(normalized)) - return true; - return false; - } - } - }, - { - base: ".claude", - spec: { - family: "claude", - owner: "claude", - scope: "global", - precedence: { rank: 30, label: "claude-rules" }, - tags: ["global-rules", "claude", "agent-instructions"], - include: (path) => { - const normalized = normalizePath(path); - return normalized === "CLAUDE.md" || /^rules\//.test(normalized) && isTextSource(normalized); - } - } - }, - { - base: ".codex", - spec: { - family: "codex", - owner: "codex", - scope: "global", - precedence: { rank: 40, label: "codex" }, - tags: ["global-rules", "codex", "agent-instructions"], - include: (path) => { - const normalized = normalizePath(path); - const name = basename5(normalized); - if (ROOT_RULE_DOCS.has(name) || name === "config.toml") - return true; - return /^(rules|instructions|prompts)\//.test(normalized) && isTextSource(normalized); - } - } - }, - { - base: ".opencode", - spec: { - family: "opencode", - owner: "opencode", - scope: "global", - precedence: { rank: 50, label: "opencode" }, - tags: ["global-rules", "opencode", "agent-instructions"], - include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) - } - }, - { - base: ".", - maxDepth: 0, - spec: { - family: "opencode", - owner: "opencode", - scope: "global", - precedence: { rank: 50, label: "opencode-config" }, - tags: ["global-rules", "opencode", "config"], - include: (path) => ["opencode.json", "opencode.jsonc", "opencode.toml", "opencode.yaml", "opencode.yml"].includes(path) - } - }, - { - base: ".hasna/prompts", - spec: { - family: "prompt", - owner: "hasna", - scope: "global", - precedence: { rank: 60, label: "selected-prompts" }, - tags: ["global-rules", "prompt"], - include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) - } - }, - { - base: ".hasna/plans", - spec: { - family: "plan", - owner: "hasna", - scope: "global", - precedence: { rank: 65, label: "selected-plans" }, - tags: ["global-rules", "plan"], - include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) - } - }, - { - base: "docs", - spec: { - family: "rule_doc", - owner: "repository", - scope: "global", - precedence: { rank: 70, label: "rule-docs" }, - tags: ["global-rules", "rule-doc"], - include: (path) => SELECTED_PROMPT_OR_PLAN_RE.test(path) && isTextSource(path) - } - } - ]; + ok, + dry_run: false, + approval_required: false, + scope: options.scope, + current_home: options.current.home, + legacy_home: options.legacy.home, + backup_home: backupHome, + tombstone_path: tombstonePath, + legacy_before: legacyBeforeOutput, + current_before: currentBefore, + backup_after: backupAfter, + current_after: currentAfter, + checks: checks3, + warnings, + message: ok ? `Migrated legacy knowledge workspace to ${options.current.home}` : `Migrated legacy knowledge workspace, but verification failed for ${options.current.home}` + }; } -function collectFiles(root, skipped) { - const candidates = new Map; - for (const entry of ruleSpecs()) { - const basePath = resolve4(root, entry.base); - if (!existsSync11(basePath)) - continue; - const rootStats = statSync2(basePath); - if (rootStats.isFile()) { - const rel = basename5(basePath); - if (entry.spec.include(rel)) { - candidates.set(basePath, { - ...entry.spec, - absPath: basePath - }); - } - continue; - } - walkRuleDirectory({ - basePath, - depth: 0, - maxDepth: entry.maxDepth ?? WALK_MAX_DEPTH, - spec: entry.spec, - candidates, - skipped - }); + +// src/service.ts +function resolvePeerWorkspace(input) { + const target = resolve5(input); + if (existsSync14(join9(target, "knowledge.db")) || existsSync14(join9(target, "config.json"))) { + return ensureKnowledgeWorkspace(target); } - return [...candidates.values()].sort((a, b) => { - if (a.precedence.rank !== b.precedence.rank) - return a.precedence.rank - b.precedence.rank; - return a.absPath.localeCompare(b.absPath); - }); + return ensureKnowledgeWorkspace(workspaceForHome(projectKnowledgeHome(target)).home); } -function walkRuleDirectory(input) { - const rootBasePath = input.rootBasePath ?? input.basePath; - if (input.depth > input.maxDepth) - return; - for (const dirent of readdirSync2(input.basePath, { withFileTypes: true })) { - const absPath = join6(input.basePath, dirent.name); - const rel = relativePath(rootBasePath, absPath); - if (dirent.isSymbolicLink()) - continue; - if (dirent.isDirectory()) { - if (SKIP_DIRECTORIES.has(dirent.name)) { - continue; - } - if (hasSensitivePathPart(rel)) { - input.skipped.push({ source_family: input.spec.family, source_path: absPath, reason: "sensitive_path" }); - continue; - } - walkRuleDirectory({ - ...input, - rootBasePath, - basePath: absPath, - depth: input.depth + 1 - }); - continue; - } - if (!dirent.isFile()) - continue; - const sourceRelativePath = relativePath(resolve4(rootBasePath), absPath); - if (hasSensitivePathPart(sourceRelativePath)) { - input.skipped.push({ source_family: input.spec.family, source_path: absPath, reason: "sensitive_path" }); - continue; - } - if (!input.spec.include(sourceRelativePath)) - continue; - if (!isTextSource(absPath)) - continue; - input.candidates.set(absPath, { - ...input.spec, - absPath - }); - } +function workspaceMachineId(workspace) { + return `${hostname5()}:${createHash21("sha256").update(workspace.home).digest("hex").slice(0, 12)}`; } -function legacyRuleLike(item) { - const tags = (item.tags ?? []).map((tag) => tag.toLowerCase()); - if (tags.some((tag) => ["rule", "rules", "agent", "instructions", "global-rules", "global-agent-rules"].includes(tag))) { - return true; - } - const haystack = `${item.title} -${item.content.slice(0, 500)}`.toLowerCase(); - return /\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(haystack); +function shellQuote2(value) { + return `'${value.replace(/'/g, "'\\''")}'`; } -function manifestItemForRecord(record2, text) { - const ruleProvenance = { - source_path: record2.source_path, - source_path_ref: record2.source_path_ref, - source_ref: record2.source_ref, - owner: record2.owner, - scope: record2.scope, - precedence: record2.precedence, - source_hash: record2.source_hash, - content_hash: record2.content_hash, - discovered_at: record2.discovered_at, - tags: record2.tags, - redaction_status: record2.redaction_status, - citations: record2.citations +function knowledgeCliCommand(args) { + return ["knowledge", ...args].map(shellQuote2).join(" "); +} +function remoteKnowledgeCommand(peerWorkspace, args) { + return `cd ${shellQuote2(peerWorkspace)} && knowledge ${args.map(shellQuote2).join(" ")}`; +} +function serviceMachineIsLocal(machine) { + return !machine || machine === "local" || machine === "localhost"; +} +function workspaceSummary(resolvedWorkspace, projectRoot) { + return { + source: resolvedWorkspace.source, + adapter: resolvedWorkspace.adapter, + project_root: projectRoot, + project_root_source: resolvedWorkspace.project_root_source, + workspace_root: resolvedWorkspace.workspace_root, + workspace_root_source: resolvedWorkspace.workspace_root_source, + open_files_root: resolvedWorkspace.open_files_root, + open_files_root_source: resolvedWorkspace.open_files_root_source, + trust_status: resolvedWorkspace.trust_status, + auth_status: resolvedWorkspace.auth_status, + current: resolvedWorkspace.current, + primary: resolvedWorkspace.primary, + diagnostics: resolvedWorkspace.diagnostics, + repair_hints: resolvedWorkspace.repair_hints, + evidence: resolvedWorkspace.evidence, + cacheability: resolvedWorkspace.cacheability, + warnings: resolvedWorkspace.warnings }; +} +function routeSummary(resolvedMachine) { return { - source_ref: record2.source_ref, - name: record2.title, - mime: "text/markdown", - size: Buffer.byteLength(text), - hash: record2.content_hash, - revision: record2.content_hash, - status: "active", - updated_at: record2.discovered_at, - permissions: { - mode: "read_only", - allowed_purposes: ["knowledge_index", "knowledge_answer", "agent_context"] - }, - rule_provenance: ruleProvenance, - source_family: record2.source_family, - source_path_ref: record2.source_path_ref, - owner: record2.owner, - scope: record2.scope, - precedence: record2.precedence, - tags: record2.tags, - redaction_status: record2.redaction_status, - legacy_json_id: record2.legacy_json_id ?? null, - extracted_text: text + source: resolvedMachine.source, + adapter: resolvedMachine.adapter, + target: resolvedMachine.target, + route: resolvedMachine.route, + target_kind: resolvedMachine.targetKind, + confidence: resolvedMachine.confidence, + evidence: resolvedMachine.evidence, + cacheability: resolvedMachine.cacheability }; } -function prepareFileRecord(input) { - const stats = lstatSync2(input.candidate.absPath); - const sourcePath = input.candidate.absPath; - const sourcePathRef = relativePath(input.root, sourcePath); - if (stats.size > input.maxBytesPerFile) { - const sourceRef2 = pathToFileURL3(sourcePath).href; - const evidence2 = { - source_family: input.candidate.family, - title: basename5(sourcePath), - source_path: sourcePath, - source_path_ref: sourcePathRef, - source_ref: sourceRef2, - owner: input.candidate.owner, - scope: input.candidate.scope, - precedence: input.candidate.precedence, - source_hash: "sha256:skipped-too-large", - content_hash: "sha256:skipped-too-large", - discovered_at: input.discoveredAt, - tags: [...input.candidate.tags, "skipped"], - redaction_status: "refused", - redactions: [], - citations: [], - bytes: stats.size, - line_count: 0, - importable: false, - skipped_reason: "max_bytes_exceeded", - preview: null - }; - return { evidence: evidence2, text: "", manifest: null }; +function parseJsonStringArray(value) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === "string") : []; + } catch { + return []; } - const bytes = readFileSync12(sourcePath); - const rawText = bytes.toString("utf8"); - const redacted = redactSecrets(rawText, input.safetyPolicy); - const highSeverity = redacted.findings.some((finding) => finding.severity === "high"); - const redactionStatus = highSeverity ? "refused" : redacted.findings.length > 0 ? "redacted" : "clean"; - const contentHash = sha256Text2(redacted.text); - const sourceRef = pathToFileURL3(sourcePath).href; - const lines = lineCount(redacted.text); - const evidence = { - source_family: input.candidate.family, - title: basename5(sourcePath), - source_path: sourcePath, - source_path_ref: sourcePathRef, - source_ref: sourceRef, - owner: input.candidate.owner, - scope: input.candidate.scope, - precedence: input.candidate.precedence, - source_hash: sha256Bytes(bytes), - content_hash: contentHash, - discovered_at: input.discoveredAt, - tags: [...input.candidate.tags], - redaction_status: redactionStatus, - redactions: redacted.findings.map((finding) => ({ type: finding.type, severity: finding.severity })), - citations: [citationFor2({ sourceRef, sourcePath, lineCount: lines, contentHash })], - bytes: bytes.byteLength, - line_count: lines, - importable: redactionStatus !== "refused", - skipped_reason: redactionStatus === "refused" ? "secret_refused" : null, - preview: redactionStatus === "refused" ? null : boundedPreview(redacted.text) +} +function recordValue(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : {}; +} +function stringValue(value) { + return typeof value === "string" && value.length > 0 ? value : null; +} +function numberValue(value) { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} +function booleanValue(value) { + return typeof value === "boolean" ? value : null; +} +function stringArrayValue(value) { + return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : []; +} +function registryCacheability(value, resolver, prefix) { + const raw = recordValue(value); + const observedAt = stringValue(raw.observed_at) ?? stringValue(resolver[`${prefix}_observed_at`]); + const sourceAuthority = stringValue(raw.source_authority) ?? stringValue(resolver[`${prefix}_source_authority`]); + if (!observedAt || !sourceAuthority) + return null; + return { + observed_at: observedAt, + verified_at: stringValue(raw.verified_at), + expires_at: stringValue(raw.expires_at) ?? stringValue(resolver[`${prefix}_expires_at`]), + ttl_ms: numberValue(raw.ttl_ms), + source_authority: sourceAuthority, + confidence: stringValue(raw.confidence) ?? (prefix === "route" ? stringValue(resolver.route_confidence) : null), + cacheable: booleanValue(raw.cacheable) ?? booleanValue(resolver[`${prefix}_cacheable`]) ?? false, + stale: booleanValue(raw.stale) ?? booleanValue(resolver[`${prefix}_stale`]) ?? false, + reasons: stringArrayValue(raw.reasons) }; +} +function registryMachineMatches(row, machine) { + return row.machine_id === machine || row.hostname === machine || row.ssh_target === machine || row.tailscale_dns === machine || parseJsonStringArray(row.tailscale_ips_json).includes(machine); +} +function findRegistryMachine(dbPath, machine) { + return listKnowledgeMachines(dbPath).find((row) => registryMachineMatches(row, machine)) ?? null; +} +function registryResolverEvidence(row) { + return recordValue(parseMetadataJson(row.metadata_json).resolver_evidence); +} +function registryResolverCapabilities(row) { + return recordValue(parseMetadataJson(row.capabilities_json).resolver); +} +function registryRouteKind(row) { + const resolver = registryResolverCapabilities(row); + const kind = stringValue(resolver.route_kind); + if (kind === "local" || kind === "lan" || kind === "tailscale" || kind === "ssh" || kind === "unknown") + return kind; + if (row.tailscale_dns && row.ssh_target === row.tailscale_dns) + return "tailscale"; + return row.ssh_target ? "ssh" : "unknown"; +} +function registryRouteTargetKind(row) { + const resolver = registryResolverCapabilities(row); + const kind = stringValue(resolver.route_target_kind); + if (kind === "local" || kind === "lan" || kind === "tailscale" || kind === "ssh" || kind === "unknown") + return kind; + return registryRouteKind(row); +} +function registryRouteConfidence(row) { + return stringValue(registryResolverCapabilities(row).route_confidence) ?? "medium"; +} +function routeFromRegistry(row, machine, fallback) { + const evidence = registryResolverEvidence(row); + const routeEvidence = recordValue(evidence.route); + const resolver = registryResolverCapabilities(row); return { - evidence, - text: redacted.text, - manifest: evidence.importable ? manifestItemForRecord(evidence, redacted.text) : null + target: row.ssh_target ?? row.tailscale_dns ?? row.hostname ?? row.machine_id, + route: registryRouteKind(row), + targetKind: registryRouteTargetKind(row), + confidence: registryRouteConfidence(row), + source: "registry", + adapter: fallback.adapter, + evidence: { + registry: true, + requested_machine_id: machine, + machine_id: row.machine_id, + recorded_at: row.updated_at, + route: routeEvidence + }, + cacheability: registryCacheability(routeEvidence.cacheability, resolver, "route") ?? fallback.cacheability, + warnings: [...new Set([...fallback.warnings, "registry_route_fallback"])] }; } -function prepareLegacyRecord(input) { - const redacted = redactSecrets(input.item.content, input.safetyPolicy); - const highSeverity = redacted.findings.some((finding) => finding.severity === "high"); - const redactionStatus = highSeverity ? "refused" : redacted.findings.length > 0 ? "redacted" : "clean"; - const sourceRef = `open-files://source/legacy-json/path/${encodeURIComponent(input.item.id)}`; - const contentHash = sha256Text2(redacted.text); - const sourceHash = sha256Text2(input.item.content); - const lines = lineCount(redacted.text); - const evidence = { - source_family: "legacy_json", - title: input.item.title, - source_path: input.legacyStorePath, - source_path_ref: `legacy-json:${input.item.id}`, - source_ref: sourceRef, - owner: "legacy-json", - scope: input.scope, - precedence: { rank: 90, label: "legacy-json-note" }, - source_hash: sourceHash, - content_hash: contentHash, - discovered_at: input.discoveredAt, - tags: [...new Set(["global-rules", "legacy-json", ...input.item.tags ?? []])], - redaction_status: redactionStatus, - redactions: redacted.findings.map((finding) => ({ type: finding.type, severity: finding.severity })), - citations: [citationFor2({ sourceRef, sourcePath: input.legacyStorePath, lineCount: lines, contentHash })], - bytes: Buffer.byteLength(input.item.content), - line_count: lines, - importable: redactionStatus !== "refused", - skipped_reason: redactionStatus === "refused" ? "secret_refused" : null, - preview: redactionStatus === "refused" ? null : boundedPreview(redacted.text), - legacy_json_id: input.item.id +function workspaceFromRegistry(row, machine, fallback) { + if (!row.workspace_home) + return null; + const evidence = registryResolverEvidence(row); + const workspaceEvidence = recordValue(evidence.workspace); + const resolver = registryResolverCapabilities(row); + return { + ok: true, + source: "registry", + adapter: fallback.adapter, + requested_machine_id: machine, + machine_id: row.machine_id, + project_id: stringValue(workspaceEvidence.project_id) ?? fallback.project_id, + repo_name: stringValue(workspaceEvidence.repo_name) ?? fallback.repo_name, + project_root: row.workspace_home, + project_root_source: stringValue(resolver.project_root_source) ?? "registry", + workspace_root: stringValue(workspaceEvidence.workspace_root), + workspace_root_source: stringValue(resolver.workspace_root_source) ?? "registry", + open_files_root: stringValue(workspaceEvidence.open_files_root), + open_files_root_source: stringValue(resolver.open_files_root_source) ?? "registry", + trust_status: stringValue(resolver.trust_status) ?? "unknown", + auth_status: stringValue(resolver.auth_status) ?? "unknown", + current: false, + primary: false, + diagnostics: [], + repair_hints: [], + evidence: { + registry: true, + requested_machine_id: machine, + machine_id: row.machine_id, + recorded_at: row.updated_at, + workspace: workspaceEvidence + }, + cacheability: registryCacheability(workspaceEvidence.cacheability, resolver, "workspace") ?? fallback.cacheability, + warnings: [...new Set([...fallback.warnings, "registry_workspace_fallback"])] + }; +} +function workspaceReadinessMessage(resolvedWorkspace) { + if (!resolvedWorkspace) + return null; + const nonOkDiagnostics = resolvedWorkspace.diagnostics.filter((entry) => entry.severity !== "ok"); + const firstRepair = resolvedWorkspace.repair_hints[0]; + if (!nonOkDiagnostics.length && !resolvedWorkspace.warnings.length && !firstRepair) + return null; + return [ + nonOkDiagnostics.length ? `workspace diagnostics: ${nonOkDiagnostics.map((entry) => `${entry.id}=${entry.status}`).join(", ")}` : null, + resolvedWorkspace.warnings.length ? `warnings: ${resolvedWorkspace.warnings.join(", ")}` : null, + firstRepair ? `repair: ${firstRepair.shell_command}` : null + ].filter(Boolean).join("; "); +} +function syncCommand(input) { + return { + id: input.id, + reason: input.reason, + command: ["knowledge", ...input.args], + shell_command: knowledgeCliCommand(input.args) }; +} +function countQuery(dbPath, sql) { + const db = openKnowledgeDb(dbPath); + try { + return Number(db.query(sql).get()?.count ?? 0); + } finally { + db.close(); + } +} +function openFilesBoundaryStatus(dbPath, resolvedWorkspace) { + const openFilesRefs = countQuery(dbPath, "SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"); + const metadataMentions = countQuery(dbPath, "SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"); + const extractedTextArtifacts = countQuery(dbPath, "SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"); + const rawPayloadSentinelHits = countQuery(dbPath, [ + "SELECT COUNT(*) AS count FROM sources", + "WHERE metadata_json LIKE '%raw_bytes%'", + "OR metadata_json LIKE '%raw_content%'", + "OR metadata_json LIKE '%content_base64%'", + "OR metadata_json LIKE '%source_bytes%'" + ].join(" ")); + const ok = rawPayloadSentinelHits === 0; return { - evidence, - text: redacted.text, - manifest: evidence.importable ? manifestItemForRecord(evidence, redacted.text) : null + ok, + source_of_truth: "open-files", + configured_root: resolvedWorkspace?.open_files_root ?? null, + configured_root_source: resolvedWorkspace?.open_files_root_source ?? null, + source_refs: { + open_files: openFilesRefs, + metadata_mentions: metadataMentions + }, + extracted_text_artifacts: extractedTextArtifacts, + raw_source_bytes_owned_by: "open-files", + raw_payload_sentinel_hits: rawPayloadSentinelHits, + message: ok ? `${openFilesRefs} open-files source ref(s); raw source bytes remain owned by open-files` : `${rawPayloadSentinelHits} raw source payload metadata sentinel(s) found` }; } -function deprecateLegacyNotes(input) { - if (!input.legacyStorePath || !existsSync11(input.legacyStorePath)) - return 0; - const byId = new Map(input.records.filter((record2) => record2.legacy_json_id && record2.importable).map((record2) => [record2.legacy_json_id, record2])); - if (byId.size === 0) - return 0; - return withLock(input.legacyStorePath, () => { - const store = loadStoreIfExists(input.legacyStorePath); - if (!store.exists) - return 0; - let deprecated = 0; - for (const item of store.items) { - const record2 = byId.get(item.id); - if (!record2) - continue; - const metadata = item.metadata ?? {}; - item.archived = true; - item.metadata = { - ...metadata, - knowledge_rules_import: { - status: "deprecated_after_source_backed_promotion", - deprecated_at: input.now, - source_ref: record2.source_ref, - source_hash: record2.source_hash, - content_hash: record2.content_hash, - data_loss: false - } - }; - item.tags = [...new Set([...item.tags ?? [], "deprecated:knowledge-rules-import"])]; - item.updated_at = input.now; - deprecated += 1; +var RAW_ARTIFACT_PAYLOAD_METADATA_KEYS = new Set([ + "raw", + "raw_bytes", + "raw_content", + "content_base64", + "source_bytes", + "source_content", + "body", + "body_bytes" +]); +function metadataHasRawPayloadSentinel(value, depth = 0) { + if (depth > 8) + return false; + if (!value || typeof value !== "object") + return false; + if (Array.isArray(value)) + return value.some((entry) => metadataHasRawPayloadSentinel(entry, depth + 1)); + for (const [key, entry] of Object.entries(value)) { + if (RAW_ARTIFACT_PAYLOAD_METADATA_KEYS.has(key.toLowerCase())) + return true; + if (metadataHasRawPayloadSentinel(entry, depth + 1)) + return true; + } + return false; +} +function parseMetadataJson(value) { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } +} +function inventoryLimit(value, fallback = 20, max = 200) { + if (!Number.isFinite(value) || value <= 0) + return fallback; + return Math.min(Math.floor(value), max); +} +function previewText(value, max = 220) { + const text = value ?? ""; + return text.length > max ? `${text.slice(0, max)}...` : text; +} +function rowsWithJsonFields(rows, fields = ["metadata_json"]) { + return rows.map((row) => { + const next = { ...row }; + for (const field of fields) { + const raw = next[field]; + if (typeof raw === "string") { + const parsedField = field.endsWith("_json") ? field.slice(0, -5) : field; + next[parsedField] = parseMetadataJson(raw); + delete next[field]; + } } - if (deprecated > 0) - saveStore(input.legacyStorePath, { items: store.items }); - return deprecated; + return next; }); } -async function importRulesProvenance(options = {}) { - const root = resolve4(options.root ?? process.cwd()); - const scope = options.scope ?? "global"; - const owner = options.owner ?? "global-agent-rules-standard"; - const dryRun = options.dryRun !== false; - const discoveredAt = (options.now ?? new Date).toISOString(); - const maxItems = Math.max(1, Math.min(options.maxItems ?? DEFAULT_MAX_ITEMS2, 1000)); - const evidenceLimit = Math.max(1, Math.min(options.limit ?? DEFAULT_EVIDENCE_LIMIT, 100)); - const maxBytesPerFile = Math.max(1024, Math.min(options.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE, 2 * 1024 * 1024)); - const skipped = []; - const files = collectFiles(root, skipped).slice(0, maxItems); - const fileRecords = files.map((candidate) => prepareFileRecord({ - root, - candidate: { - ...candidate, - owner: candidate.owner === "repository" ? owner : candidate.owner, - scope - }, - discoveredAt, - maxBytesPerFile, - safetyPolicy: options.safetyPolicy - })); - const legacyStore = options.includeLegacy === false || !options.legacyStorePath ? { exists: false, items: [] } : loadStoreIfExists(options.legacyStorePath); - const legacyItems = legacyStore.items.filter((item) => item.archived !== true && legacyRuleLike(item)).slice(0, maxItems); - const legacyRecords = legacyItems.map((item) => prepareLegacyRecord({ - item, - legacyStorePath: options.legacyStorePath, - discoveredAt, - scope, - safetyPolicy: options.safetyPolicy - })); - const prepared = [...fileRecords, ...legacyRecords].slice(0, maxItems); - const allEvidence = prepared.map((record2) => record2.evidence); - const importableRecords = prepared.filter((record2) => record2.manifest); - const manifests = importableRecords.map((record2) => record2.manifest); - const refused = allEvidence.filter((record2) => record2.redaction_status === "refused").length; - const evidence = allEvidence.slice(0, evidenceLimit); - const boundedSkipped = skipped.slice(0, evidenceLimit); - let importResult = null; - let deprecated = 0; - if (!dryRun) { - if (!options.dbPath) - throw new Error("rules provenance apply mode requires dbPath."); - if (manifests.length > 0) { - importResult = await ingestOpenFilesManifestItems({ - dbPath: options.dbPath, - items: manifests, - sourceLabel: "knowledge://rules-provenance/global-agent-rules", - readAction: "rules_provenance_import", - allowFileSourceRefs: true, - safetyPolicy: options.safetyPolicy, - now: options.now, - maxItems - }); - } - if (options.deprecateLegacy !== false) { - deprecated = deprecateLegacyNotes({ - legacyStorePath: options.legacyStorePath, - records: allEvidence, - now: discoveredAt - }); +function parseInventoryJsonArray(value) { + if (typeof value !== "string") + return []; + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } +} +function parseInventoryJsonObject(value) { + if (typeof value !== "string") + return {}; + return parseMetadataJson(value); +} +function promotionCandidateInventoryRow(row) { + const next = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.requires_approval = next.requires_approval === 1 || next.requires_approval === true; + next.checks = parseInventoryJsonObject(next.checks_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.checks_json; + delete next.metadata_json; + return next; +} +function durableRecordInventoryRow(row) { + const next = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.metadata_json; + return next; +} +function selectInventoryRows(db, sql, params = []) { + return db.query(sql).all(...params); +} +function readLegacyInventoryStore(path) { + if (!existsSync14(path)) + return { exists: false, read_error: null, items: [] }; + try { + const parsed = JSON.parse(readFileSync15(path, "utf8")); + if (!parsed || !Array.isArray(parsed.items)) { + return { exists: true, read_error: "invalid_store_shape", items: [] }; } + return { exists: true, read_error: null, items: parsed.items }; + } catch (error51) { + return { + exists: true, + read_error: error51 instanceof Error ? error51.message : String(error51), + items: [] + }; } +} +function legacyInventoryItem(item) { return { - ok: refused === 0 || manifests.length > 0 || dryRun, - workflow: "global-rules-provenance-import", - dry_run: dryRun, - writes_performed: !dryRun, - root, - scope, - owner, - discovered_at: discoveredAt, - max_items: maxItems, - evidence_limit: evidenceLimit, - records_seen: allEvidence.length, - records_importable: manifests.length, - records_refused: refused, - records_skipped: skipped.length, - evidence_truncated: allEvidence.length > evidence.length, - skipped_truncated: skipped.length > boundedSkipped.length, - evidence, - skipped: boundedSkipped, - import_result: importResult, - legacy: { - store_path: options.legacyStorePath ?? null, - candidates: legacyItems.length, - promoted: legacyRecords.filter((record2) => record2.manifest).length, - deprecated, - data_loss: false - }, - message: dryRun ? `Discovered ${allEvidence.length} rule source(s); ${manifests.length} importable, ${refused} refused` : `Imported ${importResult?.items_seen ?? 0} rule source(s); ${deprecated} legacy note(s) deprecated` + id: item.id, + short_id: item.short_id ?? null, + title: item.title, + content_preview: previewText(item.content), + url: item.url ?? null, + tags: item.tags ?? [], + metadata: item.metadata ?? {}, + archived: item.archived === true, + created_at: item.created_at, + updated_at: item.updated_at }; } - -// src/web-search.ts -import { createHash as createHash17, randomUUID as randomUUID11 } from "crypto"; -function stableHash(value) { - return `sha256:${createHash17("sha256").update(value).digest("hex")}`; -} -function estimateTokens3(text) { - const words = text.trim().split(/\s+/).filter(Boolean).length; - return Math.max(1, Math.ceil(words * 1.25)); +function emptyKnowledgeDbStats() { + return { + schema_version: 0, + sources: 0, + source_revisions: 0, + chunks: 0, + wiki_pages: 0, + citations: 0, + indexes: 0, + runs: 0, + run_events: 0, + redaction_findings: 0, + audit_events: 0, + approval_gates: 0, + storage_objects: 0, + embeddings: 0, + vector_entries: 0, + reindex_queue: 0, + knowledge_machines: 0, + sync_snapshots: 0, + sync_changes: 0, + sync_conflicts: 0, + sync_table_clocks: 0, + sync_imports: 0, + promotion_candidates: 0, + durable_records: 0 + }; } -function asRecord2(value) { - return value && typeof value === "object" && !Array.isArray(value) ? value : {}; +function emptySearchResult(query2, limit, semantic = false) { + return { + query: query2, + limit, + offset: 0, + mode: { + keyword: true, + catalog: true, + semantic + }, + semantic_provider: null, + semantic_model: null, + semantic_dimensions: null, + counts: { + keyword_results: 0, + catalog_results: 0, + semantic_results: 0, + merged_results: 0 + }, + warnings: ["knowledge_db_missing"], + results: [] + }; } -function asString4(value) { - return typeof value === "string" && value.length > 0 ? value : null; +function normalizeContextQuery(query2) { + return query2.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase(); } -function sourceFromRecord(value) { - const record2 = asRecord2(value); - const url2 = asString4(record2.url) ?? asString4(record2.uri) ?? asString4(record2.sourceUrl); - if (!url2) - return null; +function emptyContextPack(query2, limit, semantic = false) { + const search = emptySearchResult(query2, limit, semantic); return { - url: url2, - title: asString4(record2.title) ?? asString4(record2.name), - snippet: asString4(record2.snippet) ?? asString4(record2.text) ?? asString4(record2.description), - provider_metadata: record2 + query: query2, + normalized_query: normalizeContextQuery(query2), + created_at: new Date().toISOString(), + mode: search.mode, + warnings: search.warnings, + search_counts: search.counts, + results: [], + citations: [], + excerpts: [], + graph: { + citations: [], + backlinks: [] + }, + notes: { + permissions: [], + freshness: [] + } }; } -function collectSources(value, output) { - if (Array.isArray(value)) { - for (const entry of value) - collectSources(entry, output); - return; - } - const source = sourceFromRecord(value); - if (source) - output.set(source.url, source); - const record2 = asRecord2(value); - for (const key of ["sources", "results", "citations", "annotations", "output"]) { - if (record2[key]) - collectSources(record2[key], output); +function legacyStorePathForRead(scope, workspace, preferred) { + const current = preferred ?? workspace.jsonStorePath; + if (existsSync14(current)) + return current; + if (scope === "global") { + const legacy = legacyGlobalStorePath(); + if (existsSync14(legacy)) + return legacy; } + return current; } -function fakeSources(query2, limit) { - return Array.from({ length: Math.min(limit, 3) }, (_, index) => ({ - url: `https://example.com/knowledge-web-${index + 1}`, - title: `Fake web source ${index + 1}`, - snippet: `Deterministic web-search fixture for "${query2}"`, - provider_metadata: { fake: true, rank: index + 1 } - })); +function estimateTokensForValue2(value) { + const text = JSON.stringify(value); + return Math.max(1, Math.ceil(text.length / 4)); } -async function openAiWebSearch(input) { - const { generateText } = await import("ai"); - const { createOpenAI } = await import("@ai-sdk/openai"); - const settings = providerSettings(input.config, "openai"); - const openai = createOpenAI({ - apiKey: input.env[settings.api_key_env], - baseURL: settings.base_url - }); - const webSearch = openai.tools?.webSearch; - if (!webSearch) - throw new Error("OpenAI provider does not expose tools.webSearch."); - return generateText({ - model: openai(input.model), - prompt: input.query, - tools: { - web_search: webSearch({ - externalWebAccess: true, - searchContextSize: "medium", - ...input.domains.length > 0 ? { allowedDomains: input.domains } : {} - }) - }, - toolChoice: { type: "tool", toolName: "web_search" } - }); +function compactText(value, maxChars) { + const normalized = (value ?? "").normalize("NFKC").trim().replace(/\s+/g, " "); + if (normalized.length <= maxChars) + return normalized; + return `${normalized.slice(0, Math.max(0, maxChars - 1)).trim()}...`; } -async function anthropicWebSearch(input) { - const { generateText } = await import("ai"); - const { createAnthropic } = await import("@ai-sdk/anthropic"); - const settings = providerSettings(input.config, "anthropic"); - const anthropic = createAnthropic({ - apiKey: input.env[settings.api_key_env], - baseURL: settings.base_url - }); - const factory = anthropic.tools?.webSearch_20250305 ?? anthropic.tools?.webSearch; - if (!factory) - throw new Error("Anthropic provider does not expose a web search tool."); - return generateText({ - model: anthropic(input.model), - prompt: input.query, - tools: { - web_search: factory({ - maxUses: input.maxUses, - ...input.domains.length > 0 ? { allowedDomains: input.domains } : {} - }) - } - }); +function redactPreviewForPack(value, policy, maxChars) { + const redacted = redactSecrets(compactText(value, maxChars), policy); + return { text: redacted.text, redactions: redacted.findings.length }; } -async function fileWebSources(options, sources, now) { - if (!options.fileResults || sources.length === 0) - return 0; - const items = sources.map((source) => { - const text = [source.title, source.snippet, source.url].filter(Boolean).join(` -`); - const hash2 = stableHash(text); +function legacyAgentContextPack(options, context, policy) { + const now = options.now ?? new Date; + const source = options.source ?? "search"; + const purpose = options.purpose ?? (source === "loops" || source === "runs" ? "proposal" : "agent_context"); + const query2 = (options.query ?? options.topic ?? context.query).normalize("NFKC").trim().replace(/\s+/g, " "); + const maxItems = Math.max(1, Math.min(options.maxItems ?? options.limit ?? 8, 50)); + const maxTokens = Math.max(500, Math.min(options.maxTokens ?? 6000, 1e5)); + let redactions = 0; + const citations = context.citations.slice(0, Math.max(maxItems * 2, maxItems)).map((citation, index) => { + const quote = redactPreviewForPack(citation.quote, policy, index < 3 ? 220 : 140); + redactions += quote.redactions; + const ref = citation.source_ref ?? citation.source_uri ?? citation.artifact_path ?? citation.artifact_uri ?? citation.id; return { - source_ref: source.url, - name: source.title ?? source.url, - url: source.url, - mime: "text/plain", - hash: hash2, - revision: hash2, - status: "active", - updated_at: now, - permissions: { mode: "read_only", allowed_purposes: ["knowledge_answer", "knowledge_index"] }, - metadata: { - source_ref: source.url, - content_source: "provider_web_search", - provider_metadata: source.provider_metadata + id: `cite_${createHash21("sha256").update(`${citation.id}\x00${ref}`).digest("hex").slice(0, 12)}`, + kind: citation.artifact_uri || citation.artifact_path ? "artifact" : "source", + ref, + source_ref: citation.source_ref, + source_uri: citation.source_uri, + artifact_uri: citation.artifact_uri, + artifact_path: citation.artifact_path, + run_id: null, + run_event_id: null, + revision: citation.revision, + hash: citation.hash, + chunk_id: citation.chunk_id, + offsets: { + start: citation.start_offset, + end: citation.end_offset }, - extracted_text: text - }; - }); - const result = await ingestOpenFilesManifestItems({ - dbPath: options.dbPath, - items, - sourceLabel: `web-search:${options.query}`, - readAction: "provider_web_search_file_results", - safetyPolicy: options.safetyPolicy, - now: new Date(now) - }); - return result.sources_upserted; -} -async function runProviderWebSearch(options) { - const query2 = options.query.trim(); - if (!query2) - throw new Error("Web search query is required."); - const env = options.env ?? process.env; - const now = (options.now ?? new Date).toISOString(); - const limit = Math.max(1, Math.min(options.limit ?? 5, 20)); - const maxUses = Math.max(1, Math.min(options.maxUses ?? 3, 10)); - const domains = options.domains ?? []; - const modelRef = resolveModelRef(options.modelRef ?? (options.provider ? `${options.provider}:${providerSettings(options.config, options.provider).default_model}` : "default"), options.config); - const parsed = parseModelRef(modelRef); - const provider = options.provider ?? parsed.provider; - const model = parsed.provider === provider ? parsed.model : providerSettings(options.config, provider).default_model; - const runId = `run_${randomUUID11()}`; - if (!options.fake && options.safetyPolicy) - assertWebSearchAllowed(options.safetyPolicy); - if (!options.fake && provider !== "openai" && provider !== "anthropic") { - throw new Error(`Provider ${provider} does not expose native web search yet.`); - } - if (!options.fake) - assertProviderCredentials(provider, options.config, env); - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - try { - db.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - runId, - "provider-web-search", - query2, - "running", - provider, - model, - JSON.stringify({ domains, max_uses: maxUses, fake: options.fake === true }), - now, - now - ]); - recordAuditEvent(db, { - event_type: "source_read", - action: options.fake ? "fake_provider_web_search" : "provider_web_search", - target_uri: query2, - decision: "allow", - metadata: { provider, model, domains, max_uses: maxUses }, - created_at: now - }); - } finally { - db.close(); - } - let answer = ""; - let sources = []; - let usage = { input_tokens: estimateTokens3(query2), output_tokens: 0, cost_usd: 0 }; - const warnings = []; - if (options.fake) { - sources = fakeSources(query2, limit); - answer = `Fake web search answer for: ${query2}`; - usage.output_tokens = estimateTokens3(answer); - } else { - const result = provider === "openai" ? await openAiWebSearch({ query: query2, model, config: options.config, env, maxUses, domains }) : await anthropicWebSearch({ query: query2, model, config: options.config, env, maxUses, domains }); - answer = result.text; - const collected = new Map; - collectSources(result.sources, collected); - collectSources(result.toolResults, collected); - sources = Array.from(collected.values()).slice(0, limit); - const normalized = normalizeAiSdkUsage({ - provider, - model, - usage: result.usage, - providerMetadata: result.providerMetadata - }); - usage = { - input_tokens: normalized.input_tokens, - output_tokens: normalized.output_tokens, - cost_usd: normalized.cost_usd + quote_preview: quote.text }; - } - const filedSources = await fileWebSources(options, sources, now); - const writeDb = openKnowledgeDb(options.dbPath); - try { - writeDb.run(`UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?`, [ - "completed", - JSON.stringify({ domains, max_uses: maxUses, sources: sources.length, filed_sources: filedSources, fake: options.fake === true }), - now, - runId - ]); - writeDb.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, [ - `evt_${randomUUID11()}`, - runId, - "info", - "provider_web_search_completed", - JSON.stringify({ sources: sources.length, filed_sources: filedSources }), - now - ]); - recordProviderUsage(writeDb, { - run_id: runId, - provider, - model, - input_tokens: usage.input_tokens, - output_tokens: usage.output_tokens, - cost_usd: usage.cost_usd, - metadata: { web_search: true, sources: sources.length, filed_sources: filedSources }, - created_at: now - }); - } finally { - writeDb.close(); - } - if (sources.length === 0) - warnings.push("no_web_sources_returned"); - return { - run_id: runId, + }); + const citationByRetrievalId = new Map(context.citations.map((citation, index) => [citation.id, citations[index]])); + const evidence = context.excerpts.slice(0, Math.max(maxItems * 2, maxItems)).map((excerpt2) => { + const result = context.results.find((entry) => entry.id === excerpt2.result_id); + const citation = excerpt2.citation_id ? citationByRetrievalId.get(excerpt2.citation_id) : undefined; + const preview2 = redactPreviewForPack(excerpt2.text, policy, 520); + redactions += preview2.redactions; + return { + id: `ev_${createHash21("sha256").update(`${excerpt2.kind}\x00${excerpt2.result_id}\x00${excerpt2.citation_id ?? ""}`).digest("hex").slice(0, 14)}`, + kind: excerpt2.kind, + title: compactText(result?.title ?? citation?.ref ?? excerpt2.kind, 100), + text_preview: preview2.text, + score: Number(excerpt2.score.toFixed(6)), + citation_ids: citation ? [citation.id] : [], + provenance: { + source, + record_ref: `${excerpt2.kind}:${excerpt2.result_id}`, + created_at: context.created_at, + updated_at: null, + metadata_keys: [] + } + }; + }).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, maxItems); + const usedCitationIds = new Set(evidence.flatMap((entry) => entry.citation_ids)); + const usedCitations = citations.filter((citation) => usedCitationIds.has(citation.id)); + const warnings = Array.from(new Set(context.warnings)); + const idempotencyKey = `ctx_${createHash21("sha256").update([source, purpose, query2, warnings.join(","), evidence.map((entry) => entry.id).join(",")].join("\x00")).digest("hex").slice(0, 20)}`; + const pack = { + ok: true, + format: "knowledge-agent-context-pack", + version: 1, + created_at: now.toISOString(), + source, + purpose, query: query2, - provider, - model, - answer, - sources, - filed_sources: filedSources, - usage, - warnings + topic: options.topic ?? null, + since: options.since ?? null, + dry_run: true, + idempotency_key: idempotencyKey, + budgets: { + max_tokens: maxTokens, + estimated_tokens: 0, + max_items: maxItems, + items_included: evidence.length, + items_available: context.excerpts.length, + items_truncated: Math.max(0, context.excerpts.length - evidence.length), + token_budget_exceeded: false + }, + safety: { + raw_artifact_content_included: false, + durable_writes_performed: false, + redactions, + reminders: [ + "This pack is read-only and performs no durable writes.", + "Legacy JSON note evidence is bounded and redacted before inclusion." + ] + }, + citations: usedCitations, + evidence, + duplicate_candidates: [], + outline: { + title: query2 ? `Knowledge context: ${compactText(query2, 80)}` : "Knowledge context", + bullets: evidence.length > 0 ? evidence.slice(0, 5).map((entry) => `${entry.id}: ${entry.title}`) : ["No matching bounded evidence was found."], + evidence_ids: evidence.slice(0, 8).map((entry) => entry.id), + duplicate_candidate_ids: [], + next_actions: [ + "Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.", + "Inspect cited refs only if the bounded preview is insufficient.", + "Use knowledge build/file-answer only with explicit approval for durable writes." + ] + }, + warnings, + message: `${evidence.length} bounded evidence item(s), estimated under ${maxTokens} token(s)` }; + pack.budgets.estimated_tokens = estimateTokensForValue2(pack); + pack.budgets.token_budget_exceeded = pack.budgets.estimated_tokens > maxTokens; + pack.message = `${pack.evidence.length} bounded evidence item(s), estimated ${pack.budgets.estimated_tokens}/${maxTokens} token(s)`; + return pack; } - -// src/wiki-compiler.ts -import { createHash as createHash18, randomUUID as randomUUID12 } from "crypto"; -function stableId9(prefix, value) { - return `${prefix}_${createHash18("sha256").update(value).digest("hex").slice(0, 20)}`; +function emptyReindexHealth() { + return { + schema_version: 0, + chunks: 0, + vector_entries: 0, + missing_embeddings: 0, + queued: {}, + stale_revisions: 0 + }; } -function slugify3(value) { - const slug = value.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80); - return slug || "knowledge-page"; +function emptyEmbeddingStatus() { + return { + total_embeddings: 0, + total_vector_entries: 0, + indexes: [] + }; } -function todayParts(now) { +function emptySyncStatus(input) { return { - year: String(now.getUTCFullYear()), - month: String(now.getUTCMonth() + 1).padStart(2, "0"), - day: String(now.getUTCDate()).padStart(2, "0") + ok: true, + scope: input.scope, + workspace_home: input.workspaceHome, + sqlite_schema_version: 0, + local_machine_id: input.localMachineId ?? null, + machines: { + total: 0, + rows: [] + }, + snapshots: { + total: 0, + latest: null + }, + changes: { + total: 0, + by_operation: [] + }, + clocks: { + total: 0, + rows: [] + }, + imports: { + total: 0, + latest: null + }, + conflicts: { + total: 0, + by_status: [], + open: 0 + }, + table_counts: {}, + message: "0 machine(s), 0 open sync conflict(s)" }; } -function estimateTokenCount3(text) { - const words = text.trim().split(/\s+/).filter(Boolean).length; - return Math.max(1, Math.ceil(words * 1.25)); +function emptyAgentContextPack(options) { + const now = options.now ?? new Date; + const source = options.source ?? "search"; + const purpose = options.purpose ?? (source === "loops" || source === "runs" ? "proposal" : "agent_context"); + const query2 = (options.query ?? options.topic ?? "").normalize("NFKC").trim().replace(/\s+/g, " "); + const maxItems = Math.max(1, Math.min(options.maxItems ?? options.limit ?? 8, 50)); + const maxTokens = Math.max(500, Math.min(options.maxTokens ?? 6000, 1e5)); + const idempotencyKey = `ctx_${createHash21("sha256").update(["empty", source, purpose, query2, options.topic ?? "", options.since ?? ""].join("\x00")).digest("hex").slice(0, 20)}`; + return { + ok: true, + format: "knowledge-agent-context-pack", + version: 1, + created_at: now.toISOString(), + source, + purpose, + query: query2, + topic: options.topic ?? null, + since: options.since ?? null, + dry_run: true, + idempotency_key: idempotencyKey, + budgets: { + max_tokens: maxTokens, + estimated_tokens: 0, + max_items: maxItems, + items_included: 0, + items_available: 0, + items_truncated: 0, + token_budget_exceeded: false + }, + safety: { + raw_artifact_content_included: false, + durable_writes_performed: false, + redactions: 0, + reminders: [ + "This pack is read-only and performs no durable writes.", + "No knowledge.db exists for this scope yet." + ] + }, + citations: [], + evidence: [], + duplicate_candidates: [], + outline: { + title: query2 ? `Context for ${query2}` : "Knowledge context", + bullets: [], + evidence_ids: [], + duplicate_candidate_ids: [], + next_actions: [] + }, + warnings: ["knowledge_db_missing"], + message: `0 bounded evidence item(s), estimated 0/${maxTokens} token(s)` + }; } -function parseJsonObject6(value) { - if (!value) - return {}; +function storagePrefixKey(storage) { + const prefix = storage.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g, ""); + return prefix ? `${prefix}/` : null; +} +function artifactManifestStatus(dbPath, storage) { + const db = openKnowledgeDb(dbPath); try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; + const rows = db.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json + FROM storage_objects + ORDER BY artifact_uri ASC`).all(); + const byKind = new Map; + let withHash = 0; + let withSize = 0; + let totalSizeBytes = 0; + let matchingPrefix = 0; + let missingKey = 0; + let prefixedKey = 0; + let rawPayloadSentinelHits = 0; + let withModifiedAt = 0; + let invalidModifiedAt = 0; + let withProvenance2 = 0; + let withProvenanceArtifactKey = 0; + let provenanceArtifactKeyMismatches = 0; + const generatedFrom = new Map; + const mismatchedExamples = []; + const prefixedExamples = []; + const invalidModifiedExamples = []; + const provenanceExamples = []; + const expectedPrefix = storage.artifact_store.uri_prefix; + const s3StoragePrefix = storagePrefixKey(storage); + for (const row of rows) { + byKind.set(row.kind, (byKind.get(row.kind) ?? 0) + 1); + if (row.hash?.startsWith("sha256:")) + withHash += 1; + if (typeof row.size_bytes === "number" && row.size_bytes >= 0) { + withSize += 1; + totalSizeBytes += row.size_bytes; + } + if (row.artifact_uri.startsWith(expectedPrefix)) { + matchingPrefix += 1; + } else if (mismatchedExamples.length < 5) { + mismatchedExamples.push(row.artifact_uri); + } + const metadata = parseMetadataJson(row.metadata_json); + if (metadataHasRawPayloadSentinel(metadata)) + rawPayloadSentinelHits += 1; + const key = typeof metadata.key === "string" ? metadata.key : null; + if (!key) { + missingKey += 1; + } else if (s3StoragePrefix && key.startsWith(s3StoragePrefix)) { + prefixedKey += 1; + if (prefixedExamples.length < 5) + prefixedExamples.push(key); + } + const modifiedAt = typeof metadata.artifact_modified_at === "string" ? metadata.artifact_modified_at : null; + if (modifiedAt) { + if (Number.isNaN(Date.parse(modifiedAt))) { + invalidModifiedAt += 1; + if (invalidModifiedExamples.length < 5) + invalidModifiedExamples.push(row.artifact_uri); + } else { + withModifiedAt += 1; + } + } + const provenance = metadata.provenance && typeof metadata.provenance === "object" && !Array.isArray(metadata.provenance) ? metadata.provenance : null; + if (provenance) { + withProvenance2 += 1; + const artifactKey = typeof provenance.artifact_key === "string" ? provenance.artifact_key : null; + const generated = typeof provenance.generated_from === "string" ? provenance.generated_from : "unknown"; + generatedFrom.set(generated, (generatedFrom.get(generated) ?? 0) + 1); + if (artifactKey) { + withProvenanceArtifactKey += 1; + if (key && artifactKey !== key) { + provenanceArtifactKeyMismatches += 1; + if (provenanceExamples.length < 5) + provenanceExamples.push(`${row.artifact_uri}:provenance.artifact_key=${artifactKey}:key=${key}`); + } + } else if (provenanceExamples.length < 5) { + provenanceExamples.push(`${row.artifact_uri}:missing_provenance_artifact_key`); + } + } else if (provenanceExamples.length < 5) { + provenanceExamples.push(`${row.artifact_uri}:missing_provenance`); + } + } + const missingHash = rows.length - withHash; + const missingSize = rows.length - withSize; + const missingModifiedAt = rows.length - withModifiedAt - invalidModifiedAt; + const missingProvenance = rows.length - withProvenance2; + const missingProvenanceArtifactKey = withProvenance2 - withProvenanceArtifactKey; + const mismatchedPrefix = rows.length - matchingPrefix; + const warnings = [ + missingHash > 0 ? `artifact_manifest_missing_hash:${missingHash}` : null, + missingSize > 0 ? `artifact_manifest_missing_size:${missingSize}` : null, + missingKey > 0 ? `artifact_manifest_missing_key:${missingKey}` : null, + mismatchedPrefix > 0 ? `artifact_manifest_uri_prefix_mismatch:${mismatchedPrefix}` : null, + prefixedKey > 0 ? `artifact_manifest_s3_key_contains_storage_prefix:${prefixedKey}` : null, + invalidModifiedAt > 0 ? `artifact_manifest_invalid_modified_at:${invalidModifiedAt}` : null, + missingProvenance > 0 ? `artifact_manifest_missing_provenance:${missingProvenance}` : null, + missingProvenanceArtifactKey > 0 ? `artifact_manifest_missing_provenance_artifact_key:${missingProvenanceArtifactKey}` : null, + provenanceArtifactKeyMismatches > 0 ? `artifact_manifest_provenance_key_mismatch:${provenanceArtifactKeyMismatches}` : null, + rawPayloadSentinelHits > 0 ? `artifact_manifest_raw_payload_sentinels:${rawPayloadSentinelHits}` : null + ].filter((entry) => Boolean(entry)); + const ok = warnings.length === 0; + return { + ok, + read_only: true, + storage_type: storage.storage_type, + artifact_uri_prefix: expectedPrefix, + s3: storage.artifact_store.s3, + artifacts: { + total: rows.length, + by_kind: [...byKind.entries()].map(([kind, count3]) => ({ kind, count: count3 })).sort((a, b) => a.kind.localeCompare(b.kind)), + with_hash: withHash, + missing_hash: missingHash, + with_size: withSize, + missing_size: missingSize, + total_size_bytes: totalSizeBytes + }, + modified_time: { + with_modified_at: withModifiedAt, + missing_modified_at: missingModifiedAt, + invalid_modified_at: invalidModifiedAt, + examples: invalidModifiedExamples + }, + provenance: { + with_provenance: withProvenance2, + missing_provenance: missingProvenance, + with_artifact_key: withProvenanceArtifactKey, + missing_artifact_key: missingProvenanceArtifactKey, + artifact_key_mismatches: provenanceArtifactKeyMismatches, + generated_from: [...generatedFrom.entries()].map(([value, count3]) => ({ value, count: count3 })).sort((a, b) => a.value.localeCompare(b.value)), + examples: provenanceExamples + }, + uri_prefix: { + matching: matchingPrefix, + mismatched: mismatchedPrefix, + examples: mismatchedExamples + }, + keys: { + with_key: rows.length - missingKey, + missing_key: missingKey, + prefixed_with_storage_prefix: prefixedKey, + prefixed_examples: prefixedExamples + }, + sync_manifest: { + copied_by_sync: true, + generated_artifacts_only: true, + includes_raw_source_bytes: false, + hash_algorithm: "sha256", + portable_keys: prefixedKey === 0 && missingKey === 0, + tracks_modified_time: withModifiedAt > 0 && invalidModifiedAt === 0, + preserves_provenance: missingProvenance === 0 && missingProvenanceArtifactKey === 0 && provenanceArtifactKeyMismatches === 0 + }, + raw_payload_sentinel_hits: rawPayloadSentinelHits, + warnings, + message: ok ? `${rows.length} generated artifact manifest row(s) ready for ${storage.storage_type} sync` : `Generated artifact manifest needs attention: ${warnings.join(", ")}` + }; + } finally { + db.close(); } } -function queryTerms3(query2) { - return Array.from(new Set((query2 ?? "").toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [])).slice(0, 12); -} -function escapeLike(value) { - return value.replace(/[\\%_]/g, (char) => `\\${char}`); -} -function selectSourceChunks(db, options) { - const limit = Math.max(1, Math.min(options.limit ?? 10, 50)); - const sourceRefs = options.sourceRefs ?? []; - const terms = queryTerms3(options.query); - const where = ["c.kind = 'source'"]; - const params = []; - if (sourceRefs.length > 0) { - where.push(`(${sourceRefs.map(() => "(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`); - for (const ref of sourceRefs) { - params.push(ref, `%${escapeLike(ref)}%`); +function artifactManifestKeyRepairCandidates(dbPath, storage) { + const prefix = storagePrefixKey(storage); + if (!prefix) + return []; + const db = openKnowledgeDb(dbPath); + try { + const rows = db.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json + FROM storage_objects + ORDER BY artifact_uri ASC`).all(); + const candidates = []; + for (const row of rows) { + const metadata = parseMetadataJson(row.metadata_json); + const currentKey = typeof metadata.key === "string" ? metadata.key : null; + if (!currentKey?.startsWith(prefix)) + continue; + const repaired = currentKey.slice(prefix.length); + if (!repaired) + continue; + candidates.push({ + id: row.id, + artifact_uri: row.artifact_uri, + kind: row.kind, + current_key: currentKey, + repaired_key: normalizeArtifactKey(repaired), + hash: row.hash, + size_bytes: row.size_bytes + }); } + return candidates; + } finally { + db.close(); } - if (terms.length > 0) { - where.push(`(${terms.map(() => "lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`); - for (const term of terms) - params.push(`%${escapeLike(term)}%`); - } - params.push(limit); - return db.query(`SELECT - c.id AS chunk_id, - c.text, - c.start_offset, - c.end_offset, - c.metadata_json, - c.source_revision_id, - sr.revision, - sr.hash, - s.uri AS source_uri, - s.title AS source_title - FROM chunks c - JOIN source_revisions sr ON sr.id = c.source_revision_id - JOIN sources s ON s.id = sr.source_id - WHERE ${where.join(" AND ")} - ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`).all(...params); -} -function excerpt(text, max = 420) { - const normalized = text.replace(/\s+/g, " ").trim(); - return normalized.length <= max ? normalized : `${normalized.slice(0, max - 1).trim()}...`; -} -function titleFor(options, rows) { - if (options.title?.trim()) - return options.title.trim(); - if (options.query?.trim()) - return options.query.trim(); - return rows[0]?.source_title ?? "Compiled Knowledge"; -} -function compileBody(title, rows, now) { - const sourceLines = rows.map((row, index) => { - const label = `S${index + 1}`; - return `- [${label}] ${row.source_title ?? row.source_uri ?? "Source"} (${row.source_uri ?? "unknown"}, revision ${row.revision ?? "unknown"}, hash ${row.hash ?? "unknown"})`; - }); - const noteLines = rows.map((row, index) => { - const label = `S${index + 1}`; - return [ - `## ${row.source_title ?? `Source ${index + 1}`}`, - "", - excerpt(row.text), - "", - `Citation: [${label}]` - ].join(` -`); - }); - return [ - `# ${title}`, - "", - `Generated at: ${now}`, - "", - "## Sources", - "", - ...sourceLines, - "", - ...noteLines, - "" - ].join(` -`); } -async function writeArtifact2(store, entry) { - const written = await store.put(entry); - return { - key: written.key, - uri: written.uri, - kind: entry.key.startsWith("logs/") ? "log" : "wiki_page", - content_type: entry.content_type, - modified_at: written.modified_at, - ...hashArtifactBody(entry.body), - metadata: { - ...entry.metadata ?? {} - } - }; +function doctorRecommendations(input) { + const scopeArgs = ["--scope", input.scope, "--json"]; + const tableArgs = input.tables?.length ? ["--tables", input.tables.join(",")] : []; + const commands = [ + syncCommand({ + id: "sync_status", + reason: "Inspect local sync registry, clocks, snapshots, and conflicts.", + args: ["sync", "status", ...scopeArgs] + }) + ]; + if (input.machine && !serviceMachineIsLocal(input.machine)) { + commands.push(syncCommand({ + id: "sync_dry_run_remote", + reason: "Preview remote machine sync before changing either workspace.", + args: [ + "sync", + "dry-run", + "--machine", + input.machine, + ...input.peerWorkspace ? ["--peer-workspace", input.peerWorkspace] : [], + ...tableArgs, + ...scopeArgs + ] + })); + } else if (input.peerWorkspace) { + commands.push(syncCommand({ + id: "sync_dry_run_peer", + reason: "Preview local peer sync before changing either workspace.", + args: ["sync", "dry-run", "--peer-workspace", input.peerWorkspace, ...tableArgs, ...scopeArgs] + })); + } + for (const hint of input.resolvedWorkspace?.repair_hints ?? []) { + commands.push({ + id: hint.id, + reason: hint.reason, + command: hint.command, + shell_command: hint.shell_command + }); + } + if (input.openConflicts > 0) { + commands.push(syncCommand({ + id: "sync_conflicts", + reason: "Review open conflicts before relying on bidirectional sync.", + args: ["sync", "conflicts", ...scopeArgs] + })); + } + return commands; } -async function appendLog2(store, event, now) { - const { year, month, day } = todayParts(now); - const key = `logs/${year}/${month}/${day}.jsonl`; - let existing = ""; +function resolveSshSpawnSpec() { + const command = process.env.KNOWLEDGE_SSH_COMMAND?.trim() || "ssh"; + const rawArgs = process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON; + if (!rawArgs) + return { command, argsPrefix: [] }; + let parsed; try { - existing = await store.getText(key); - } catch { - existing = ""; + parsed = JSON.parse(rawArgs); + } catch (error51) { + throw new Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${error51 instanceof Error ? error51.message : String(error51)}`); } - return writeArtifact2(store, { - key, - body: `${existing}${JSON.stringify(event)} -`, - content_type: "application/x-ndjson", - metadata: { - provenance: generatedArtifactProvenance({ - generated_from: String(event.event ?? "wiki_log"), - artifact_key: key - }) - } + if (!Array.isArray(parsed) || !parsed.every((arg) => typeof arg === "string")) { + throw new Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array."); + } + return { command, argsPrefix: parsed }; +} +function runSshCommand(machine, command, input, resolved) { + const ssh = resolveSshSpawnSpec(); + const result = spawnSync2(ssh.command, [...ssh.argsPrefix, resolved.target, command], { + encoding: "utf8", + env: process.env, + input, + maxBuffer: 64 * 1024 * 1024 }); + if ((result.status ?? 1) !== 0) { + const route = resolved.source === "open-machines" ? ` via ${resolved.route ?? "resolved"}:${resolved.target}` : ""; + throw new Error(`ssh ${machine}${route} failed: ${(result.stderr || result.stdout || String(result.status)).trim()}`); + } + return result.stdout || ""; } -function upsertWikiPage(db, input) { - db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(path) DO UPDATE SET - title = excluded.title, - artifact_uri = excluded.artifact_uri, - content_hash = excluded.content_hash, - status = excluded.status, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`, [ - input.pageId, - input.path, - input.title, - input.artifactUri, - input.contentHash, - "active", - JSON.stringify({ - artifact_key: input.path, - provenance: input.provenance - }), - input.now, - input.now - ]); - const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(input.pageId); - for (const row of existing) - db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); - db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [input.pageId]); - const chunkId = stableId9("chk", `${input.pageId}\x00${input.contentHash}`); - db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - chunkId, - input.pageId, - "wiki", - 0, - input.body, - estimateTokenCount3(input.body), - 0, - input.body.length, - JSON.stringify({ - artifact_key: input.path, - artifact_uri: input.artifactUri, - content_hash: input.contentHash, - provenance: input.provenance - }), - input.now - ]); - db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [ - chunkId, - input.body, - input.title, - input.artifactUri - ]); +function parseRemoteJson(machine, action, raw) { + try { + return JSON.parse(raw); + } catch (error51) { + const preview2 = raw.trim().slice(0, 240); + throw new Error(`Remote knowledge ${action} on ${machine} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${preview2 || String(error51)}`); + } } -function replacePageCitations(db, pageId, citations, now) { - db.run("DELETE FROM citations WHERE wiki_page_id = ?", [pageId]); - for (const citation of citations) { - db.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - stableId9("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID12()}`), - pageId, - citation.chunk_id, - citation.source_uri, - citation.quote, - citation.start_offset, - citation.end_offset, - JSON.stringify(citation.metadata), - now - ]); +function assertRemoteSyncBundle(machine, value) { + if (typeof value !== "object" || value === null || !("format" in value) || value.format !== "knowledge-sync-bundle") { + throw new Error(`Remote knowledge sync export on ${machine} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`); + } + const protocolVersion = value.protocol_version; + const minProtocolVersion = value.min_protocol_version; + if (typeof protocolVersion !== "number" || typeof minProtocolVersion !== "number" || protocolVersion < KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION || minProtocolVersion > KNOWLEDGE_SYNC_PROTOCOL_VERSION) { + throw new Error(`Remote knowledge sync export on ${machine} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`); } - return citations.length; } -function upsertIndex(db, input) { - db.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(kind, name, shard_key) DO UPDATE SET - artifact_uri = excluded.artifact_uri, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`, [ - stableId9("idx", `wiki-topic\x00${input.path}`), - "wiki_topic", - input.title, - input.artifactUri, - input.path, - JSON.stringify({ - artifact_key: input.path, - content_hash: input.contentHash - }), - input.now, - input.now - ]); - return 1; +function assertRemoteSyncApplyResult(machine, value) { + if (typeof value !== "object" || value === null || !("ok" in value) || !("target" in value) || !("tables" in value) || !("artifacts" in value) || !("conflicts_created" in value)) { + throw new Error(`Remote knowledge sync import on ${machine} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`); + } + const protocolVersion = value.protocol_version; + const minProtocolVersion = value.min_protocol_version; + if (typeof protocolVersion !== "number" || typeof minProtocolVersion !== "number" || protocolVersion < KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION || minProtocolVersion > KNOWLEDGE_SYNC_PROTOCOL_VERSION) { + throw new Error(`Remote knowledge sync import on ${machine} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`); + } } -function firstConcept(title) { - return title.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0] ?? "knowledge"; +function normalizeMode(value) { + if (!value) + return; + const normalized = value.trim().toLowerCase(); + if (normalized === "local" || normalized === "offline") + return "local"; + if (normalized === "hosted" || normalized === "remote" || normalized === "knowledge.md") + return "hosted"; + throw new Error("Invalid setup mode. Use hosted or local."); } -async function compileWikiPage(options) { - const nowDate = options.now ?? new Date; - const now = nowDate.toISOString(); - migrateKnowledgeDb(options.dbPath); - const readDb = openKnowledgeDb(options.dbPath); - let rows; - try { - rows = selectSourceChunks(readDb, options); - } finally { - readDb.close(); + +class KnowledgeService { + options; + ensuredWorkspace; + cachedConfig; + constructor(options = {}) { + this.options = options; } - if (rows.length === 0) - throw new Error("No source chunks matched wiki compile input."); - const title = titleFor(options, rows); - const slug = slugify3(title); - const path = `wiki/generated/${slug}.md`; - const body = compileBody(title, rows, now); - const sourceRefs = rows.map((row) => { - const metadata = parseJsonObject6(row.metadata_json); - return typeof metadata.source_ref === "string" ? metadata.source_ref : row.source_uri; - }).filter((ref) => Boolean(ref)); - const provenance = generatedArtifactProvenance({ - generated_from: "wiki_compile", - artifact_key: path, - source_refs: sourceRefs - }); - const pageArtifact = await writeArtifact2(options.store, { - key: path, - body, - content_type: "text/markdown", - metadata: { generated_from: "wiki_compile" } - }); - const pageId = stableId9("wiki", path); - const citations = rows.map((row) => ({ - chunk_id: row.chunk_id, - source_uri: row.source_uri ?? "unknown", - quote: excerpt(row.text, 240), - start_offset: row.start_offset, - end_offset: row.end_offset, - metadata: { - source_revision_id: row.source_revision_id, - revision: row.revision, - hash: row.hash, - source_ref: parseJsonObject6(row.metadata_json).source_ref ?? row.source_uri - } - })); - const concept = firstConcept(title); - const conceptPath = `wiki/concepts/${slugify3(concept)}.md`; - const conceptBody = [`# ${concept}`, "", `Related page: [[${path}]]`, ""].join(` -`); - const conceptProvenance = generatedArtifactProvenance({ - generated_from: "wiki_compile_concept", - artifact_key: conceptPath, - source_refs: sourceRefs - }); - const conceptArtifact = await writeArtifact2(options.store, { - key: conceptPath, - body: conceptBody, - content_type: "text/markdown", - metadata: { generated_from: "wiki_compile_concept" } - }); - const conceptPageId = stableId9("wiki", conceptPath); - const log = await appendLog2(options.store, { - ts: now, - event: "wiki_compile_completed", - page_key: path, - source_refs: sourceRefs, - chunks_seen: rows.length - }, nowDate); - const db = openKnowledgeDb(options.dbPath); - try { - recordStorageObjects(db, [pageArtifact, conceptArtifact, log], nowDate); - upsertWikiPage(db, { - pageId, - path, - title, - artifactUri: pageArtifact.uri, - contentHash: pageArtifact.hash ?? "", - body, - provenance, - now + get scope() { + return this.options.scope ?? "global"; + } + get workspace() { + return this.ensuredWorkspace ?? resolveScopedWorkspace(this.options.scope, this.options.cwd); + } + ensureWorkspace() { + if (!this.ensuredWorkspace) + this.ensuredWorkspace = ensureKnowledgeWorkspace(this.workspace.home); + return this.ensuredWorkspace; + } + jsonStorePath() { + return this.ensureWorkspace().jsonStorePath; + } + itemStore() { + const workspace = this.ensureWorkspace(); + return resolveItemStore({ + storePath: workspace.jsonStorePath, + storePathOverridden: false }); - upsertWikiPage(db, { - pageId: conceptPageId, - path: conceptPath, - title: concept, - artifactUri: conceptArtifact.uri, - contentHash: conceptArtifact.hash ?? "", - body: conceptBody, - provenance: conceptProvenance, - now + } + async listItems() { + return this.itemStore().listAll(); + } + async getItem(idOrShort) { + return this.itemStore().get(idOrShort); + } + async createItem(input) { + return this.itemStore().create(input); + } + async updateItem(idOrShort, patch) { + return this.itemStore().update(idOrShort, patch); + } + async deleteItem(idOrShort) { + return this.itemStore().delete(idOrShort); + } + async deleteItems(idsOrShorts) { + return this.itemStore().deleteMany(idsOrShorts); + } + async resolveInventory(options = {}) { + if (this.isApiMode()) + return this.cloudInventory(options); + return this.inventory(options); + } + config(options = {}) { + const workspace = options.ensure ? this.ensureWorkspace() : this.workspace; + if (!this.cachedConfig || options.ensure || existsSync14(workspace.configPath)) { + this.cachedConfig = existsSync14(workspace.configPath) ? readKnowledgeConfig(workspace.configPath) : defaultKnowledgeConfig(); + } + return this.cachedConfig; + } + safetyPolicy() { + return resolveSafetyPolicy(this.config(), this.workspace); + } + artifactStore() { + return createArtifactStore(this.config(), this.ensureWorkspace()); + } + storageContract() { + return resolveStorageContract(this.config(), this.workspace, this.scope); + } + validateStorage() { + return validateStorageConfig(this.config(), this.workspace); + } + assertStorageValid(action) { + const validation = this.validateStorage(); + if (!validation.ok) { + throw new Error(`Storage contract invalid before ${action}: ${validation.errors.join("; ")}`); + } + } + migrateLegacyPath(options = {}) { + const current = this.workspace; + const legacy = resolveLegacyScopedWorkspace(this.options.scope, this.options.cwd); + const result = migrateLegacyKnowledgeWorkspace({ + scope: this.scope, + current, + legacy, + approveWrite: options.approveWrite, + approvedBy: options.approvedBy }); - db.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) - VALUES (?, ?, ?, ?)`, [pageId, conceptPageId, "concept", now]); - const citationsWritten = replacePageCitations(db, pageId, citations, now); - const indexesUpdated = upsertIndex(db, { - title, - path, - artifactUri: pageArtifact.uri, - contentHash: pageArtifact.hash ?? "", - now + if (!result.dry_run && result.ok) { + this.ensuredWorkspace = undefined; + this.cachedConfig = undefined; + } + return result; + } + mergeLegacyPath(options = {}) { + const current = this.workspace; + const legacy = resolveLegacyScopedWorkspace(this.options.scope, this.options.cwd); + const result = mergeLegacyKnowledgeWorkspace({ + scope: this.scope, + current, + legacy, + approveWrite: options.approveWrite, + approvedBy: options.approvedBy }); + if (!result.dry_run && result.ok) { + this.ensuredWorkspace = undefined; + this.cachedConfig = undefined; + } + return result; + } + setup(options = {}) { + const workspace = this.ensureWorkspace(); + const current = this.config({ ensure: true }); + const mode2 = normalizeMode(options.mode) ?? current.mode; + const apiUrl = options.apiUrl ? normalizeKnowledgeApiOrigin(options.apiUrl) : current.hosted?.api_url ? normalizeKnowledgeApiOrigin(current.hosted.api_url) : null; + const nextConfig = { + ...current, + mode: mode2, + hosted: { + ...current.hosted ?? {}, + ...apiUrl ? { api_url: apiUrl } : {} + }, + storage: options.canonicalExample ? canonicalExampleKnowledgeStorage() : current.storage + }; + writeKnowledgeConfig(workspace.configPath, nextConfig); + this.cachedConfig = nextConfig; + const storage = resolveStorageContract(nextConfig, workspace, this.scope); return { - page_id: pageId, - path, - artifact_uri: pageArtifact.uri, - content_hash: pageArtifact.hash ?? "", - chunks_seen: rows.length, - citations_written: citationsWritten, - concept_page_id: conceptPageId, - indexes_updated: indexesUpdated, - log_key: log.key, - warnings: [] + ok: true, + mode: mode2, + api_url: nextConfig.hosted?.api_url ?? null, + storage_type: nextConfig.storage.type, + artifact_uri_prefix: storage.artifact_store.uri_prefix, + canonical_example: storage.canonical_example, + config_path: workspace.configPath, + next: mode2 === "hosted" ? ["knowledge auth login --api-key <key>", "knowledge storage status --json"] : ["knowledge search <query>", "knowledge <prompt>"], + message: `Set knowledge mode to ${mode2}` + }; + } + authStatus(env = process.env) { + return knowledgeAuthStatus(this.config(), env); + } + saveAuth(input, env = process.env) { + const apiUrl = input.apiUrl ?? this.config().hosted?.api_url; + return saveKnowledgeAuth({ + api_key: input.apiKey, + email: input.email, + org_id: input.orgId, + org_slug: input.orgSlug, + user_id: input.userId, + api_url: apiUrl + }, env); + } + clearAuth(env = process.env) { + return clearKnowledgeAuth(env); + } + paths() { + const workspace = this.workspace; + return { + ok: true, + scope: this.scope, + home: workspace.home, + exists: existsSync14(workspace.home), + config_path: workspace.configPath, + config_exists: existsSync14(workspace.configPath), + json_store_path: workspace.jsonStorePath, + json_store_exists: existsSync14(workspace.jsonStorePath), + knowledge_db_path: workspace.knowledgeDbPath, + knowledge_db_exists: existsSync14(workspace.knowledgeDbPath), + artifacts_dir: workspace.artifactsDir, + indexes_dir: workspace.indexesDir, + logs_dir: workspace.logsDir, + runs_dir: workspace.runsDir, + schemas_dir: workspace.schemasDir, + wiki_dir: workspace.wikiDir, + config: this.config(), + message: workspace.home + }; + } + initDb() { + return migrateKnowledgeDb(this.ensureWorkspace().knowledgeDbPath); + } + dbStats() { + assertLocalCatalogMode("reading knowledge.db stats"); + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) + return emptyKnowledgeDbStats(); + return getKnowledgeDbStats(workspace.knowledgeDbPath); + } + enqueuePromotion(input) { + return enqueueKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, input); + } + promotionInbox(options = {}) { + return listKnowledgePromotions(this.ensureWorkspace().knowledgeDbPath, options); + } + getPromotion(id) { + return getKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id); + } + reviewPromotion(id, now) { + return reviewKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, now); + } + promoteCandidate(id, options = {}) { + return promoteKnowledgeCandidate(this.ensureWorkspace().knowledgeDbPath, id, options); + } + rejectPromotion(id, options = {}) { + return rejectKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, options); + } + durableRecords(options = {}) { + return listDurableKnowledgeRecords(this.ensureWorkspace().knowledgeDbPath, options); + } + itemOnlyInventory(params) { + const workspace = this.workspace; + const { items, limit, includeArchived, storePath, storeExists, storeReadError } = params; + const activeItems = items.filter((item) => item.archived !== true); + const visibleItems = includeArchived ? items : activeItems; + const stats = emptyKnowledgeDbStats(); + const summary = { + legacy_items: items.length, + active_items: activeItems.length, + archived_items: items.length - activeItems.length, + schema_version: stats.schema_version, + sources: stats.sources, + source_revisions: stats.source_revisions, + chunks: stats.chunks, + wiki_pages: stats.wiki_pages, + citations: stats.citations, + indexes: stats.indexes, + runs: stats.runs, + run_events: stats.run_events, + storage_objects: stats.storage_objects, + embeddings: stats.embeddings, + vector_entries: stats.vector_entries, + reindex_queue: stats.reindex_queue, + redaction_findings: stats.redaction_findings, + audit_events: stats.audit_events, + approval_gates: stats.approval_gates, + knowledge_machines: stats.knowledge_machines, + sync_snapshots: stats.sync_snapshots, + sync_changes: stats.sync_changes, + sync_conflicts: stats.sync_conflicts, + sync_table_clocks: stats.sync_table_clocks, + sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records }; - } finally { - db.close(); - } -} -async function fileAnswerToWiki(options) { - if (!options.approveWrite) { return { - approved: false, - durable_writes_performed: false, - page_id: null, - path: null, - artifact_uri: null, - citations_written: 0, - log_key: null, - message: "Dry-run: answer filing requires --approve-write." + ok: true, + scope: this.scope, + home: workspace.home, + limit, + paths: { + json_store_path: workspace.jsonStorePath, + json_store_exists: existsSync14(workspace.jsonStorePath), + knowledge_db_path: workspace.knowledgeDbPath, + knowledge_db_exists: existsSync14(workspace.knowledgeDbPath), + artifacts_dir: workspace.artifactsDir, + indexes_dir: workspace.indexesDir, + logs_dir: workspace.logsDir, + wiki_dir: workspace.wikiDir + }, + summary, + legacy_store: { + path: storePath, + exists: storeExists, + read_error: storeReadError, + total_items: items.length, + active_items: activeItems.length, + archived_items: items.length - activeItems.length, + items_returned: Math.min(visibleItems.length, limit) + }, + items: visibleItems.slice(0, limit).map(legacyInventoryItem), + sources: [], + source_revisions: [], + chunks: [], + wiki_pages: [], + indexes: [], + storage_objects: [], + runs: [], + vector_indexes: [], + reindex_queue: [], + machines: [], + sync_conflicts: [], + approval_gates: [], + audit_events: [], + promotion_candidates: [], + durable_records: [], + message: `${items.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)` }; } - const nowDate = options.now ?? new Date; - const now = nowDate.toISOString(); - const title = options.prompt.length > 80 ? `${options.prompt.slice(0, 77)}...` : options.prompt; - const slug = slugify3(title); - const path = `wiki/answers/${slug}.md`; - const citations = options.context.citations; - const body = [ - `# ${title}`, - "", - options.answer, - "", - "## Citations", - "", - ...citations.map((citation, index) => `- [C${index + 1}] ${citation.source_ref ?? citation.source_uri ?? citation.artifact_path ?? citation.artifact_uri ?? "unknown"} ${citation.hash ? `(hash ${citation.hash})` : ""}`), - "" - ].join(` -`); - const sourceRefs = citations.map((citation) => citation.source_ref ?? citation.source_uri).filter((ref) => Boolean(ref)); - const provenance = generatedArtifactProvenance({ - generated_from: "knowledge_answer", - artifact_key: path, - source_refs: sourceRefs - }); - const artifact = await writeArtifact2(options.store, { - key: path, - body, - content_type: "text/markdown", - metadata: { generated_from: "knowledge_answer" } - }); - const log = await appendLog2(options.store, { - ts: now, - event: "wiki_answer_filed", - page_key: path, - prompt: options.prompt, - citations: citations.length - }, nowDate); - const pageId = stableId9("wiki", path); - const db = openKnowledgeDb(options.dbPath); - try { - recordStorageObjects(db, [artifact, log], nowDate); - upsertWikiPage(db, { - pageId, - path, - title, - artifactUri: artifact.uri, - contentHash: artifact.hash ?? "", - body, - provenance, - now - }); - const written = replacePageCitations(db, pageId, citations.map((citation) => ({ - chunk_id: citation.chunk_id, - source_uri: citation.source_uri ?? citation.artifact_uri ?? "unknown", - quote: citation.quote, - start_offset: citation.start_offset, - end_offset: citation.end_offset, - metadata: { - source_ref: citation.source_ref, - artifact_path: citation.artifact_path, - revision: citation.revision, - hash: citation.hash - } - })), now); - upsertIndex(db, { - title, - path, - artifactUri: artifact.uri, - contentHash: artifact.hash ?? "", - now + async cloudInventory(options = {}) { + const limit = inventoryLimit(options.limit); + const items = await this.fetchCloudItems(); + const cloud = resolveKnowledgeCloudStore(); + return this.itemOnlyInventory({ + items, + limit, + includeArchived: options.includeArchived ?? false, + storePath: cloud?.baseUrl ?? "cloud", + storeExists: true, + storeReadError: null }); - return { - approved: true, - durable_writes_performed: true, - page_id: pageId, - path, - artifact_uri: artifact.uri, - citations_written: written, - log_key: log.key, - message: `Filed answer to ${path}` - }; - } finally { - db.close(); } -} -function addIssue(issues, issue2) { - issues.push(issue2); -} -function lintWiki(options) { - migrateKnowledgeDb(options.dbPath); - const db = openKnowledgeDb(options.dbPath); - const issues = []; - try { - const activePages = db.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n ?? 0; - const citationCount = db.query("SELECT COUNT(*) AS n FROM citations").get()?.n ?? 0; - const backlinkCount = db.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n ?? 0; - const missingCitations = db.query(`SELECT wp.id, wp.path - FROM wiki_pages wp - LEFT JOIN citations c ON c.wiki_page_id = wp.id - WHERE wp.status = 'active' AND wp.path LIKE 'wiki/generated/%' - GROUP BY wp.id - HAVING COUNT(c.id) = 0`).all(); - for (const page of missingCitations) { - addIssue(issues, { type: "missing_citation", severity: "error", page_id: page.id, path: page.path, message: "Generated wiki page has no citations." }); - } - const stale = db.query(`SELECT wp.id AS page_id, wp.path, c.source_uri, c.chunk_id - FROM citations c - JOIN wiki_pages wp ON wp.id = c.wiki_page_id - LEFT JOIN chunks ch ON ch.id = c.chunk_id - WHERE ch.metadata_json LIKE '%"stale":true%' OR ch.metadata_json LIKE '%"status":"stale"%' OR ch.metadata_json LIKE '%"status":"deleted"%'`).all(); - for (const row of stale) { - addIssue(issues, { type: "stale_citation", severity: "warn", page_id: row.page_id, path: row.path, source_uri: row.source_uri, chunk_id: row.chunk_id ?? undefined, message: "Page cites a stale or deleted source chunk." }); - } - const duplicates = db.query(`SELECT lower(title) AS title, COUNT(*) AS n - FROM wiki_pages - WHERE status = 'active' - GROUP BY lower(title) - HAVING COUNT(*) > 1`).all(); - for (const row of duplicates) { - addIssue(issues, { type: "duplicate_page", severity: "warn", message: `Duplicate active wiki title: ${row.title} (${row.n} pages).` }); - } - const orphans = db.query(`SELECT wp.id, wp.path - FROM wiki_pages wp - LEFT JOIN wiki_backlinks wb1 ON wb1.from_page_id = wp.id - LEFT JOIN wiki_backlinks wb2 ON wb2.to_page_id = wp.id - WHERE wp.status = 'active' - AND wp.path NOT IN ('wiki/README.md') - GROUP BY wp.id - HAVING COUNT(wb1.to_page_id) = 0 AND COUNT(wb2.from_page_id) = 0`).all(); - for (const page of orphans) { - addIssue(issues, { type: "orphan_page", severity: "info", page_id: page.id, path: page.path, message: "Wiki page has no backlinks." }); - } - const unresolved = db.query(`SELECT wp.id AS page_id, wp.path, c.source_uri - FROM citations c - JOIN wiki_pages wp ON wp.id = c.wiki_page_id - LEFT JOIN sources s ON s.uri = c.source_uri - WHERE s.id IS NULL AND c.source_uri NOT LIKE 'file://%' AND c.source_uri NOT LIKE 's3://%' AND c.source_uri NOT LIKE 'https://%' AND c.source_uri NOT LIKE 'open-files://%'`).all(); - for (const row of unresolved) { - addIssue(issues, { type: "unresolved_source_ref", severity: "error", page_id: row.page_id, path: row.path, source_uri: row.source_uri, message: "Citation source URI cannot be resolved to a known or allowed source ref." }); - } - const contradictions = db.query(`SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'`).all(); - for (const page of contradictions) { - addIssue(issues, { type: "contradiction_marker", severity: "warn", page_id: page.id, path: page.path, message: "Page metadata contains a contradiction marker." }); + inventory(options = {}) { + const workspace = this.workspace; + const limit = inventoryLimit(options.limit); + const storePath = options.storePath ?? workspace.jsonStorePath; + const legacyStore = readLegacyInventoryStore(storePath); + const activeItems = legacyStore.items.filter((item) => item.archived !== true); + const visibleItems = options.includeArchived ? legacyStore.items : activeItems; + const dbExists = existsSync14(workspace.knowledgeDbPath); + if (!dbExists) { + return this.itemOnlyInventory({ + items: legacyStore.items, + limit, + includeArchived: options.includeArchived ?? false, + storePath, + storeExists: legacyStore.exists, + storeReadError: legacyStore.read_error + }); } - const newArticleCandidates = db.query(`SELECT c.id AS chunk_id, s.uri AS source_uri - FROM chunks c - JOIN source_revisions sr ON sr.id = c.source_revision_id - JOIN sources s ON s.id = sr.source_id - LEFT JOIN citations cit ON cit.chunk_id = c.id - WHERE c.kind = 'source' - GROUP BY c.id - HAVING COUNT(cit.id) = 0 - LIMIT 25`).all(); - for (const row of newArticleCandidates) { - addIssue(issues, { type: "new_article_candidate", severity: "info", chunk_id: row.chunk_id, source_uri: row.source_uri ?? undefined, message: "Source chunk is indexed but not cited by any wiki page yet." }); + migrateKnowledgeDb(workspace.knowledgeDbPath); + const stats = getKnowledgeDbStats(workspace.knowledgeDbPath); + const db = openKnowledgeDb(workspace.knowledgeDbPath); + try { + const sources = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT + s.id, + s.uri, + s.kind, + s.title, + s.metadata_json, + s.acl_json, + s.created_at, + s.updated_at, + COUNT(DISTINCT sr.id) AS revisions, + COUNT(DISTINCT c.id) AS chunks + FROM sources s + LEFT JOIN source_revisions sr ON sr.source_id = s.id + LEFT JOIN chunks c ON c.source_revision_id = sr.id + GROUP BY s.id + ORDER BY s.updated_at DESC, s.created_at DESC + LIMIT ? + `, [limit]), ["metadata_json", "acl_json"]); + const sourceRevisions = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT + sr.id, + s.uri AS source_uri, + sr.revision, + sr.hash, + sr.extracted_text_uri, + sr.metadata_json, + sr.created_at + FROM source_revisions sr + JOIN sources s ON s.id = sr.source_id + ORDER BY sr.created_at DESC + LIMIT ? + `, [limit])); + const chunks = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT + c.id, + c.kind, + c.ordinal, + substr(c.text, 1, 220) AS text_preview, + c.token_count, + c.start_offset, + c.end_offset, + c.metadata_json, + c.created_at, + s.uri AS source_uri, + sr.revision AS source_revision, + wp.path AS wiki_path, + wp.title AS wiki_title + FROM chunks c + LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id + LEFT JOIN sources s ON s.id = sr.source_id + LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id + ORDER BY c.created_at DESC, c.ordinal ASC + LIMIT ? + `, [limit])); + const wikiPages = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at + FROM wiki_pages + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit])); + const indexes = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at + FROM knowledge_indexes + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit])); + const storageObjects = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at + FROM storage_objects + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit])); + const runs = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT + id, + type, + substr(prompt, 1, 220) AS prompt_preview, + status, + provider, + model, + cost_tokens, + cost_usd, + metadata_json, + created_at, + updated_at + FROM runs + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit])); + const vectorIndexes = selectInventoryRows(db, ` + SELECT provider, model, dimensions, status, COUNT(*) AS entries + FROM vector_index_entries + GROUP BY provider, model, dimensions, status + ORDER BY entries DESC + LIMIT ? + `, [limit]); + const reindexQueue = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT id, kind, target_id, source_uri, reason, status, attempts, metadata_json, created_at, updated_at + FROM reindex_queue + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit])); + const machines = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT + machine_id, + hostname, + platform, + user_label, + workspace_home, + tailscale_dns, + tailscale_ips_json, + ssh_target, + last_seen_at, + capabilities_json, + metadata_json, + created_at, + updated_at + FROM knowledge_machines + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]), ["tailscale_ips_json", "capabilities_json", "metadata_json"]); + const syncConflicts = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT + id, + entity_kind, + entity_id, + local_machine_id, + remote_machine_id, + status, + resolution_strategy, + proposed_patch_uri, + approved_by, + resolved_at, + metadata_json, + created_at + FROM knowledge_sync_conflicts + ORDER BY created_at DESC + LIMIT ? + `, [limit])); + const approvalGates = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at + FROM approval_gates + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit])); + const auditEvents = rowsWithJsonFields(selectInventoryRows(db, ` + SELECT id, event_type, action, target_uri, decision, metadata_json, created_at + FROM audit_events + ORDER BY created_at DESC + LIMIT ? + `, [limit])); + const promotionCandidates = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + source_kind, + source_refs_json, + evidence_refs_json, + status, + requires_approval, + checks_json, + duplicate_of, + approved_by, + promoted_record_id, + metadata_json, + created_at, + updated_at, + reviewed_at, + promoted_at + FROM knowledge_promotion_candidates + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(promotionCandidateInventoryRow); + const durableRecords = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + status, + source_refs_json, + evidence_refs_json, + confidence, + valid_from, + valid_to, + promoted_from_candidate_id, + approved_by, + metadata_json, + created_at, + updated_at + FROM durable_knowledge_records + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(durableRecordInventoryRow); + const summary = { + legacy_items: legacyStore.items.length, + active_items: activeItems.length, + archived_items: legacyStore.items.length - activeItems.length, + schema_version: stats.schema_version, + sources: stats.sources, + source_revisions: stats.source_revisions, + chunks: stats.chunks, + wiki_pages: stats.wiki_pages, + citations: stats.citations, + indexes: stats.indexes, + runs: stats.runs, + run_events: stats.run_events, + storage_objects: stats.storage_objects, + embeddings: stats.embeddings, + vector_entries: stats.vector_entries, + reindex_queue: stats.reindex_queue, + redaction_findings: stats.redaction_findings, + audit_events: stats.audit_events, + approval_gates: stats.approval_gates, + knowledge_machines: stats.knowledge_machines, + sync_snapshots: stats.sync_snapshots, + sync_changes: stats.sync_changes, + sync_conflicts: stats.sync_conflicts, + sync_table_clocks: stats.sync_table_clocks, + sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records + }; + return { + ok: true, + scope: this.scope, + home: workspace.home, + limit, + paths: { + json_store_path: storePath, + json_store_exists: legacyStore.exists, + knowledge_db_path: workspace.knowledgeDbPath, + knowledge_db_exists: true, + artifacts_dir: workspace.artifactsDir, + indexes_dir: workspace.indexesDir, + logs_dir: workspace.logsDir, + wiki_dir: workspace.wikiDir + }, + summary, + legacy_store: { + path: storePath, + exists: legacyStore.exists, + read_error: legacyStore.read_error, + total_items: legacyStore.items.length, + active_items: activeItems.length, + archived_items: legacyStore.items.length - activeItems.length, + items_returned: Math.min(visibleItems.length, limit) + }, + items: visibleItems.slice(0, limit).map(legacyInventoryItem), + sources, + source_revisions: sourceRevisions, + chunks, + wiki_pages: wikiPages, + indexes, + storage_objects: storageObjects, + runs, + vector_indexes: vectorIndexes, + reindex_queue: reindexQueue, + machines, + sync_conflicts: syncConflicts, + approval_gates: approvalGates, + audit_events: auditEvents, + promotion_candidates: promotionCandidates, + durable_records: durableRecords, + message: `${legacyStore.items.length} item(s), ${stats.sources} source(s), ${stats.chunks} chunk(s), ${stats.wiki_pages} wiki page(s), ${stats.storage_objects} artifact(s)` + }; + } finally { + db.close(); } - return { - ok: issues.every((issue2) => issue2.severity !== "error"), - issue_count: issues.length, - issues, - counts: { - active_pages: activePages, - citations: citationCount, - backlinks: backlinkCount, - new_article_candidates: newArticleCandidates.length - } - }; - } finally { - db.close(); - } -} - -// src/item-store.ts -import { existsSync as existsSync12 } from "fs"; -class VersionHistoryUnsupportedError extends Error { - location; - code = "version_history_unsupported"; - constructor(location) { - super("Version history is not kept by the local JSON knowledge store " + `(${location}). It has no version line, so an empty history here would be a claim, not a measurement. ` + "Entry versioning lives in the Postgres-backed store: point this CLI at it " + "(HASNA_KNOWLEDGE_STORAGE_MODE=cloud plus the API url/key) and re-run."); - this.location = location; - this.name = "VersionHistoryUnsupportedError"; - } -} -function matchesId(item, idOrShort) { - return item.id === idOrShort || item.short_id === idOrShort; -} - -class LocalItemStore { - storePath; - kind = "local"; - supportsVersions = false; - constructor(storePath) { - this.storePath = storePath; - } - async listVersions() { - throw new VersionHistoryUnsupportedError(this.storePath); - } - async getVersion() { - throw new VersionHistoryUnsupportedError(this.storePath); } - get location() { - return this.storePath; - } - get exists() { - return existsSync12(this.storePath); - } - async listAll() { - const store = loadStoreIfExists(this.storePath); - return { items: store.items, exists: store.exists }; - } - async get(idOrShort) { - const store = loadStoreIfExists(this.storePath); - return store.items.find((item) => matchesId(item, idOrShort)) ?? null; - } - async create(input) { - return withLock(this.storePath, () => { - const db = loadStore(this.storePath); - const now = new Date().toISOString(); - const id = input.id ?? makeId(); - const item = { - id, - short_id: makeShortId(id), - title: input.title, - content: input.content, - url: input.url ?? null, - tags: input.tags ?? [], - metadata: input.metadata ?? {}, - archived: false, - created_at: now, - updated_at: now - }; - db.items.push(item); - saveStore(this.storePath, db); - return item; - }, { createParent: true }); + assertAppWikiWrite(allowGlobal) { + assertAppWikiWriteAllowed({ + scope: this.scope, + workspace: this.workspace, + safetyPolicy: this.safetyPolicy(), + allowGlobal + }); } - async update(idOrShort, patch) { - return withLock(this.storePath, () => { - const db = loadStore(this.storePath); - const idx = db.items.findIndex((item2) => matchesId(item2, idOrShort)); - if (idx === -1) - return null; - const item = db.items[idx]; - if (patch.title !== undefined) - item.title = patch.title; - if (patch.content !== undefined) - item.content = patch.content; - if (patch.url !== undefined) - item.url = patch.url; - if (patch.tags !== undefined) - item.tags = patch.tags; - if (patch.metadata !== undefined) - item.metadata = patch.metadata; - if (patch.archived !== undefined) - item.archived = patch.archived; - item.updated_at = new Date().toISOString(); - db.items[idx] = item; - saveStore(this.storePath, db); - return item; - }, { createParent: true }); + async initAppWiki(options = {}) { + this.assertAppWikiWrite(options.allowGlobal); + const workspace = this.ensureWorkspace(); + return initAppWikiScope({ + scope: this.scope, + workspace, + store: this.artifactStore(), + safetyPolicy: this.safetyPolicy(), + allowGlobal: options.allowGlobal + }); } - async delete(idOrShort) { - return withLock(this.storePath, () => { - const db = loadStore(this.storePath); - const before = db.items.length; - db.items = db.items.filter((item) => !matchesId(item, idOrShort)); - const removed = before !== db.items.length; - if (removed) - saveStore(this.storePath, db); - return removed; - }, { createParent: true }); + async addAppWikiNote(options) { + this.assertAppWikiWrite(options.allowGlobal); + const workspace = this.ensureWorkspace(); + return writeAppWikiNote({ + scope: this.scope, + workspace, + store: this.artifactStore(), + safetyPolicy: this.safetyPolicy(), + allowGlobal: options.allowGlobal, + title: options.title, + content: options.content, + tags: options.tags, + sourceRefs: options.sourceRefs, + path: options.path, + metadata: options.metadata + }); } - async deleteMany(idsOrShorts) { - if (idsOrShorts.length === 0) - return 0; - const targets = new Set(idsOrShorts); - return withLock(this.storePath, () => { - const db = loadStore(this.storePath); - const before = db.items.length; - db.items = db.items.filter((item) => !targets.has(item.id) && !(item.short_id != null && targets.has(item.short_id))); - const removed = before - db.items.length; - if (removed > 0) - saveStore(this.storePath, db); - return removed; - }, { createParent: true }); + listAppWikiNotes(options = {}) { + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) + return []; + return listAppWikiNotes({ + dbPath: workspace.knowledgeDbPath, + limit: options.limit + }); } -} - -class ApiItemStore { - cloud; - kind = "api"; - exists = true; - supportsVersions = true; - constructor(cloud) { - this.cloud = cloud; + async getAppWikiNote(id, options = {}) { + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) + return null; + return getAppWikiNote({ + dbPath: workspace.knowledgeDbPath, + store: this.artifactStore(), + id, + includeContent: options.includeContent + }); } - async listVersions(idOrShort, options = {}) { - return this.cloud.listVersions(idOrShort, options); + async addAppWikiSourceRef(options) { + this.assertAppWikiWrite(options.allowGlobal); + const workspace = this.ensureWorkspace(); + return ingestAppWikiSourceRef({ + scope: this.scope, + workspace, + sourceRef: options.sourceRef, + purpose: options.purpose, + config: this.config(), + safetyPolicy: this.safetyPolicy(), + allowGlobal: options.allowGlobal + }); } - async getVersion(idOrShort, version2) { - return this.cloud.getVersion(idOrShort, version2); + async searchAppWiki(options) { + return this.search(options); } - get location() { - return this.cloud.baseUrl; + async queryAppWiki(options) { + return this.retrieveContext(options); } - async listAll() { - return { items: await fetchAllCloudItems(this.cloud), exists: true }; + async initWiki() { + const workspace = this.ensureWorkspace(); + migrateKnowledgeDb(workspace.knowledgeDbPath); + const result = await initializeWikiLayout(this.artifactStore()); + const db = openKnowledgeDb(workspace.knowledgeDbPath); + try { + recordStorageObjects(db, result.artifacts); + recordWikiLayoutCatalog(db, result.artifacts); + } finally { + db.close(); + } + return result; } - async get(idOrShort) { - return this.cloud.get(idOrShort); + async compileWiki(options = {}) { + const workspace = this.ensureWorkspace(); + return compileWikiPage({ + ...options, + dbPath: workspace.knowledgeDbPath, + store: this.artifactStore() + }); } - async create(input) { - return this.cloud.create({ - ...input.id ? { id: input.id } : {}, - title: input.title, - content: input.content, - url: input.url ?? null, - tags: input.tags ?? [], - ...input.metadata ? { metadata: input.metadata } : {} + async fileAnswer(options) { + const workspace = this.ensureWorkspace(); + const context = await this.retrieveContext({ + query: options.prompt, + limit: options.limit, + semantic: options.semantic, + modelRef: options.modelRef, + dimensions: options.dimensions, + fake: options.fake + }); + return fileAnswerToWiki({ + dbPath: workspace.knowledgeDbPath, + store: this.artifactStore(), + prompt: options.prompt, + answer: options.answer, + context, + approveWrite: options.approveWrite }); } - async update(idOrShort, patch, options = {}) { - return this.cloud.update(idOrShort, patch, { expectedVersion: options.expectedVersion }); + lintWiki() { + const workspace = this.ensureWorkspace(); + return lintWiki({ dbPath: workspace.knowledgeDbPath }); } - async delete(idOrShort) { - return this.cloud.delete(idOrShort); + async ingestManifest(input) { + const workspace = this.ensureWorkspace(); + return ingestOpenFilesManifest({ + dbPath: workspace.knowledgeDbPath, + input, + config: this.config(), + safetyPolicy: this.safetyPolicy() + }); } - async deleteMany(idsOrShorts) { - let removed = 0; - for (const id of idsOrShorts) { - if (await this.cloud.delete(id)) - removed += 1; - } - return removed; + async ingestSource(sourceRef, purpose) { + const workspace = this.ensureWorkspace(); + return ingestSourceRef({ + dbPath: workspace.knowledgeDbPath, + sourceRef, + purpose, + config: this.config(), + safetyPolicy: this.safetyPolicy() + }); } -} -function resolveItemStore(options) { - const cloud = options.storePathOverridden ? null : resolveKnowledgeCloudStore(options.env ?? process.env); - if (cloud) - return new ApiItemStore(cloud); - return new LocalItemStore(options.storePath); -} - -// src/wiki-layout.ts -import { createHash as createHash19 } from "crypto"; -function todayParts2(now) { - const year = String(now.getUTCFullYear()); - const month = String(now.getUTCMonth() + 1).padStart(2, "0"); - const day = String(now.getUTCDate()).padStart(2, "0"); - return { year, month, day }; -} -function stableId10(prefix, value) { - return `${prefix}_${createHash19("sha256").update(value).digest("hex").slice(0, 20)}`; -} -function estimateTokenCount4(text) { - const words = text.trim().split(/\s+/).filter(Boolean).length; - return Math.max(1, Math.ceil(words * 1.25)); -} -function agentSchemaTemplate() { - return `# Knowledge Agent Schema v1 - -## Source Rules - -- Treat open-files source references as the preferred source of truth. -- Do not copy raw source files into knowledge. -- Cite every durable fact with a source URI, revision/hash when available, and optional span. -- Mark uncertainty explicitly when sources disagree or are incomplete. - -## Wiki Rules - -- Write generated knowledge as Markdown pages under wiki/. -- Keep root indexes small; use topic, team, project, and machine-readable shards for scale. -- Preserve backlinks between related pages and decisions. -- Prefer updating existing pages over creating near-duplicates. - -## Query Rules - -- Search wiki pages first, then source chunks, then deeper read-only source refs. -- Use web search only when requested or when current external context is required. -- File useful answers back into the wiki only after approval or approved auto-write mode. - -## Lint Rules - -- Flag stale pages, missing citations, contradictions, orphan pages, duplicate pages, and unresolved source refs. -`; -} -function rootIndexTemplate() { - return `# Knowledge Index - -This is a compact orientation index for agents. It is not the full search index. - -## Shards - -- wiki/ -- indexes/ -- schemas/ -- logs/ - -## Source Ownership - -Raw source files are resolved through open-files. This app stores source refs, -citations, chunks, generated wiki artifacts, indexes, and run records. -`; -} -function wikiReadmeTemplate() { - return `# Wiki - -Generated durable knowledge pages live here. - -Pages should be concise, cited, and organized for both humans and agents. -`; -} -async function initializeWikiLayout(store, now = new Date) { - const { year, month, day } = todayParts2(now); - const schemaKey = "schemas/v1.md"; - const rootIndexKey = "indexes/root.md"; - const wikiReadmeKey = "wiki/README.md"; - const logKey = `logs/${year}/${month}/${day}.jsonl`; - const event = { - ts: now.toISOString(), - event: "wiki_layout_initialized", - schema_key: schemaKey, - root_index_key: rootIndexKey, - wiki_readme_key: wikiReadmeKey - }; - const entries = [ - { key: schemaKey, body: agentSchemaTemplate(), content_type: "text/markdown" }, - { key: rootIndexKey, body: rootIndexTemplate(), content_type: "text/markdown" }, - { key: wikiReadmeKey, body: wikiReadmeTemplate(), content_type: "text/markdown" }, - { key: logKey, body: `${JSON.stringify(event)} -`, content_type: "application/x-ndjson" } - ]; - const artifacts = await Promise.all(entries.map(async (entry) => { - const result = await store.put(entry); - return { - key: result.key, - uri: result.uri, - kind: artifactKindForKey(entry.key), - content_type: entry.content_type, - modified_at: result.modified_at, - metadata: { - provenance: generatedArtifactProvenance({ - generated_from: "wiki_layout_init", - artifact_key: entry.key, - citation_required: entry.key.startsWith("wiki/") || entry.key.startsWith("indexes/") - }) - }, - ...hashArtifactBody(entry.body) - }; - })); - return { - schema_key: schemaKey, - root_index_key: rootIndexKey, - wiki_readme_key: wikiReadmeKey, - log_key: logKey, - artifacts, - written: [schemaKey, rootIndexKey, wikiReadmeKey, logKey] - }; -} -function provenanceFor(artifact) { - const existing = artifact.metadata?.provenance; - if (existing && typeof existing === "object" && !Array.isArray(existing)) { - return existing; + async importRulesProvenance(options = {}) { + const dryRun = options.dryRun !== false; + const workspace = dryRun ? this.workspace : this.ensureWorkspace(); + return importRulesProvenance({ + root: options.root ?? this.options.cwd ?? process.cwd(), + scope: this.scope, + owner: options.owner, + dryRun, + deprecateLegacy: options.deprecateLegacy, + includeLegacy: options.includeLegacy, + legacyStorePath: workspace.jsonStorePath, + dbPath: workspace.knowledgeDbPath, + safetyPolicy: this.safetyPolicy(), + maxItems: options.maxItems, + limit: options.limit + }); } - return generatedArtifactProvenance({ - generated_from: "wiki_layout_init", - artifact_key: artifact.key - }); -} -function recordWikiChunk(db, pageId, title, artifact, body, now) { - const provenance = provenanceFor(artifact); - const chunkId = stableId10("chk", `${pageId}\x00${artifact.hash ?? artifact.uri}`); - const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(pageId); - for (const row of existing) - db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); - db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [pageId]); - db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - chunkId, - pageId, - "wiki", - 0, - body, - estimateTokenCount4(body), - 0, - body.length, - JSON.stringify({ - artifact_key: artifact.key, - artifact_uri: artifact.uri, - content_hash: artifact.hash ?? null, - provenance - }), - now - ]); - db.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)", [chunkId, body, title, artifact.uri]); -} -function recordWikiLayoutCatalog(db, artifacts, now = new Date) { - const timestamp = now.toISOString(); - const rootIndex = artifacts.find((artifact) => artifact.key.endsWith("indexes/root.md")); - const wikiReadme = artifacts.find((artifact) => artifact.key.endsWith("wiki/README.md")); - if (rootIndex) { - db.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(kind, name, shard_key) DO UPDATE SET - artifact_uri = excluded.artifact_uri, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`, [ - stableId10("idx", "root:indexes/root.md"), - "root", - "root", - rootIndex.uri, - "root", - JSON.stringify({ - artifact_key: rootIndex.key, - content_hash: rootIndex.hash ?? null, - provenance: provenanceFor(rootIndex) - }), - timestamp, - timestamp - ]); + async resolveSource(sourceRef, options = {}) { + const workspace = this.ensureWorkspace(); + return resolveOpenFilesSource({ + dbPath: workspace.knowledgeDbPath, + sourceRef, + purpose: options.purpose, + limit: options.limit, + safetyPolicy: this.safetyPolicy() + }); } - if (wikiReadme) { - const wikiPageId = stableId10("wiki", "wiki/README.md"); - db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(path) DO UPDATE SET - title = excluded.title, - artifact_uri = excluded.artifact_uri, - content_hash = excluded.content_hash, - status = excluded.status, - metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`, [ - wikiPageId, - "wiki/README.md", - "Wiki", - wikiReadme.uri, - wikiReadme.hash ?? null, - "active", - JSON.stringify({ - artifact_key: wikiReadme.key, - provenance: provenanceFor(wikiReadme) - }), - timestamp, - timestamp - ]); - recordWikiChunk(db, wikiPageId, "Wiki", wikiReadme, wikiReadmeTemplate(), timestamp); + async consumeOutbox(input) { + const workspace = this.ensureWorkspace(); + return consumeOpenFilesOutbox({ + dbPath: workspace.knowledgeDbPath, + input, + config: this.config(), + safetyPolicy: this.safetyPolicy() + }); } -} - -// src/workspace-migration.ts -import { createHash as createHash20 } from "crypto"; -import { - cpSync, - chmodSync as chmodSync4, - existsSync as existsSync13, - lstatSync as lstatSync3, - mkdirSync as mkdirSync4, - readdirSync as readdirSync3, - readFileSync as readFileSync13, - renameSync as renameSync2, - rmSync, - writeFileSync as writeFileSync5 -} from "fs"; -import { dirname as dirname5, join as join7, relative as relative5 } from "path"; -function walkFiles(root, base = root) { - if (!existsSync13(root)) - return []; - const stat = lstatSync3(root); - if (stat.isFile()) - return [relative5(base, root) || "."]; - if (!stat.isDirectory()) - return []; - return readdirSync3(root).flatMap((entry) => walkFiles(join7(root, entry), base)).sort(); -} -function hashFiles(root, files) { - if (files.length === 0) - return { sha256: null, bytes: 0 }; - const tree = createHash20("sha256"); - let bytes = 0; - for (const file2 of files) { - const path = join7(root, file2); - const body = readFileSync13(path); - const fileHash = createHash20("sha256").update(body).digest("hex"); - bytes += body.byteLength; - tree.update(file2); - tree.update("\x00"); - tree.update(fileHash); - tree.update("\x00"); + reindexHealth(options = {}) { + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) + return emptyReindexHealth(); + return reindexHealth({ + ...options, + dbPath: workspace.knowledgeDbPath, + config: this.config() + }); } - return { sha256: tree.digest("hex"), bytes }; -} -function jsonItemCount(path) { - if (!existsSync13(path)) - return null; - const parsed = JSON.parse(readFileSync13(path, "utf8")); - return Array.isArray(parsed.items) ? parsed.items.length : null; -} -function sqliteSummary(path) { - if (!existsSync13(path)) { - return { exists: false, integrity_check: null, table_counts: {} }; + enqueueReindex(options = {}) { + const workspace = this.ensureWorkspace(); + return enqueueMissingEmbeddings({ + ...options, + dbPath: workspace.knowledgeDbPath, + config: this.config() + }); } - const db = openKnowledgeDbReadonly(path); - try { - const integrity = db.query("PRAGMA integrity_check").get(); - const integrityCheck = integrity ? Object.values(integrity)[0] ?? null : null; - const tables = db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(); - const tableCounts2 = {}; - for (const table of tables) { - const quoted = `"${table.name.replaceAll('"', '""')}"`; - const count3 = db.query(`SELECT COUNT(*) AS n FROM ${quoted}`).get(); - tableCounts2[table.name] = count3?.n ?? 0; - } - return { exists: true, integrity_check: integrityCheck, table_counts: tableCounts2 }; - } finally { - db.close(); + async refreshEmbeddings(options = {}) { + const workspace = this.ensureWorkspace(); + return refreshEmbeddingIndex({ + ...options, + dbPath: workspace.knowledgeDbPath, + config: this.config() + }); } -} -function summarizeWorkspaceTree(workspace, options = {}) { - const files = walkFiles(workspace.home); - const treeHash = hashFiles(workspace.home, files); - const artifactFiles = walkFiles(workspace.artifactsDir); - const artifactHash = hashFiles(workspace.artifactsDir, artifactFiles); - const sqliteExists = existsSync13(workspace.knowledgeDbPath); - return { - path: workspace.home, - exists: existsSync13(workspace.home), - file_count: files.length, - total_bytes: treeHash.bytes, - tree_sha256: treeHash.sha256, - json_items: jsonItemCount(workspace.jsonStorePath), - sqlite: options.includeSqlite === false ? { exists: sqliteExists, integrity_check: null, table_counts: {} } : sqliteSummary(workspace.knowledgeDbPath), - artifacts: { - exists: existsSync13(workspace.artifactsDir), - file_count: artifactFiles.length, - total_bytes: artifactHash.bytes, - tree_sha256: artifactHash.sha256 - }, - files - }; -} -function isDefaultScaffold(workspace, summary) { - if (!summary.exists) - return true; - const materialFiles = summary.files.filter((file2) => file2 !== "config.json"); - if (materialFiles.length > 0) - return false; - if (!summary.files.includes("config.json")) - return true; - try { - return JSON.stringify(JSON.parse(readFileSync13(workspace.configPath, "utf8"))) === JSON.stringify(defaultKnowledgeConfig()); - } catch { - return false; + providerStatus(env = process.env) { + return providerStatus(this.config(), env); } -} -function summariesMatch(left, right) { - return left.file_count === right.file_count && left.total_bytes === right.total_bytes && left.tree_sha256 === right.tree_sha256 && left.json_items === right.json_items && left.sqlite.integrity_check === right.sqlite.integrity_check && JSON.stringify(left.sqlite.table_counts) === JSON.stringify(right.sqlite.table_counts) && left.artifacts.file_count === right.artifacts.file_count && left.artifacts.total_bytes === right.artifacts.total_bytes && left.artifacts.tree_sha256 === right.artifacts.tree_sha256; -} -function migrationTimestamp(now) { - return now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); -} -function stableJson2(value) { - if (Array.isArray(value)) - return `[${value.map(stableJson2).join(",")}]`; - if (value && typeof value === "object") { - return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson2(entry)}`).join(",")}}`; + modelRegistry() { + return listModelRegistry(this.config()); } - return JSON.stringify(value); -} -function itemSignature(item) { - return stableJson2(item); -} -function itemShortId(item) { - return typeof item.short_id === "string" && item.short_id.trim().length > 0 ? item.short_id : null; -} -function readMergeStore(path) { - if (!existsSync13(path)) - return { items: [] }; - const parsed = JSON.parse(readFileSync13(path, "utf8")); - if (!parsed || !Array.isArray(parsed.items)) { - throw new Error(`Invalid knowledge JSON store shape at ${path}`); + embeddingStatus() { + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) + return emptyEmbeddingStatus(); + return embeddingIndexStatus(workspace.knowledgeDbPath); } - return { items: parsed.items }; -} -function mergeStats(currentStore, legacyStore) { - const currentById = new Map(currentStore.items.map((item) => [item.id, item])); - const reservedKeys = new Map; - for (const item of currentStore.items) { - const existingId = reservedKeys.get(item.id); - if (existingId && existingId.item.id !== item.id) {} - reservedKeys.set(item.id, { item, keyKind: "id", source: "current" }); - const shortId = itemShortId(item); - if (shortId && !reservedKeys.has(shortId)) { - reservedKeys.set(shortId, { item, keyKind: "short_id", source: "current" }); + async indexEmbeddings(options = {}) { + const workspace = this.ensureWorkspace(); + return indexKnowledgeEmbeddings({ + ...options, + dbPath: workspace.knowledgeDbPath, + config: this.config() + }); + } + isApiMode() { + return isKnowledgeApiMode(); + } + async fetchCloudItems() { + const cloud = resolveKnowledgeCloudStore(); + if (!cloud) + throw new Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY)."); + return fetchAllCloudItems(cloud); + } + async semanticSearch(options) { + const workspace = this.workspace; + if (this.isApiMode()) { + const items = await this.fetchCloudItems(); + const search = await hybridSearchItems(items, { ...options }, ["semantic_search_requires_local_catalog"]); + return { + provider: "openai", + model: "text-embedding-3-small", + dimensions: options.dimensions ?? 1536, + query: options.query, + results: search.results + }; + } + if (!existsSync14(workspace.knowledgeDbPath)) { + return { + provider: "openai", + model: "text-embedding-3-small", + dimensions: options.dimensions ?? 1536, + query: options.query, + results: [] + }; } + return searchVectorIndex({ + ...options, + dbPath: workspace.knowledgeDbPath, + config: this.config() + }); } - const conflicts = []; - let duplicateIdsIdentical = 0; - let duplicateIdsConflicting = 0; - let shortIdConflicts = 0; - const stranded = []; - for (const legacyItem of legacyStore.items) { - const currentItem = currentById.get(legacyItem.id); - if (currentItem) { - if (itemSignature(currentItem) === itemSignature(legacyItem)) { - duplicateIdsIdentical += 1; - } else { - duplicateIdsConflicting += 1; - conflicts.push({ - type: "id_conflict", - id: legacyItem.id, - legacy_title: legacyItem.title, - current_title: currentItem.title + async search(options) { + const workspace = this.workspace; + if (this.isApiMode()) { + const items = await this.fetchCloudItems(); + return hybridSearchItems(items, options); + } + const legacyStorePath = legacyStorePathForRead(this.scope, workspace, options.legacyStorePath); + if (!existsSync14(workspace.knowledgeDbPath)) { + if (existsSync14(legacyStorePath)) { + return hybridSearchLegacyStore({ + ...options, + legacyStorePath, + config: this.config() }); } - continue; + return emptySearchResult(options.query, Math.max(1, Math.min(options.limit ?? 10, 100)), options.semantic === true || options.fake === true || Boolean(options.modelRef)); } - const keys = [ - { key: legacyItem.id, keyKind: "id" }, - ...itemShortId(legacyItem) ? [{ key: itemShortId(legacyItem), keyKind: "short_id" }] : [] - ]; - let itemHasConflict = false; - for (const { key, keyKind } of keys) { - const existing = reservedKeys.get(key); - if (!existing) - continue; - if (keyKind === "id" && existing.keyKind === "id") { - duplicateIdsConflicting += 1; - conflicts.push({ - type: "id_conflict", - id: key, - legacy_id: legacyItem.id, - current_id: existing.item.id, - legacy_title: legacyItem.title, - current_title: existing.item.title + return hybridSearch({ + ...options, + dbPath: workspace.knowledgeDbPath, + legacyStorePath, + config: this.config() + }); + } + async retrieveContext(options) { + const workspace = this.workspace; + if (this.isApiMode()) { + const items = await this.fetchCloudItems(); + return retrieveKnowledgeContextFromItems(items, options); + } + const legacyStorePath = legacyStorePathForRead(this.scope, workspace, options.legacyStorePath); + if (!existsSync14(workspace.knowledgeDbPath)) { + if (existsSync14(legacyStorePath)) { + const search = await hybridSearchLegacyStore({ + ...options, + legacyStorePath, + config: this.config() }); - } else { - shortIdConflicts += 1; - conflicts.push({ - type: "short_id_conflict", - id: key, - legacy_id: legacyItem.id, - current_id: existing.item.id, - legacy_title: legacyItem.title, - current_title: existing.item.title + return retrieveKnowledgeContextFromSearch(search, { + contextChars: options.contextChars }); } - itemHasConflict = true; + return emptyContextPack(options.query, Math.max(1, Math.min(options.limit ?? 10, 100)), options.semantic === true || options.fake === true || Boolean(options.modelRef)); } - if (itemHasConflict) { - continue; + return retrieveKnowledgeContext({ + ...options, + dbPath: workspace.knowledgeDbPath, + legacyStorePath, + config: this.config() + }); + } + async contextPack(options) { + const workspace = this.workspace; + if (this.isApiMode()) { + const query2 = (options.query ?? options.topic ?? "").trim(); + if (query2 && options.source !== "loops" && options.source !== "runs") { + const items = await this.fetchCloudItems(); + const search = await hybridSearchItems(items, { ...options, query: query2 }); + const context = retrieveKnowledgeContextFromSearch(search, { contextChars: options.contextChars }); + return legacyAgentContextPack(options, context, this.safetyPolicy()); + } + return emptyAgentContextPack(options); } - stranded.push(legacyItem); - for (const { key, keyKind } of keys) { - reservedKeys.set(key, { item: legacyItem, keyKind, source: "legacy" }); + const legacyStorePath = legacyStorePathForRead(this.scope, workspace, options.legacyStorePath); + if (!existsSync14(workspace.knowledgeDbPath)) { + const query2 = (options.query ?? options.topic ?? "").trim(); + if (query2 && options.source !== "loops" && options.source !== "runs" && existsSync14(legacyStorePath)) { + const search = await hybridSearchLegacyStore({ + ...options, + query: query2, + legacyStorePath, + config: this.config() + }); + const context = retrieveKnowledgeContextFromSearch(search, { + contextChars: options.contextChars + }); + return legacyAgentContextPack(options, context, this.safetyPolicy()); + } + return emptyAgentContextPack(options); } + return buildKnowledgeAgentContextPack({ + ...options, + dbPath: workspace.knowledgeDbPath, + legacyStorePath, + config: this.config(), + safetyPolicy: this.safetyPolicy() + }); } - const mergedStore = { items: [...currentStore.items, ...stranded] }; - return { - stats: { - current_items: currentStore.items.length, - legacy_items: legacyStore.items.length, - duplicate_ids_identical: duplicateIdsIdentical, - duplicate_ids_conflicting: duplicateIdsConflicting, - short_id_conflicts: shortIdConflicts, - stranded_items: stranded.length, - merged_items: conflicts.length === 0 ? stranded.length : 0, - expected_total_items: currentStore.items.length + stranded.length, - final_items: null - }, - conflicts, - mergedStore - }; -} -function withStoreLocks(paths, fn) { - const uniquePaths = [...new Set(paths)].sort(); - const run = (index) => { - if (index >= uniquePaths.length) - return fn(); - return withLock(uniquePaths[index], () => run(index + 1), { createParent: true }); - }; - return run(0); -} -function mergeLegacyKnowledgeWorkspace(options) { - const now = options.now ?? new Date; - const dryRun = options.approveWrite !== true; - const legacyBefore = summarizeWorkspaceTree(options.legacy); - const currentBefore = summarizeWorkspaceTree(options.current); - const checks3 = { - legacy_exists: legacyBefore.exists, - legacy_store_exists: existsSync13(options.legacy.jsonStorePath), - current_store_exists: existsSync13(options.current.jsonStorePath), - approval_present: options.approveWrite === true && Boolean(options.approvedBy), - legacy_backup_written: false, - no_conflicts: false, - final_count_matches_expected: false - }; - const warnings = []; - if (!legacyBefore.exists || !checks3.legacy_store_exists) { + async runPrompt(options) { + if (this.isApiMode()) { + const items = await this.fetchCloudItems(); + return runKnowledgePromptOverItems(items, { ...options, config: this.config() }); + } + const workspace = this.ensureWorkspace(); + const legacyStorePath = options.legacyStorePath ?? workspace.jsonStorePath; + if (!options.legacyStorePath) + ensureStore(legacyStorePath); + return runKnowledgePrompt({ + ...options, + dbPath: workspace.knowledgeDbPath, + legacyStorePath, + config: this.config() + }); + } + async webSearch(options) { + const workspace = this.ensureWorkspace(); + return runProviderWebSearch({ + ...options, + dbPath: workspace.knowledgeDbPath, + config: this.config(), + safetyPolicy: this.safetyPolicy() + }); + } + async machineTopology(options = {}) { + const workspace = this.workspace; + return discoverKnowledgeMachineTopology({ + ...options, + knowledge: { + scope: this.scope, + workspace_home: workspace.home + } + }); + } + async machinePreflight(options = {}) { + const workspace = this.workspace; + return preflightKnowledgeMachine({ + ...options, + knowledge: { + scope: this.scope, + workspace_home: workspace.home + } + }); + } + syncStatus() { + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) { + return emptySyncStatus({ + scope: this.scope, + workspaceHome: workspace.home + }); + } + return getKnowledgeSyncStatus({ + dbPath: workspace.knowledgeDbPath, + scope: this.scope, + workspaceHome: workspace.home + }); + } + async syncDoctor(options = {}) { + const workspace = this.ensureWorkspace(); + migrateKnowledgeDb(workspace.knowledgeDbPath); + const status = this.syncStatus(); + const storage = this.storageContract(); + const validation = this.validateStorage(); + const artifactManifest = artifactManifestStatus(workspace.knowledgeDbPath, storage); + const machine = options.machine?.trim() || null; + const peerWorkspace = options.peerWorkspace?.trim() || null; + const warnings = []; + let resolvedRoute = null; + let resolvedWorkspace = null; + if (machine && !serviceMachineIsLocal(machine)) { + const route = await resolveKnowledgeMachineRoute({ + machineId: machine, + includeTailscale: options.includeTailscale + }); + resolvedRoute = routeSummary(route); + warnings.push(...route.warnings); + } + if (machine || peerWorkspace) { + const workspaceResolution = await resolveKnowledgeMachineWorkspace({ + machineId: machine ?? workspaceMachineId(workspace), + peerWorkspace, + includeTailscale: options.includeTailscale + }); + if (machine && !peerWorkspace && (resolvedRoute?.source === "raw" || !workspaceResolution.ok || !workspaceResolution.project_root)) { + const registryRow = findRegistryMachine(workspace.knowledgeDbPath, machine); + if (registryRow) { + if (resolvedRoute?.source === "raw" && registryRow.ssh_target) { + resolvedRoute = routeSummary(routeFromRegistry(registryRow, machine, { + target: resolvedRoute.target, + route: resolvedRoute.route, + targetKind: resolvedRoute.target_kind, + confidence: resolvedRoute.confidence, + source: resolvedRoute.source, + adapter: resolvedRoute.adapter, + evidence: resolvedRoute.evidence, + cacheability: resolvedRoute.cacheability, + warnings: [] + })); + } + if (!workspaceResolution.ok || !workspaceResolution.project_root) { + const registryWorkspace = workspaceFromRegistry(registryRow, machine, workspaceResolution); + if (registryWorkspace) { + resolvedWorkspace = workspaceSummary(registryWorkspace, registryWorkspace.project_root); + warnings.push(...registryWorkspace.warnings); + } + } + } + } + resolvedWorkspace = workspaceResolution.ok && workspaceResolution.project_root ? workspaceSummary(workspaceResolution, workspaceResolution.project_root) : resolvedWorkspace ?? { + ...workspaceSummary(workspaceResolution, peerWorkspace ?? ""), + project_root: workspaceResolution.project_root ?? peerWorkspace ?? "" + }; + warnings.push(...workspaceResolution.warnings); + } + if (!validation.ok) + warnings.push(...validation.errors.map((error51) => `storage:${error51}`)); + const openFiles = openFilesBoundaryStatus(workspace.knowledgeDbPath, resolvedWorkspace); + if (!openFiles.ok) + warnings.push("open_files_boundary_raw_payload_sentinels"); + if (!artifactManifest.ok) + warnings.push(...artifactManifest.warnings); + const diagnosticFailures = resolvedWorkspace?.diagnostics.filter((entry) => entry.severity === "fail") ?? []; + const ok = validation.ok && artifactManifest.ok && openFiles.ok && diagnosticFailures.length === 0 && (resolvedWorkspace?.project_root !== "" || !resolvedWorkspace); + const recommendedCommands = doctorRecommendations({ + scope: this.scope, + machine, + peerWorkspace, + tables: options.tables, + resolvedWorkspace, + openConflicts: status.conflicts.open + }); return { - ok: true, - dry_run: dryRun, - approval_required: false, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: null, - legacy_before: legacyBefore, - current_before: currentBefore, - backup_after: null, - current_after: currentBefore, - merge: { - current_items: readMergeStore(options.current.jsonStorePath).items.length, - legacy_items: 0, - duplicate_ids_identical: 0, - duplicate_ids_conflicting: 0, - short_id_conflicts: 0, - stranded_items: 0, - merged_items: 0, - expected_total_items: readMergeStore(options.current.jsonStorePath).items.length, - final_items: currentBefore.json_items + ok, + read_only: true, + generated_at: new Date().toISOString(), + scope: this.scope, + workspace_home: workspace.home, + database: { + sqlite_schema_version: status.sqlite_schema_version, + table_counts: status.table_counts }, - conflicts: [], - checks: { - ...checks3, - no_conflicts: true, - final_count_matches_expected: true + storage: { + contract: storage, + validation, + artifact_manifest: artifactManifest }, - warnings, - message: `No legacy knowledge JSON store found at ${options.legacy.jsonStorePath}` - }; - } - const currentStore = readMergeStore(options.current.jsonStorePath); - const legacyStore = readMergeStore(options.legacy.jsonStorePath); - const planned = mergeStats(currentStore, legacyStore); - checks3.no_conflicts = planned.conflicts.length === 0; - if (planned.conflicts.length > 0) - warnings.push("merge_conflicts_detected"); - if (!checks3.approval_present) - warnings.push("write_approval_required"); - if (dryRun || !checks3.approval_present || planned.conflicts.length > 0) { - return { - ok: planned.conflicts.length === 0, - dry_run: true, - approval_required: !checks3.approval_present, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: `${options.legacy.home}.merge-backup-${migrationTimestamp(now)}`, - legacy_before: legacyBefore, - current_before: currentBefore, - backup_after: null, - current_after: null, - merge: planned.stats, - conflicts: planned.conflicts, - checks: checks3, - warnings, - message: planned.conflicts.length === 0 ? `Dry run: would merge ${planned.stats.stranded_items} legacy item(s) into ${options.current.jsonStorePath}` : `Refusing legacy merge with ${planned.conflicts.length} conflict(s)` + sync: { + machines: status.machines.total, + snapshots: status.snapshots.total, + clocks: status.clocks.total, + imports: status.imports.total, + open_conflicts: status.conflicts.open, + table_clocks: status.clocks.rows + }, + open_files: openFiles, + resolved_route: resolvedRoute, + resolved_workspace: resolvedWorkspace, + recommended_commands: recommendedCommands, + warnings: [...new Set(warnings)], + message: ok ? `Sync readiness ok: ${status.clocks.total} table clock(s), ${status.conflicts.open} open conflict(s)` : `Sync readiness needs attention: ${[...new Set(warnings)].join(", ") || "workspace diagnostics failed"}` }; } - return withStoreLocks([options.current.jsonStorePath, options.legacy.jsonStorePath], () => { - const lockedCurrentStore = readMergeStore(options.current.jsonStorePath); - const lockedLegacyStore = readMergeStore(options.legacy.jsonStorePath); - const lockedPlan = mergeStats(lockedCurrentStore, lockedLegacyStore); - checks3.no_conflicts = lockedPlan.conflicts.length === 0; - if (lockedPlan.conflicts.length > 0) { + repairArtifactManifestKeys(options = {}) { + const workspace = this.ensureWorkspace(); + migrateKnowledgeDb(workspace.knowledgeDbPath); + const storage = this.storageContract(); + const storagePrefix = storagePrefixKey(storage); + const candidates = artifactManifestKeyRepairCandidates(workspace.knowledgeDbPath, storage); + const dryRun = options.dryRun === true || options.approveWrite !== true; + if (candidates.length === 0) { return { - ok: false, - dry_run: true, + ok: true, + dry_run: dryRun, approval_required: false, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: null, - legacy_before: summarizeWorkspaceTree(options.legacy), - current_before: summarizeWorkspaceTree(options.current), - backup_after: null, - current_after: null, - merge: lockedPlan.stats, - conflicts: lockedPlan.conflicts, - checks: checks3, - warnings: [...warnings, "merge_conflicts_detected_after_lock"], - message: `Refusing legacy merge with ${lockedPlan.conflicts.length} conflict(s)` + storage_type: storage.storage_type, + storage_prefix: storagePrefix, + candidates, + repaired: 0, + audit_event_id: null, + message: "No legacy S3 artifact manifest keys found" }; } - if (lockedPlan.stats.stranded_items === 0) { - lockedPlan.stats.final_items = lockedCurrentStore.items.length; - checks3.final_count_matches_expected = lockedCurrentStore.items.length === lockedPlan.stats.expected_total_items; + if (options.dryRun === true) { return { - ok: checks3.no_conflicts && checks3.final_count_matches_expected, - dry_run: false, + ok: true, + dry_run: true, approval_required: false, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: null, - legacy_before: summarizeWorkspaceTree(options.legacy), - current_before: summarizeWorkspaceTree(options.current), - backup_after: null, - current_after: summarizeWorkspaceTree(options.current), - merge: lockedPlan.stats, - conflicts: [], - checks: checks3, - warnings, - message: `Legacy merge already up to date for ${options.current.jsonStorePath}` + storage_type: storage.storage_type, + storage_prefix: storagePrefix, + candidates, + repaired: 0, + audit_event_id: null, + message: `Would repair ${candidates.length} legacy S3 artifact manifest key(s)` }; } - const backupHome = `${options.legacy.home}.merge-backup-${migrationTimestamp(now)}`; - mkdirSync4(dirname5(backupHome), { recursive: true }); - cpSync(options.legacy.home, backupHome, { - recursive: true, - force: false, - errorOnExist: true, - preserveTimestamps: true - }); - const backupWorkspace = workspaceForHome(backupHome); - const backupAfter = summarizeWorkspaceTree(backupWorkspace); - checks3.legacy_backup_written = summariesMatch(summarizeWorkspaceTree(options.legacy), backupAfter); - if (!checks3.legacy_backup_written) { - throw new Error(`Legacy knowledge merge backup verification failed: ${backupHome}`); - } - saveStore(options.current.jsonStorePath, lockedPlan.mergedStore); - const finalStore = readMergeStore(options.current.jsonStorePath); - lockedPlan.stats.final_items = finalStore.items.length; - checks3.final_count_matches_expected = finalStore.items.length === lockedPlan.stats.expected_total_items; - const currentAfter = summarizeWorkspaceTree(options.current); - const ok = checks3.legacy_backup_written && checks3.no_conflicts && checks3.final_count_matches_expected; - return { - ok, - dry_run: false, - approval_required: false, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: backupHome, - legacy_before: legacyBefore, - current_before: currentBefore, - backup_after: backupAfter, - current_after: currentAfter, - merge: lockedPlan.stats, - conflicts: [], - checks: checks3, - warnings, - message: ok ? `Merged ${lockedPlan.stats.merged_items} legacy item(s) into ${options.current.jsonStorePath}` : `Merged legacy knowledge store, but verification failed for ${options.current.jsonStorePath}` - }; - }); -} -function sleepSync2(milliseconds) { - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); -} -function isRetriableFsLock(error51) { - return error51 instanceof Error && /\b(EBUSY|EPERM)\b/.test(error51.message); -} -function removeWorkspaceWithRetries(path) { - let lastError; - for (let attempt = 0;attempt < 8; attempt += 1) { - try { - rmSync(path, { recursive: true, force: false }); - return; - } catch (error51) { - lastError = error51; - if (!isRetriableFsLock(error51)) - throw error51; - sleepSync2(50 * (attempt + 1)); + if (options.approveWrite !== true || !options.approvedBy) { + return { + ok: false, + dry_run: true, + approval_required: true, + storage_type: storage.storage_type, + storage_prefix: storagePrefix, + candidates, + repaired: 0, + audit_event_id: null, + message: "Artifact key repair requires --approve-write and --approved-by <name>" + }; } - } - throw lastError; -} -function chmodOwnerOnlyTree(path) { - if (!existsSync13(path)) - return; - const stat = lstatSync3(path); - chmodSync4(path, stat.isDirectory() ? 448 : 384); - if (!stat.isDirectory()) - return; - for (const entry of readdirSync3(path)) - chmodOwnerOnlyTree(join7(path, entry)); -} -function isRetainedTombstoneFile(file2) { - return file2 === "TOMBSTONE.md" || file2 === "migration.json" || file2 === "knowledge.db" || file2 === "knowledge.db-shm" || file2 === "knowledge.db-wal" || file2 === "knowledge.db-journal"; -} -function prepareLegacyTombstoneDirectory(home) { - for (const file2 of readdirSync3(home)) { - if (file2 === "TOMBSTONE.md" || file2 === "migration.json") - continue; + const db = openKnowledgeDb(workspace.knowledgeDbPath); try { - rmSync(join7(home, file2), { recursive: true, force: false }); - } catch (error51) { - if (!isRetriableFsLock(error51) || !file2.startsWith("knowledge.db")) - throw error51; + const now = new Date().toISOString(); + const update = db.transaction((entries) => { + const statement = db.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"); + const currentRows = db.query("SELECT id, metadata_json FROM storage_objects").all(); + const metadataById = new Map(currentRows.map((row) => [row.id, parseMetadataJson(row.metadata_json)])); + for (const entry of entries) { + const metadata = metadataById.get(entry.id) ?? {}; + metadata.key = entry.repaired_key; + statement.run(JSON.stringify(metadata), now, entry.id); + } + }); + update(candidates); + const auditEventId = recordAuditEvent(db, { + event_type: "artifact_manifest_key_repair", + action: "storage.artifact_manifest.repair_keys", + target_uri: `knowledge-storage://${workspace.home}/storage_objects`, + decision: "allow", + metadata: { + approved_by: options.approvedBy, + repaired: candidates.length, + storage_type: storage.storage_type, + storage_prefix: storagePrefix, + artifact_uris: candidates.map((entry) => entry.artifact_uri) + } + }); + return { + ok: true, + dry_run: false, + approval_required: false, + storage_type: storage.storage_type, + storage_prefix: storagePrefix, + candidates, + repaired: candidates.length, + audit_event_id: auditEventId, + message: `Repaired ${candidates.length} legacy S3 artifact manifest key(s)` + }; + } finally { + db.close(); } } -} -function moveWorkspace(sourceHome, targetHome) { - try { - renameSync2(sourceHome, targetHome); - return; - } catch (error51) { - cpSync(sourceHome, targetHome, { - recursive: true, - force: false, - errorOnExist: true, - preserveTimestamps: true + async createSyncSnapshot(options = {}) { + const workspace = this.ensureWorkspace(); + const topology = await this.machineTopology({ + includeTailscale: options.includeTailscale !== false + }); + return createKnowledgeSyncSnapshot({ + dbPath: workspace.knowledgeDbPath, + scope: this.scope, + workspaceHome: workspace.home, + storage: this.storageContract(), + topology, + machineId: options.machineId }); - try { - removeWorkspaceWithRetries(sourceHome); - } catch (removeError) { - if (isRetriableFsLock(removeError)) { - prepareLegacyTombstoneDirectory(sourceHome); - return; - } - rmSync(targetHome, { recursive: true, force: true }); - throw removeError; - } - if (error51 instanceof Error && error51.message.includes("EXDEV")) - return; - } -} -function isMigrationTombstone(workspace, summary, currentHome) { - if (!summary.exists) - return false; - if (!summary.files.includes("TOMBSTONE.md") || !summary.files.includes("migration.json")) - return false; - if (summary.files.some((file2) => !isRetainedTombstoneFile(file2))) - return false; - try { - const metadata = JSON.parse(readFileSync13(join7(workspace.home, "migration.json"), "utf8")); - return metadata.new_path === currentHome && typeof metadata.backup_path === "string"; - } catch { - return false; - } -} -function migrateLegacyKnowledgeWorkspace(options) { - const now = options.now ?? new Date; - const dryRun = options.approveWrite !== true; - const currentBefore = summarizeWorkspaceTree(options.current); - const currentIsDefaultScaffold = isDefaultScaffold(options.current, currentBefore); - const willMutateLegacy = options.approveWrite === true && Boolean(options.approvedBy) && (!currentBefore.exists || currentIsDefaultScaffold); - const legacyBefore = summarizeWorkspaceTree(options.legacy, { includeSqlite: !willMutateLegacy }); - const checks3 = { - legacy_exists: legacyBefore.exists, - current_absent_or_default_scaffold: !currentBefore.exists || currentIsDefaultScaffold, - approval_present: options.approveWrite === true && Boolean(options.approvedBy), - legacy_is_tombstone: false, - backup_matches_legacy: false, - migrated_matches_backup: false, - tombstone_written: false - }; - const warnings = []; - if (!legacyBefore.exists) { - return { - ok: true, - dry_run: dryRun, - approval_required: false, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: null, - tombstone_path: null, - legacy_before: legacyBefore, - current_before: currentBefore, - backup_after: null, - current_after: null, - checks: checks3, - warnings, - message: `No legacy knowledge workspace found at ${options.legacy.home}` - }; - } - checks3.legacy_is_tombstone = isMigrationTombstone(options.legacy, legacyBefore, options.current.home); - if (checks3.legacy_is_tombstone) { - return { - ok: true, - dry_run: dryRun, - approval_required: false, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: null, - tombstone_path: join7(options.legacy.home, "TOMBSTONE.md"), - legacy_before: legacyBefore, - current_before: currentBefore, - backup_after: null, - current_after: currentBefore, - checks: { - ...checks3, - tombstone_written: true - }, - warnings, - message: `Legacy knowledge workspace already migrated to ${options.current.home}` - }; - } - if (!checks3.current_absent_or_default_scaffold) { - warnings.push("current_workspace_contains_data"); - } - if (!checks3.approval_present) { - warnings.push("write_approval_required"); - } - if (dryRun || !checks3.current_absent_or_default_scaffold || !checks3.approval_present) { - return { - ok: checks3.current_absent_or_default_scaffold, - dry_run: true, - approval_required: true, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: `${options.legacy.home}.backup-${migrationTimestamp(now)}`, - tombstone_path: join7(options.legacy.home, "TOMBSTONE.md"), - legacy_before: legacyBefore, - current_before: currentBefore, - backup_after: null, - current_after: null, - checks: checks3, - warnings, - message: checks3.current_absent_or_default_scaffold ? `Dry run: would migrate ${options.legacy.home} to ${options.current.home}` : `Cannot migrate while ${options.current.home} contains data` - }; - } - const backupHome = `${options.legacy.home}.backup-${migrationTimestamp(now)}`; - mkdirSync4(dirname5(options.current.home), { recursive: true }); - mkdirSync4(dirname5(backupHome), { recursive: true }); - cpSync(options.legacy.home, backupHome, { - recursive: true, - force: false, - errorOnExist: true, - preserveTimestamps: true - }); - chmodOwnerOnlyTree(backupHome); - const backupWorkspace = workspaceForHome(backupHome); - const backupSnapshot = summarizeWorkspaceTree(backupWorkspace, { includeSqlite: false }); - checks3.backup_matches_legacy = summariesMatch(legacyBefore, backupSnapshot); - if (!checks3.backup_matches_legacy) { - throw new Error(`Legacy knowledge backup verification failed: ${backupHome}`); - } - if (currentBefore.exists && currentIsDefaultScaffold) { - rmSync(options.current.home, { recursive: true, force: true }); - } - moveWorkspace(options.legacy.home, options.current.home); - const currentSnapshot = summarizeWorkspaceTree(options.current, { includeSqlite: false }); - checks3.migrated_matches_backup = summariesMatch(backupSnapshot, currentSnapshot); - const backupAfter = summarizeWorkspaceTree(backupWorkspace); - const currentAfter = summarizeWorkspaceTree(options.current); - const legacyBeforeOutput = { ...backupAfter, path: options.legacy.home }; - mkdirSync4(options.legacy.home, { recursive: true }); - const tombstonePath = join7(options.legacy.home, "TOMBSTONE.md"); - writeFileSync5(tombstonePath, [ - "# Migrated OpenKnowledge Workspace", - "", - `Migrated at: ${now.toISOString()}`, - `Approved by: ${options.approvedBy}`, - `New path: ${options.current.home}`, - `Backup path: ${backupHome}`, - "", - "This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.", - "" - ].join(` -`), { mode: 384 }); - chmodSync4(tombstonePath, 384); - const migrationJsonPath = join7(options.legacy.home, "migration.json"); - writeFileSync5(migrationJsonPath, `${JSON.stringify({ - migrated_at: now.toISOString(), - approved_by: options.approvedBy, - new_path: options.current.home, - backup_path: backupHome, - legacy_before: legacyBeforeOutput, - backup_after: backupAfter, - current_after: currentAfter - }, null, 2)} -`, { mode: 384 }); - chmodSync4(migrationJsonPath, 384); - checks3.tombstone_written = existsSync13(tombstonePath); - const ok = checks3.backup_matches_legacy && checks3.migrated_matches_backup && checks3.tombstone_written; - return { - ok, - dry_run: false, - approval_required: false, - scope: options.scope, - current_home: options.current.home, - legacy_home: options.legacy.home, - backup_home: backupHome, - tombstone_path: tombstonePath, - legacy_before: legacyBeforeOutput, - current_before: currentBefore, - backup_after: backupAfter, - current_after: currentAfter, - checks: checks3, - warnings, - message: ok ? `Migrated legacy knowledge workspace to ${options.current.home}` : `Migrated legacy knowledge workspace, but verification failed for ${options.current.home}` - }; -} - -// src/service.ts -function resolvePeerWorkspace(input) { - const target = resolve5(input); - if (existsSync14(join8(target, "knowledge.db")) || existsSync14(join8(target, "config.json"))) { - return ensureKnowledgeWorkspace(target); } - return ensureKnowledgeWorkspace(workspaceForHome(projectKnowledgeHome(target)).home); -} -function workspaceMachineId(workspace) { - return `${hostname5()}:${createHash21("sha256").update(workspace.home).digest("hex").slice(0, 12)}`; -} -function shellQuote2(value) { - return `'${value.replace(/'/g, "'\\''")}'`; -} -function knowledgeCliCommand(args) { - return ["knowledge", ...args].map(shellQuote2).join(" "); -} -function remoteKnowledgeCommand(peerWorkspace, args) { - return `cd ${shellQuote2(peerWorkspace)} && knowledge ${args.map(shellQuote2).join(" ")}`; -} -function serviceMachineIsLocal(machine) { - return !machine || machine === "local" || machine === "localhost"; -} -function workspaceSummary(resolvedWorkspace, projectRoot) { - return { - source: resolvedWorkspace.source, - adapter: resolvedWorkspace.adapter, - project_root: projectRoot, - project_root_source: resolvedWorkspace.project_root_source, - workspace_root: resolvedWorkspace.workspace_root, - workspace_root_source: resolvedWorkspace.workspace_root_source, - open_files_root: resolvedWorkspace.open_files_root, - open_files_root_source: resolvedWorkspace.open_files_root_source, - trust_status: resolvedWorkspace.trust_status, - auth_status: resolvedWorkspace.auth_status, - current: resolvedWorkspace.current, - primary: resolvedWorkspace.primary, - diagnostics: resolvedWorkspace.diagnostics, - repair_hints: resolvedWorkspace.repair_hints, - evidence: resolvedWorkspace.evidence, - cacheability: resolvedWorkspace.cacheability, - warnings: resolvedWorkspace.warnings - }; -} -function routeSummary(resolvedMachine) { - return { - source: resolvedMachine.source, - adapter: resolvedMachine.adapter, - target: resolvedMachine.target, - route: resolvedMachine.route, - target_kind: resolvedMachine.targetKind, - confidence: resolvedMachine.confidence, - evidence: resolvedMachine.evidence, - cacheability: resolvedMachine.cacheability - }; -} -function parseJsonStringArray(value) { - try { - const parsed = JSON.parse(value); - return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === "string") : []; - } catch { - return []; + syncConflicts(options = {}) { + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) + return []; + return listKnowledgeSyncConflicts(workspace.knowledgeDbPath, options); } -} -function recordValue(value) { - return value && typeof value === "object" && !Array.isArray(value) ? value : {}; -} -function stringValue(value) { - return typeof value === "string" && value.length > 0 ? value : null; -} -function numberValue(value) { - return typeof value === "number" && Number.isFinite(value) ? value : null; -} -function booleanValue(value) { - return typeof value === "boolean" ? value : null; -} -function stringArrayValue(value) { - return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : []; -} -function registryCacheability(value, resolver, prefix) { - const raw = recordValue(value); - const observedAt = stringValue(raw.observed_at) ?? stringValue(resolver[`${prefix}_observed_at`]); - const sourceAuthority = stringValue(raw.source_authority) ?? stringValue(resolver[`${prefix}_source_authority`]); - if (!observedAt || !sourceAuthority) - return null; - return { - observed_at: observedAt, - verified_at: stringValue(raw.verified_at), - expires_at: stringValue(raw.expires_at) ?? stringValue(resolver[`${prefix}_expires_at`]), - ttl_ms: numberValue(raw.ttl_ms), - source_authority: sourceAuthority, - confidence: stringValue(raw.confidence) ?? (prefix === "route" ? stringValue(resolver.route_confidence) : null), - cacheable: booleanValue(raw.cacheable) ?? booleanValue(resolver[`${prefix}_cacheable`]) ?? false, - stale: booleanValue(raw.stale) ?? booleanValue(resolver[`${prefix}_stale`]) ?? false, - reasons: stringArrayValue(raw.reasons) - }; -} -function registryMachineMatches(row, machine) { - return row.machine_id === machine || row.hostname === machine || row.ssh_target === machine || row.tailscale_dns === machine || parseJsonStringArray(row.tailscale_ips_json).includes(machine); -} -function findRegistryMachine(dbPath, machine) { - return listKnowledgeMachines(dbPath).find((row) => registryMachineMatches(row, machine)) ?? null; -} -function registryResolverEvidence(row) { - return recordValue(parseMetadataJson(row.metadata_json).resolver_evidence); -} -function registryResolverCapabilities(row) { - return recordValue(parseMetadataJson(row.capabilities_json).resolver); -} -function registryRouteKind(row) { - const resolver = registryResolverCapabilities(row); - const kind = stringValue(resolver.route_kind); - if (kind === "local" || kind === "lan" || kind === "tailscale" || kind === "ssh" || kind === "unknown") - return kind; - if (row.tailscale_dns && row.ssh_target === row.tailscale_dns) - return "tailscale"; - return row.ssh_target ? "ssh" : "unknown"; -} -function registryRouteTargetKind(row) { - const resolver = registryResolverCapabilities(row); - const kind = stringValue(resolver.route_target_kind); - if (kind === "local" || kind === "lan" || kind === "tailscale" || kind === "ssh" || kind === "unknown") - return kind; - return registryRouteKind(row); -} -function registryRouteConfidence(row) { - return stringValue(registryResolverCapabilities(row).route_confidence) ?? "medium"; -} -function routeFromRegistry(row, machine, fallback) { - const evidence = registryResolverEvidence(row); - const routeEvidence = recordValue(evidence.route); - const resolver = registryResolverCapabilities(row); - return { - target: row.ssh_target ?? row.tailscale_dns ?? row.hostname ?? row.machine_id, - route: registryRouteKind(row), - targetKind: registryRouteTargetKind(row), - confidence: registryRouteConfidence(row), - source: "registry", - adapter: fallback.adapter, - evidence: { - registry: true, - requested_machine_id: machine, - machine_id: row.machine_id, - recorded_at: row.updated_at, - route: routeEvidence - }, - cacheability: registryCacheability(routeEvidence.cacheability, resolver, "route") ?? fallback.cacheability, - warnings: [...new Set([...fallback.warnings, "registry_route_fallback"])] - }; -} -function workspaceFromRegistry(row, machine, fallback) { - if (!row.workspace_home) - return null; - const evidence = registryResolverEvidence(row); - const workspaceEvidence = recordValue(evidence.workspace); - const resolver = registryResolverCapabilities(row); - return { - ok: true, - source: "registry", - adapter: fallback.adapter, - requested_machine_id: machine, - machine_id: row.machine_id, - project_id: stringValue(workspaceEvidence.project_id) ?? fallback.project_id, - repo_name: stringValue(workspaceEvidence.repo_name) ?? fallback.repo_name, - project_root: row.workspace_home, - project_root_source: stringValue(resolver.project_root_source) ?? "registry", - workspace_root: stringValue(workspaceEvidence.workspace_root), - workspace_root_source: stringValue(resolver.workspace_root_source) ?? "registry", - open_files_root: stringValue(workspaceEvidence.open_files_root), - open_files_root_source: stringValue(resolver.open_files_root_source) ?? "registry", - trust_status: stringValue(resolver.trust_status) ?? "unknown", - auth_status: stringValue(resolver.auth_status) ?? "unknown", - current: false, - primary: false, - diagnostics: [], - repair_hints: [], - evidence: { - registry: true, - requested_machine_id: machine, - machine_id: row.machine_id, - recorded_at: row.updated_at, - workspace: workspaceEvidence - }, - cacheability: registryCacheability(workspaceEvidence.cacheability, resolver, "workspace") ?? fallback.cacheability, - warnings: [...new Set([...fallback.warnings, "registry_workspace_fallback"])] - }; -} -function workspaceReadinessMessage(resolvedWorkspace) { - if (!resolvedWorkspace) - return null; - const nonOkDiagnostics = resolvedWorkspace.diagnostics.filter((entry) => entry.severity !== "ok"); - const firstRepair = resolvedWorkspace.repair_hints[0]; - if (!nonOkDiagnostics.length && !resolvedWorkspace.warnings.length && !firstRepair) - return null; - return [ - nonOkDiagnostics.length ? `workspace diagnostics: ${nonOkDiagnostics.map((entry) => `${entry.id}=${entry.status}`).join(", ")}` : null, - resolvedWorkspace.warnings.length ? `warnings: ${resolvedWorkspace.warnings.join(", ")}` : null, - firstRepair ? `repair: ${firstRepair.shell_command}` : null - ].filter(Boolean).join("; "); -} -function syncCommand(input) { - return { - id: input.id, - reason: input.reason, - command: ["knowledge", ...input.args], - shell_command: knowledgeCliCommand(input.args) - }; -} -function countQuery(dbPath, sql) { - const db = openKnowledgeDb(dbPath); - try { - return Number(db.query(sql).get()?.count ?? 0); - } finally { - db.close(); + syncConflict(id) { + const workspace = this.ensureWorkspace(); + const conflict = getKnowledgeSyncConflict(workspace.knowledgeDbPath, id); + if (!conflict) + throw new Error(`Sync conflict not found: ${id}`); + return conflict; } -} -function openFilesBoundaryStatus(dbPath, resolvedWorkspace) { - const openFilesRefs = countQuery(dbPath, "SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"); - const metadataMentions = countQuery(dbPath, "SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"); - const extractedTextArtifacts = countQuery(dbPath, "SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"); - const rawPayloadSentinelHits = countQuery(dbPath, [ - "SELECT COUNT(*) AS count FROM sources", - "WHERE metadata_json LIKE '%raw_bytes%'", - "OR metadata_json LIKE '%raw_content%'", - "OR metadata_json LIKE '%content_base64%'", - "OR metadata_json LIKE '%source_bytes%'" - ].join(" ")); - const ok = rawPayloadSentinelHits === 0; - return { - ok, - source_of_truth: "open-files", - configured_root: resolvedWorkspace?.open_files_root ?? null, - configured_root_source: resolvedWorkspace?.open_files_root_source ?? null, - source_refs: { - open_files: openFilesRefs, - metadata_mentions: metadataMentions - }, - extracted_text_artifacts: extractedTextArtifacts, - raw_source_bytes_owned_by: "open-files", - raw_payload_sentinel_hits: rawPayloadSentinelHits, - message: ok ? `${openFilesRefs} open-files source ref(s); raw source bytes remain owned by open-files` : `${rawPayloadSentinelHits} raw source payload metadata sentinel(s) found` - }; -} -var RAW_ARTIFACT_PAYLOAD_METADATA_KEYS = new Set([ - "raw", - "raw_bytes", - "raw_content", - "content_base64", - "source_bytes", - "source_content", - "body", - "body_bytes" -]); -function metadataHasRawPayloadSentinel(value, depth = 0) { - if (depth > 8) - return false; - if (!value || typeof value !== "object") - return false; - if (Array.isArray(value)) - return value.some((entry) => metadataHasRawPayloadSentinel(entry, depth + 1)); - for (const [key, entry] of Object.entries(value)) { - if (RAW_ARTIFACT_PAYLOAD_METADATA_KEYS.has(key.toLowerCase())) - return true; - if (metadataHasRawPayloadSentinel(entry, depth + 1)) - return true; + proposeSyncConflictResolution(id) { + const workspace = this.ensureWorkspace(); + return proposeKnowledgeSyncConflictResolution(workspace.knowledgeDbPath, id); } - return false; -} -function parseMetadataJson(value) { - try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; + async proposeSyncConflictResolutionWithAi(options) { + const workspace = this.ensureWorkspace(); + return proposeKnowledgeSyncConflictResolutionWithAi({ + dbPath: workspace.knowledgeDbPath, + id: options.id, + config: this.config(), + modelRef: options.modelRef, + fake: options.fake, + env: options.env + }); } -} -function inventoryLimit(value, fallback = 20, max = 200) { - if (!Number.isFinite(value) || value <= 0) - return fallback; - return Math.min(Math.floor(value), max); -} -function previewText(value, max = 220) { - const text = value ?? ""; - return text.length > max ? `${text.slice(0, max)}...` : text; -} -function rowsWithJsonFields(rows, fields = ["metadata_json"]) { - return rows.map((row) => { - const next = { ...row }; - for (const field of fields) { - const raw = next[field]; - if (typeof raw === "string") { - const parsedField = field.endsWith("_json") ? field.slice(0, -5) : field; - next[parsedField] = parseMetadataJson(raw); - delete next[field]; - } + resolveSyncConflict(options) { + const workspace = this.ensureWorkspace(); + const proposal = proposeKnowledgeSyncConflictResolution(workspace.knowledgeDbPath, options.id); + if (options.approveWrite !== true || !options.approvedBy) { + return { + ok: false, + approval_required: true, + conflict: proposal.conflict, + proposal, + message: "Sync conflict resolution requires --approve-write and --approved-by <name>" + }; + } + const conflict = resolveKnowledgeSyncConflict(workspace.knowledgeDbPath, { + id: options.id, + strategy: options.strategy ?? proposal.proposed_strategy, + approvedBy: options.approvedBy, + proposedPatchUri: options.proposedPatchUri + }); + const db = openKnowledgeDb(workspace.knowledgeDbPath); + try { + const auditEventId = recordAuditEvent(db, { + event_type: "sync_conflict_resolution", + action: "sync.conflict.resolve", + target_uri: `knowledge-sync-conflict://${options.id}`, + decision: "allow", + metadata: { + conflict_id: options.id, + entity_kind: conflict.entity_kind, + entity_id: conflict.entity_id, + strategy: conflict.resolution_strategy, + approved_by: conflict.approved_by, + proposed_patch_uri: conflict.proposed_patch_uri + } + }); + return { + ok: true, + approval_required: false, + conflict, + audit_event_id: auditEventId, + message: `Resolved sync conflict ${options.id}` + }; + } finally { + db.close(); } - return next; - }); -} -function parseInventoryJsonArray(value) { - if (typeof value !== "string") - return []; - try { - const parsed = JSON.parse(value); - return Array.isArray(parsed) ? parsed : []; - } catch { - return []; } -} -function parseInventoryJsonObject(value) { - if (typeof value !== "string") - return {}; - return parseMetadataJson(value); -} -function promotionCandidateInventoryRow(row) { - const next = { ...row }; - next.source_refs = parseInventoryJsonArray(next.source_refs_json); - next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); - next.requires_approval = next.requires_approval === 1 || next.requires_approval === true; - next.checks = parseInventoryJsonObject(next.checks_json); - next.metadata = parseInventoryJsonObject(next.metadata_json); - delete next.source_refs_json; - delete next.evidence_refs_json; - delete next.checks_json; - delete next.metadata_json; - return next; -} -function durableRecordInventoryRow(row) { - const next = { ...row }; - next.source_refs = parseInventoryJsonArray(next.source_refs_json); - next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); - next.metadata = parseInventoryJsonObject(next.metadata_json); - delete next.source_refs_json; - delete next.evidence_refs_json; - delete next.metadata_json; - return next; -} -function selectInventoryRows(db, sql, params = []) { - return db.query(sql).all(...params); -} -function readLegacyInventoryStore(path) { - if (!existsSync14(path)) - return { exists: false, read_error: null, items: [] }; - try { - const parsed = JSON.parse(readFileSync14(path, "utf8")); - if (!parsed || !Array.isArray(parsed.items)) { - return { exists: true, read_error: "invalid_store_shape", items: [] }; + syncMachines() { + const workspace = this.workspace; + if (!existsSync14(workspace.knowledgeDbPath)) + return []; + return listKnowledgeMachines(workspace.knowledgeDbPath); + } + exportSyncBundle(options = {}) { + const workspace = this.ensureWorkspace(); + this.assertStorageValid("sync export"); + migrateKnowledgeDb(workspace.knowledgeDbPath); + return createKnowledgeSyncBundle({ + dbPath: workspace.knowledgeDbPath, + scope: this.scope, + workspaceHome: workspace.home, + storage: this.storageContract(), + machineId: options.machineId ?? null, + tables: options.tables, + includeArtifactContent: options.includeArtifactContent, + recordClocks: options.recordClocks !== false + }); + } + async importSyncBundle(options) { + const workspace = this.ensureWorkspace(); + this.assertStorageValid("sync import"); + migrateKnowledgeDb(workspace.knowledgeDbPath); + return applyKnowledgeSyncBundle({ + targetDbPath: workspace.knowledgeDbPath, + targetScope: this.scope, + targetWorkspaceHome: workspace.home, + targetStorage: this.storageContract(), + targetStore: this.artifactStore(), + bundle: options.bundle, + direction: options.direction ?? "import", + dryRun: options.dryRun, + localMachineId: options.machineId ?? null + }); + } + async syncRemotePeer(options) { + const direction = options.direction ?? "both"; + const dryRun = options.dryRun === true; + const localWorkspace = this.ensureWorkspace(); + migrateKnowledgeDb(localWorkspace.knowledgeDbPath); + const tableArgs = options.tables?.length ? ["--tables", options.tables.join(",")] : []; + const artifactArgs = options.includeArtifactContent === false ? ["--no-artifact-content"] : []; + const scopeArgs = ["--scope", this.scope, "--json"]; + let resolvedMachine = await resolveKnowledgeMachineRoute({ + machineId: options.machine, + includeTailscale: options.includeTailscale + }); + let resolvedWorkspace = await resolveKnowledgeMachineWorkspace({ + machineId: options.machine, + peerWorkspace: options.peerWorkspace, + includeTailscale: options.includeTailscale + }); + if (!options.peerWorkspace && resolvedMachine.source === "raw" || !resolvedWorkspace.ok || !resolvedWorkspace.project_root) { + const registryRow = findRegistryMachine(localWorkspace.knowledgeDbPath, options.machine); + if (registryRow) { + if (!options.peerWorkspace && resolvedMachine.source === "raw" && registryRow.ssh_target) { + resolvedMachine = routeFromRegistry(registryRow, options.machine, resolvedMachine); + } + if (!resolvedWorkspace.ok || !resolvedWorkspace.project_root) { + const registryWorkspace = workspaceFromRegistry(registryRow, options.machine, resolvedWorkspace); + if (registryWorkspace) + resolvedWorkspace = registryWorkspace; + } + } + } + if (!resolvedWorkspace.ok || !resolvedWorkspace.project_root) { + throw new Error([ + `Unable to resolve peer workspace for ${options.machine}.`, + `Pass --peer-workspace <repo-or-knowledge-home> or configure workspace path mapping in machines.`, + resolvedWorkspace.warnings.length ? `Warnings: ${resolvedWorkspace.warnings.join(", ")}` : null + ].filter(Boolean).join(" ")); + } + const peerWorkspace = resolvedWorkspace.project_root; + const result = { + ok: true, + dry_run: dryRun, + direction, + transport: "ssh", + machine: options.machine, + resolved_machine: resolvedMachine.target, + resolved_route: routeSummary(resolvedMachine), + resolved_workspace: workspaceSummary(resolvedWorkspace, resolvedWorkspace.project_root), + peer_workspace: peerWorkspace, + message: "" + }; + let resolverEvidenceRecorded = false; + const recordResolverEvidence = () => { + if (dryRun || resolverEvidenceRecorded) + return; + recordKnowledgeMachineResolverEvidence(localWorkspace.knowledgeDbPath, { + machineId: options.machine, + route: resolvedMachine, + workspace: resolvedWorkspace + }); + resolverEvidenceRecorded = true; + }; + if (direction === "pull" || direction === "both") { + const remoteExport = remoteKnowledgeCommand(peerWorkspace, [ + "sync", + "export", + ...scopeArgs, + ...tableArgs, + ...artifactArgs + ]); + const raw = runSshCommand(options.machine, remoteExport, undefined, resolvedMachine); + const bundle = parseRemoteJson(options.machine, "sync export", raw); + assertRemoteSyncBundle(options.machine, bundle); + result.pull = await this.importSyncBundle({ + bundle, + dryRun, + direction: "pull", + machineId: options.machineId ?? null + }); } - return { exists: true, read_error: null, items: parsed.items }; - } catch (error51) { - return { - exists: true, - read_error: error51 instanceof Error ? error51.message : String(error51), - items: [] + if (direction === "push" || direction === "both") { + recordResolverEvidence(); + const bundle = this.exportSyncBundle({ + machineId: options.machineId ?? null, + tables: options.tables, + includeArtifactContent: options.includeArtifactContent, + recordClocks: !dryRun + }); + const remoteImport = remoteKnowledgeCommand(peerWorkspace, [ + "sync", + "import", + ...scopeArgs, + ...dryRun ? ["--dry-run"] : [] + ]); + const applyResult = parseRemoteJson(options.machine, "sync import", runSshCommand(options.machine, remoteImport, JSON.stringify(bundle), resolvedMachine)); + assertRemoteSyncApplyResult(options.machine, applyResult); + result.push = applyResult; + } + result.ok = (result.pull?.ok ?? true) && (result.push?.ok ?? true); + recordResolverEvidence(); + result.message = [ + workspaceReadinessMessage(result.resolved_workspace), + result.pull ? `pull: ${result.pull.message}` : null, + result.push ? `push: ${result.push.message}` : null + ].filter(Boolean).join("; "); + return result; + } + async syncPeer(options) { + const direction = options.direction ?? "both"; + const localWorkspace = this.ensureWorkspace(); + migrateKnowledgeDb(localWorkspace.knowledgeDbPath); + const peerWorkspaceInput = resolve5(options.peerWorkspace); + const peerWorkspace = resolvePeerWorkspace(peerWorkspaceInput); + migrateKnowledgeDb(peerWorkspace.knowledgeDbPath); + const peerConfig = readKnowledgeConfig(peerWorkspace.configPath); + const peerStorage = resolveStorageContract(peerConfig, peerWorkspace, this.scope); + const peerStore = createArtifactStore(peerConfig, peerWorkspace); + const localMachineId2 = options.machineId ?? workspaceMachineId(localWorkspace); + const peerMachineId = workspaceMachineId(peerWorkspace); + const resolvedWorkspace = await resolveKnowledgeMachineWorkspace({ + machineId: options.machineId ?? peerMachineId, + peerWorkspace: peerWorkspaceInput, + includeTailscale: false + }); + const localBundle = () => createKnowledgeSyncBundle({ + dbPath: localWorkspace.knowledgeDbPath, + scope: this.scope, + workspaceHome: localWorkspace.home, + storage: this.storageContract(), + machineId: localMachineId2, + tables: options.tables, + includeArtifactContent: options.includeArtifactContent, + recordClocks: options.dryRun !== true + }); + const peerBundle = () => createKnowledgeSyncBundle({ + dbPath: peerWorkspace.knowledgeDbPath, + scope: this.scope, + workspaceHome: peerWorkspace.home, + storage: peerStorage, + machineId: peerMachineId, + tables: options.tables, + includeArtifactContent: options.includeArtifactContent, + recordClocks: options.dryRun !== true + }); + const result = { + ok: true, + dry_run: options.dryRun === true, + direction, + resolved_workspace: workspaceSummary(resolvedWorkspace, resolvedWorkspace.project_root ?? peerWorkspaceInput), + message: "" }; + if (direction === "pull" || direction === "both") { + result.pull = await applyKnowledgeSyncBundle({ + targetDbPath: localWorkspace.knowledgeDbPath, + targetScope: this.scope, + targetWorkspaceHome: localWorkspace.home, + targetStorage: this.storageContract(), + targetStore: this.artifactStore(), + bundle: peerBundle(), + targetBundle: localBundle(), + direction: "pull", + dryRun: options.dryRun, + localMachineId: localMachineId2 + }); + } + if (direction === "push" || direction === "both") { + result.push = await applyKnowledgeSyncBundle({ + targetDbPath: peerWorkspace.knowledgeDbPath, + targetScope: this.scope, + targetWorkspaceHome: peerWorkspace.home, + targetStorage: peerStorage, + targetStore: peerStore, + bundle: localBundle(), + targetBundle: peerBundle(), + direction: "push", + dryRun: options.dryRun, + localMachineId: peerMachineId + }); + } + result.ok = (result.pull?.ok ?? true) && (result.push?.ok ?? true); + result.message = [ + workspaceReadinessMessage(result.resolved_workspace), + result.pull ? `pull: ${result.pull.message}` : null, + result.push ? `push: ${result.push.message}` : null + ].filter(Boolean).join("; "); + return result; } } -function legacyInventoryItem(item) { - return { - id: item.id, - short_id: item.short_id ?? null, - title: item.title, - content_preview: previewText(item.content), - url: item.url ?? null, - tags: item.tags ?? [], - metadata: item.metadata ?? {}, - archived: item.archived === true, - created_at: item.created_at, - updated_at: item.updated_at - }; -} -function emptyKnowledgeDbStats() { - return { - schema_version: 0, - sources: 0, - source_revisions: 0, - chunks: 0, - wiki_pages: 0, - citations: 0, - indexes: 0, - runs: 0, - run_events: 0, - redaction_findings: 0, - audit_events: 0, - approval_gates: 0, - storage_objects: 0, - embeddings: 0, - vector_entries: 0, - reindex_queue: 0, - knowledge_machines: 0, - sync_snapshots: 0, - sync_changes: 0, - sync_conflicts: 0, - sync_table_clocks: 0, - sync_imports: 0, - promotion_candidates: 0, - durable_records: 0 - }; +function createKnowledgeService(options = {}) { + return new KnowledgeService(options); } -function emptySearchResult(query2, limit, semantic = false) { + +// src/sdk.ts +function createKnowledgeClient(options = {}) { + const service = createKnowledgeService(options); return { - query: query2, - limit, - offset: 0, - mode: { - keyword: true, - catalog: true, - semantic + unstable_service: service, + paths: () => service.paths(), + setup: (input = {}) => service.setup(input), + auth: { + status: (env = process.env) => service.authStatus(env), + login: (input, env = process.env) => service.saveAuth(input, env), + logout: (env = process.env) => service.clearAuth(env) }, - semantic_provider: null, - semantic_model: null, - semantic_dimensions: null, - counts: { - keyword_results: 0, - catalog_results: 0, - semantic_results: 0, - merged_results: 0 + storage: { + status: () => service.storageContract(), + validate: () => service.validateStorage(), + migrateLegacyPath: (input = {}) => service.migrateLegacyPath(input), + mergeLegacyPath: (input = {}) => service.mergeLegacyPath(input), + artifactStore: () => service.artifactStore() }, - warnings: ["knowledge_db_missing"], - results: [] - }; -} -function normalizeContextQuery(query2) { - return query2.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase(); -} -function emptyContextPack(query2, limit, semantic = false) { - const search = emptySearchResult(query2, limit, semantic); - return { - query: query2, - normalized_query: normalizeContextQuery(query2), - created_at: new Date().toISOString(), - mode: search.mode, - warnings: search.warnings, - search_counts: search.counts, - results: [], - citations: [], - excerpts: [], - graph: { - citations: [], - backlinks: [] + sync: { + status: () => service.syncStatus(), + doctor: (input = {}) => service.syncDoctor(input), + snapshot: (input = {}) => service.createSyncSnapshot(input), + conflicts: (input = {}) => service.syncConflicts(input), + conflict: (id) => service.syncConflict(id), + proposeConflictResolution: (id) => service.proposeSyncConflictResolution(id), + proposeConflictResolutionAi: (input) => service.proposeSyncConflictResolutionWithAi(input), + resolveConflict: (input) => service.resolveSyncConflict(input), + machines: () => service.syncMachines(), + exportBundle: (input = {}) => service.exportSyncBundle(input), + importBundle: (input) => service.importSyncBundle(input), + peer: (input) => service.syncPeer(input), + remotePeer: (input) => service.syncRemotePeer(input) }, - notes: { - permissions: [], - freshness: [] - } - }; -} -function legacyStorePathForRead(scope, workspace, preferred) { - const current = preferred ?? workspace.jsonStorePath; - if (existsSync14(current)) - return current; - if (scope === "global") { - const legacy = legacyGlobalStorePath(); - if (existsSync14(legacy)) - return legacy; - } - return current; -} -function estimateTokensForValue2(value) { - const text = JSON.stringify(value); - return Math.max(1, Math.ceil(text.length / 4)); -} -function compactText(value, maxChars) { - const normalized = (value ?? "").normalize("NFKC").trim().replace(/\s+/g, " "); - if (normalized.length <= maxChars) - return normalized; - return `${normalized.slice(0, Math.max(0, maxChars - 1)).trim()}...`; -} -function redactPreviewForPack(value, policy, maxChars) { - const redacted = redactSecrets(compactText(value, maxChars), policy); - return { text: redacted.text, redactions: redacted.findings.length }; -} -function legacyAgentContextPack(options, context, policy) { - const now = options.now ?? new Date; - const source = options.source ?? "search"; - const purpose = options.purpose ?? (source === "loops" || source === "runs" ? "proposal" : "agent_context"); - const query2 = (options.query ?? options.topic ?? context.query).normalize("NFKC").trim().replace(/\s+/g, " "); - const maxItems = Math.max(1, Math.min(options.maxItems ?? options.limit ?? 8, 50)); - const maxTokens = Math.max(500, Math.min(options.maxTokens ?? 6000, 1e5)); - let redactions = 0; - const citations = context.citations.slice(0, Math.max(maxItems * 2, maxItems)).map((citation, index) => { - const quote = redactPreviewForPack(citation.quote, policy, index < 3 ? 220 : 140); - redactions += quote.redactions; - const ref = citation.source_ref ?? citation.source_uri ?? citation.artifact_path ?? citation.artifact_uri ?? citation.id; - return { - id: `cite_${createHash21("sha256").update(`${citation.id}\x00${ref}`).digest("hex").slice(0, 12)}`, - kind: citation.artifact_uri || citation.artifact_path ? "artifact" : "source", - ref, - source_ref: citation.source_ref, - source_uri: citation.source_uri, - artifact_uri: citation.artifact_uri, - artifact_path: citation.artifact_path, - run_id: null, - run_event_id: null, - revision: citation.revision, - hash: citation.hash, - chunk_id: citation.chunk_id, - offsets: { - start: citation.start_offset, - end: citation.end_offset - }, - quote_preview: quote.text - }; - }); - const citationByRetrievalId = new Map(context.citations.map((citation, index) => [citation.id, citations[index]])); - const evidence = context.excerpts.slice(0, Math.max(maxItems * 2, maxItems)).map((excerpt2) => { - const result = context.results.find((entry) => entry.id === excerpt2.result_id); - const citation = excerpt2.citation_id ? citationByRetrievalId.get(excerpt2.citation_id) : undefined; - const preview2 = redactPreviewForPack(excerpt2.text, policy, 520); - redactions += preview2.redactions; - return { - id: `ev_${createHash21("sha256").update(`${excerpt2.kind}\x00${excerpt2.result_id}\x00${excerpt2.citation_id ?? ""}`).digest("hex").slice(0, 14)}`, - kind: excerpt2.kind, - title: compactText(result?.title ?? citation?.ref ?? excerpt2.kind, 100), - text_preview: preview2.text, - score: Number(excerpt2.score.toFixed(6)), - citation_ids: citation ? [citation.id] : [], - provenance: { - source, - record_ref: `${excerpt2.kind}:${excerpt2.result_id}`, - created_at: context.created_at, - updated_at: null, - metadata_keys: [] - } - }; - }).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, maxItems); - const usedCitationIds = new Set(evidence.flatMap((entry) => entry.citation_ids)); - const usedCitations = citations.filter((citation) => usedCitationIds.has(citation.id)); - const warnings = Array.from(new Set(context.warnings)); - const idempotencyKey = `ctx_${createHash21("sha256").update([source, purpose, query2, warnings.join(","), evidence.map((entry) => entry.id).join(",")].join("\x00")).digest("hex").slice(0, 20)}`; - const pack = { - ok: true, - format: "knowledge-agent-context-pack", - version: 1, - created_at: now.toISOString(), - source, - purpose, - query: query2, - topic: options.topic ?? null, - since: options.since ?? null, - dry_run: true, - idempotency_key: idempotencyKey, - budgets: { - max_tokens: maxTokens, - estimated_tokens: 0, - max_items: maxItems, - items_included: evidence.length, - items_available: context.excerpts.length, - items_truncated: Math.max(0, context.excerpts.length - evidence.length), - token_budget_exceeded: false + items: { + store: () => service.itemStore(), + list: () => service.listItems(), + get: (idOrShort) => service.getItem(idOrShort), + create: (input) => service.createItem(input), + update: (idOrShort, patch) => service.updateItem(idOrShort, patch), + delete: (idOrShort) => service.deleteItem(idOrShort), + deleteMany: (idsOrShorts) => service.deleteItems(idsOrShorts) }, - safety: { - raw_artifact_content_included: false, - durable_writes_performed: false, - redactions, - reminders: [ - "This pack is read-only and performs no durable writes.", - "Legacy JSON note evidence is bounded and redacted before inclusion." - ] + inventory: (input = {}) => service.resolveInventory(input), + db: { + init: () => service.initDb(), + stats: () => service.dbStats() }, - citations: usedCitations, - evidence, - duplicate_candidates: [], - outline: { - title: query2 ? `Knowledge context: ${compactText(query2, 80)}` : "Knowledge context", - bullets: evidence.length > 0 ? evidence.slice(0, 5).map((entry) => `${entry.id}: ${entry.title}`) : ["No matching bounded evidence was found."], - evidence_ids: evidence.slice(0, 8).map((entry) => entry.id), - duplicate_candidate_ids: [], - next_actions: [ - "Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.", - "Inspect cited refs only if the bounded preview is insufficient.", - "Use knowledge build/file-answer only with explicit approval for durable writes." - ] + wiki: { + init: () => service.initWiki(), + compile: (input = {}) => service.compileWiki(input), + fileAnswer: (input) => service.fileAnswer(input), + lint: () => service.lintWiki() }, - warnings, - message: `${evidence.length} bounded evidence item(s), estimated under ${maxTokens} token(s)` - }; - pack.budgets.estimated_tokens = estimateTokensForValue2(pack); - pack.budgets.token_budget_exceeded = pack.budgets.estimated_tokens > maxTokens; - pack.message = `${pack.evidence.length} bounded evidence item(s), estimated ${pack.budgets.estimated_tokens}/${maxTokens} token(s)`; - return pack; -} -function emptyReindexHealth() { - return { - schema_version: 0, - chunks: 0, - vector_entries: 0, - missing_embeddings: 0, - queued: {}, - stale_revisions: 0 - }; -} -function emptyEmbeddingStatus() { - return { - total_embeddings: 0, - total_vector_entries: 0, - indexes: [] - }; -} -function emptySyncStatus(input) { - return { - ok: true, - scope: input.scope, - workspace_home: input.workspaceHome, - sqlite_schema_version: 0, - local_machine_id: input.localMachineId ?? null, - machines: { - total: 0, - rows: [] + appWiki: { + paths: () => service.paths(), + init: (input = {}) => service.initAppWiki(input), + notes: { + add: (input) => service.addAppWikiNote(input), + list: (input = {}) => service.listAppWikiNotes(input), + get: (id, input = {}) => service.getAppWikiNote(id, input) + }, + sources: { + add: (input) => service.addAppWikiSourceRef(input) + }, + search: (input) => service.searchAppWiki(input), + query: (input) => service.queryAppWiki(input) }, - snapshots: { - total: 0, - latest: null + ingest: { + manifest: (input) => service.ingestManifest(input), + source: (sourceRef, purpose) => service.ingestSource(sourceRef, purpose), + rules: (input = {}) => service.importRulesProvenance(input) }, - changes: { - total: 0, - by_operation: [] + sources: { + resolve: (sourceRef, input = {}) => service.resolveSource(sourceRef, input), + consumeOutbox: (input) => service.consumeOutbox(input) }, - clocks: { - total: 0, - rows: [] + reindex: { + health: (input = {}) => service.reindexHealth(input), + enqueue: (input = {}) => service.enqueueReindex(input), + refreshEmbeddings: (input = {}) => service.refreshEmbeddings(input) }, - imports: { - total: 0, - latest: null + providers: { + status: (env = process.env) => service.providerStatus(env), + models: () => service.modelRegistry() }, - conflicts: { - total: 0, - by_status: [], - open: 0 + embeddings: { + status: () => service.embeddingStatus(), + index: (input = {}) => service.indexEmbeddings(input), + search: (input) => service.semanticSearch(input) }, - table_counts: {}, - message: "0 machine(s), 0 open sync conflict(s)" - }; -} -function emptyAgentContextPack(options) { - const now = options.now ?? new Date; - const source = options.source ?? "search"; - const purpose = options.purpose ?? (source === "loops" || source === "runs" ? "proposal" : "agent_context"); - const query2 = (options.query ?? options.topic ?? "").normalize("NFKC").trim().replace(/\s+/g, " "); - const maxItems = Math.max(1, Math.min(options.maxItems ?? options.limit ?? 8, 50)); - const maxTokens = Math.max(500, Math.min(options.maxTokens ?? 6000, 1e5)); - const idempotencyKey = `ctx_${createHash21("sha256").update(["empty", source, purpose, query2, options.topic ?? "", options.since ?? ""].join("\x00")).digest("hex").slice(0, 20)}`; - return { - ok: true, - format: "knowledge-agent-context-pack", - version: 1, - created_at: now.toISOString(), - source, - purpose, - query: query2, - topic: options.topic ?? null, - since: options.since ?? null, - dry_run: true, - idempotency_key: idempotencyKey, - budgets: { - max_tokens: maxTokens, - estimated_tokens: 0, - max_items: maxItems, - items_included: 0, - items_available: 0, - items_truncated: 0, - token_budget_exceeded: false + search: (input) => service.search(input), + retrieveContext: (input) => service.retrieveContext(input), + contextPack: (input) => service.contextPack(input), + context: { + pack: (input) => service.contextPack(input) }, - safety: { - raw_artifact_content_included: false, - durable_writes_performed: false, - redactions: 0, - reminders: [ - "This pack is read-only and performs no durable writes.", - "No knowledge.db exists for this scope yet." - ] + ask: (prompt, input = {}) => service.runPrompt({ ...input, prompt }), + build: (prompt, input = {}) => service.runPrompt({ ...input, prompt }), + web: { + search: (input) => service.webSearch(input) + } + }; +} +var createKnowledgeSdk = createKnowledgeClient; +function withDefaultAllowGlobal(input, allowGlobal) { + if (allowGlobal !== true) + return input; + return { ...input ?? {}, allowGlobal: input?.allowGlobal ?? true }; +} +function createAppWikiScope(options = {}) { + const { allowGlobal, ...clientOptions } = options; + const client = createKnowledgeClient({ + ...clientOptions, + scope: clientOptions.scope ?? "project" + }); + return { + paths: () => client.appWiki.paths(), + init: (input = {}) => client.appWiki.init(withDefaultAllowGlobal(input, allowGlobal)), + notes: { + add: (input) => client.appWiki.notes.add(withDefaultAllowGlobal(input, allowGlobal)), + list: (input = {}) => client.appWiki.notes.list(input), + get: (id, input = {}) => client.appWiki.notes.get(id, input) }, - citations: [], - evidence: [], - duplicate_candidates: [], - outline: { - title: query2 ? `Context for ${query2}` : "Knowledge context", - bullets: [], - evidence_ids: [], - duplicate_candidate_ids: [], - next_actions: [] + sources: { + add: (input) => client.appWiki.sources.add(withDefaultAllowGlobal(input, allowGlobal)) }, - warnings: ["knowledge_db_missing"], - message: `0 bounded evidence item(s), estimated 0/${maxTokens} token(s)` + search: (input) => client.appWiki.search(input), + query: (input) => client.appWiki.query(input) }; } -function storagePrefixKey(storage) { - const prefix = storage.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g, ""); - return prefix ? `${prefix}/` : null; +function openProjectWiki(options = {}) { + return createAppWikiScope({ ...options, scope: "project" }); } -function artifactManifestStatus(dbPath, storage) { - const db = openKnowledgeDb(dbPath); - try { - const rows = db.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json - FROM storage_objects - ORDER BY artifact_uri ASC`).all(); - const byKind = new Map; - let withHash = 0; - let withSize = 0; - let totalSizeBytes = 0; - let matchingPrefix = 0; - let missingKey = 0; - let prefixedKey = 0; - let rawPayloadSentinelHits = 0; - let withModifiedAt = 0; - let invalidModifiedAt = 0; - let withProvenance2 = 0; - let withProvenanceArtifactKey = 0; - let provenanceArtifactKeyMismatches = 0; - const generatedFrom = new Map; - const mismatchedExamples = []; - const prefixedExamples = []; - const invalidModifiedExamples = []; - const provenanceExamples = []; - const expectedPrefix = storage.artifact_store.uri_prefix; - const s3StoragePrefix = storagePrefixKey(storage); - for (const row of rows) { - byKind.set(row.kind, (byKind.get(row.kind) ?? 0) + 1); - if (row.hash?.startsWith("sha256:")) - withHash += 1; - if (typeof row.size_bytes === "number" && row.size_bytes >= 0) { - withSize += 1; - totalSizeBytes += row.size_bytes; +function openGlobalWiki(options) { + return createAppWikiScope({ ...options, scope: "global", allowGlobal: true }); +} +// node_modules/@hasna/contracts/dist/index.js +import { createHash as createHash22 } from "crypto"; +var __defProp2 = Object.defineProperty; +var __returnValue2 = (v) => v; +function __exportSetter2(name, newValue) { + this[name] = __returnValue2.bind(null, newValue); +} +var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { + get: all[name], + enumerable: true, + configurable: true, + set: __exportSetter2.bind(all, name) + }); +}; +var exports_external2 = {}; +__export2(exports_external2, { + void: () => voidType, + util: () => util, + unknown: () => unknownType, + union: () => unionType, + undefined: () => undefinedType, + tuple: () => tupleType, + transformer: () => effectsType, + symbol: () => symbolType, + string: () => stringType, + strictObject: () => strictObjectType, + setErrorMap: () => setErrorMap2, + set: () => setType, + record: () => recordType, + quotelessJson: () => quotelessJson, + promise: () => promiseType, + preprocess: () => preprocessType, + pipeline: () => pipelineType, + ostring: () => ostring, + optional: () => optionalType, + onumber: () => onumber, + oboolean: () => oboolean, + objectUtil: () => objectUtil, + object: () => objectType, + number: () => numberType, + nullable: () => nullableType, + null: () => nullType, + never: () => neverType, + nativeEnum: () => nativeEnumType, + nan: () => nanType, + map: () => mapType, + makeIssue: () => makeIssue, + literal: () => literalType, + lazy: () => lazyType, + late: () => late, + isValid: () => isValid, + isDirty: () => isDirty, + isAsync: () => isAsync, + isAborted: () => isAborted, + intersection: () => intersectionType, + instanceof: () => instanceOfType, + getParsedType: () => getParsedType2, + getErrorMap: () => getErrorMap2, + function: () => functionType, + enum: () => enumType, + effect: () => effectsType, + discriminatedUnion: () => discriminatedUnionType, + defaultErrorMap: () => en_default2, + datetimeRegex: () => datetimeRegex, + date: () => dateType, + custom: () => custom2, + coerce: () => coerce, + boolean: () => booleanType, + bigint: () => bigIntType, + array: () => arrayType, + any: () => anyType, + addIssueToContext: () => addIssueToContext, + ZodVoid: () => ZodVoid2, + ZodUnknown: () => ZodUnknown2, + ZodUnion: () => ZodUnion2, + ZodUndefined: () => ZodUndefined2, + ZodType: () => ZodType2, + ZodTuple: () => ZodTuple2, + ZodTransformer: () => ZodEffects, + ZodSymbol: () => ZodSymbol2, + ZodString: () => ZodString2, + ZodSet: () => ZodSet2, + ZodSchema: () => ZodType2, + ZodRecord: () => ZodRecord2, + ZodReadonly: () => ZodReadonly2, + ZodPromise: () => ZodPromise2, + ZodPipeline: () => ZodPipeline, + ZodParsedType: () => ZodParsedType, + ZodOptional: () => ZodOptional2, + ZodObject: () => ZodObject2, + ZodNumber: () => ZodNumber2, + ZodNullable: () => ZodNullable2, + ZodNull: () => ZodNull2, + ZodNever: () => ZodNever2, + ZodNativeEnum: () => ZodNativeEnum, + ZodNaN: () => ZodNaN2, + ZodMap: () => ZodMap2, + ZodLiteral: () => ZodLiteral2, + ZodLazy: () => ZodLazy2, + ZodIssueCode: () => ZodIssueCode2, + ZodIntersection: () => ZodIntersection2, + ZodFunction: () => ZodFunction2, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, + ZodError: () => ZodError2, + ZodEnum: () => ZodEnum2, + ZodEffects: () => ZodEffects, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, + ZodDefault: () => ZodDefault2, + ZodDate: () => ZodDate2, + ZodCatch: () => ZodCatch2, + ZodBranded: () => ZodBranded, + ZodBoolean: () => ZodBoolean2, + ZodBigInt: () => ZodBigInt2, + ZodArray: () => ZodArray2, + ZodAny: () => ZodAny2, + Schema: () => ZodType2, + ParseStatus: () => ParseStatus, + OK: () => OK, + NEVER: () => NEVER2, + INVALID: () => INVALID, + EMPTY_PATH: () => EMPTY_PATH, + DIRTY: () => DIRTY, + BRAND: () => BRAND +}); +var util; +(function(util2) { + util2.assertEqual = (_) => {}; + function assertIs2(_arg) {} + util2.assertIs = assertIs2; + function assertNever2(_x) { + throw new Error; + } + util2.assertNever = assertNever2; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { + const keys = []; + for (const key in object2) { + if (Object.prototype.hasOwnProperty.call(object2, key)) { + keys.push(key); } - if (row.artifact_uri.startsWith(expectedPrefix)) { - matchingPrefix += 1; - } else if (mismatchedExamples.length < 5) { - mismatchedExamples.push(row.artifact_uri); + } + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues2(array2, separator = " | ") { + return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues2; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; } - const metadata = parseMetadataJson(row.metadata_json); - if (metadataHasRawPayloadSentinel(metadata)) - rawPayloadSentinelHits += 1; - const key = typeof metadata.key === "string" ? metadata.key : null; - if (!key) { - missingKey += 1; - } else if (s3StoragePrefix && key.startsWith(s3StoragePrefix)) { - prefixedKey += 1; - if (prefixedExamples.length < 5) - prefixedExamples.push(key); + if (data === null) { + return ZodParsedType.null; } - const modifiedAt = typeof metadata.artifact_modified_at === "string" ? metadata.artifact_modified_at : null; - if (modifiedAt) { - if (Number.isNaN(Date.parse(modifiedAt))) { - invalidModifiedAt += 1; - if (invalidModifiedExamples.length < 5) - invalidModifiedExamples.push(row.artifact_uri); - } else { - withModifiedAt += 1; - } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; } - const provenance = metadata.provenance && typeof metadata.provenance === "object" && !Array.isArray(metadata.provenance) ? metadata.provenance : null; - if (provenance) { - withProvenance2 += 1; - const artifactKey = typeof provenance.artifact_key === "string" ? provenance.artifact_key : null; - const generated = typeof provenance.generated_from === "string" ? provenance.generated_from : "unknown"; - generatedFrom.set(generated, (generatedFrom.get(generated) ?? 0) + 1); - if (artifactKey) { - withProvenanceArtifactKey += 1; - if (key && artifactKey !== key) { - provenanceArtifactKeyMismatches += 1; - if (provenanceExamples.length < 5) - provenanceExamples.push(`${row.artifact_uri}:provenance.artifact_key=${artifactKey}:key=${key}`); + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; +var ZodIssueCode2 = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json3 = JSON.stringify(obj, null, 2); + return json3.replace(/"([^"]+)":/g, "$1:"); +}; + +class ZodError2 extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error51) => { + for (const issue2 of error51.issues) { + if (issue2.code === "invalid_union") { + issue2.unionErrors.map(processError); + } else if (issue2.code === "invalid_return_type") { + processError(issue2.returnTypeError); + } else if (issue2.code === "invalid_arguments") { + processError(issue2.argumentsError); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue2.path.length) { + const el = issue2.path[i]; + const terminal = i === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; } - } else if (provenanceExamples.length < 5) { - provenanceExamples.push(`${row.artifact_uri}:missing_provenance_artifact_key`); } - } else if (provenanceExamples.length < 5) { - provenanceExamples.push(`${row.artifact_uri}:missing_provenance`); } - } - const missingHash = rows.length - withHash; - const missingSize = rows.length - withSize; - const missingModifiedAt = rows.length - withModifiedAt - invalidModifiedAt; - const missingProvenance = rows.length - withProvenance2; - const missingProvenanceArtifactKey = withProvenance2 - withProvenanceArtifactKey; - const mismatchedPrefix = rows.length - matchingPrefix; - const warnings = [ - missingHash > 0 ? `artifact_manifest_missing_hash:${missingHash}` : null, - missingSize > 0 ? `artifact_manifest_missing_size:${missingSize}` : null, - missingKey > 0 ? `artifact_manifest_missing_key:${missingKey}` : null, - mismatchedPrefix > 0 ? `artifact_manifest_uri_prefix_mismatch:${mismatchedPrefix}` : null, - prefixedKey > 0 ? `artifact_manifest_s3_key_contains_storage_prefix:${prefixedKey}` : null, - invalidModifiedAt > 0 ? `artifact_manifest_invalid_modified_at:${invalidModifiedAt}` : null, - missingProvenance > 0 ? `artifact_manifest_missing_provenance:${missingProvenance}` : null, - missingProvenanceArtifactKey > 0 ? `artifact_manifest_missing_provenance_artifact_key:${missingProvenanceArtifactKey}` : null, - provenanceArtifactKeyMismatches > 0 ? `artifact_manifest_provenance_key_mismatch:${provenanceArtifactKeyMismatches}` : null, - rawPayloadSentinelHits > 0 ? `artifact_manifest_raw_payload_sentinels:${rawPayloadSentinelHits}` : null - ].filter((entry) => Boolean(entry)); - const ok = warnings.length === 0; - return { - ok, - read_only: true, - storage_type: storage.storage_type, - artifact_uri_prefix: expectedPrefix, - s3: storage.artifact_store.s3, - artifacts: { - total: rows.length, - by_kind: [...byKind.entries()].map(([kind, count3]) => ({ kind, count: count3 })).sort((a, b) => a.kind.localeCompare(b.kind)), - with_hash: withHash, - missing_hash: missingHash, - with_size: withSize, - missing_size: missingSize, - total_size_bytes: totalSizeBytes - }, - modified_time: { - with_modified_at: withModifiedAt, - missing_modified_at: missingModifiedAt, - invalid_modified_at: invalidModifiedAt, - examples: invalidModifiedExamples - }, - provenance: { - with_provenance: withProvenance2, - missing_provenance: missingProvenance, - with_artifact_key: withProvenanceArtifactKey, - missing_artifact_key: missingProvenanceArtifactKey, - artifact_key_mismatches: provenanceArtifactKeyMismatches, - generated_from: [...generatedFrom.entries()].map(([value, count3]) => ({ value, count: count3 })).sort((a, b) => a.value.localeCompare(b.value)), - examples: provenanceExamples - }, - uri_prefix: { - matching: matchingPrefix, - mismatched: mismatchedPrefix, - examples: mismatchedExamples - }, - keys: { - with_key: rows.length - missingKey, - missing_key: missingKey, - prefixed_with_storage_prefix: prefixedKey, - prefixed_examples: prefixedExamples - }, - sync_manifest: { - copied_by_sync: true, - generated_artifacts_only: true, - includes_raw_source_bytes: false, - hash_algorithm: "sha256", - portable_keys: prefixedKey === 0 && missingKey === 0, - tracks_modified_time: withModifiedAt > 0 && invalidModifiedAt === 0, - preserves_provenance: missingProvenance === 0 && missingProvenanceArtifactKey === 0 && provenanceArtifactKeyMismatches === 0 - }, - raw_payload_sentinel_hits: rawPayloadSentinelHits, - warnings, - message: ok ? `${rows.length} generated artifact manifest row(s) ready for ${storage.storage_type} sync` : `Generated artifact manifest needs attention: ${warnings.join(", ")}` }; - } finally { - db.close(); + processError(this); + return fieldErrors; } -} -function artifactManifestKeyRepairCandidates(dbPath, storage) { - const prefix = storagePrefixKey(storage); - if (!prefix) - return []; - const db = openKnowledgeDb(dbPath); - try { - const rows = db.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json - FROM storage_objects - ORDER BY artifact_uri ASC`).all(); - const candidates = []; - for (const row of rows) { - const metadata = parseMetadataJson(row.metadata_json); - const currentKey = typeof metadata.key === "string" ? metadata.key : null; - if (!currentKey?.startsWith(prefix)) - continue; - const repaired = currentKey.slice(prefix.length); - if (!repaired) - continue; - candidates.push({ - id: row.id, - artifact_uri: row.artifact_uri, - kind: row.kind, - current_key: currentKey, - repaired_key: normalizeArtifactKey(repaired), - hash: row.hash, - size_bytes: row.size_bytes - }); + static assert(value) { + if (!(value instanceof ZodError2)) { + throw new Error(`Not a ZodError: ${value}`); } - return candidates; - } finally { - db.close(); } -} -function doctorRecommendations(input) { - const scopeArgs = ["--scope", input.scope, "--json"]; - const tableArgs = input.tables?.length ? ["--tables", input.tables.join(",")] : []; - const commands = [ - syncCommand({ - id: "sync_status", - reason: "Inspect local sync registry, clocks, snapshots, and conflicts.", - args: ["sync", "status", ...scopeArgs] - }) - ]; - if (input.machine && !serviceMachineIsLocal(input.machine)) { - commands.push(syncCommand({ - id: "sync_dry_run_remote", - reason: "Preview remote machine sync before changing either workspace.", - args: [ - "sync", - "dry-run", - "--machine", - input.machine, - ...input.peerWorkspace ? ["--peer-workspace", input.peerWorkspace] : [], - ...tableArgs, - ...scopeArgs - ] - })); - } else if (input.peerWorkspace) { - commands.push(syncCommand({ - id: "sync_dry_run_peer", - reason: "Preview local peer sync before changing either workspace.", - args: ["sync", "dry-run", "--peer-workspace", input.peerWorkspace, ...tableArgs, ...scopeArgs] - })); + toString() { + return this.message; } - for (const hint of input.resolvedWorkspace?.repair_hints ?? []) { - commands.push({ - id: hint.id, - reason: hint.reason, - command: hint.command, - shell_command: hint.shell_command - }); + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } - if (input.openConflicts > 0) { - commands.push(syncCommand({ - id: "sync_conflicts", - reason: "Review open conflicts before relying on bidirectional sync.", - args: ["sync", "conflicts", ...scopeArgs] - })); + get isEmpty() { + return this.issues.length === 0; } - return commands; -} -function resolveSshSpawnSpec() { - const command = process.env.KNOWLEDGE_SSH_COMMAND?.trim() || "ssh"; - const rawArgs = process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON; - if (!rawArgs) - return { command, argsPrefix: [] }; - let parsed; - try { - parsed = JSON.parse(rawArgs); - } catch (error51) { - throw new Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${error51 instanceof Error ? error51.message : String(error51)}`); + flatten(mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; } - if (!Array.isArray(parsed) || !parsed.every((arg) => typeof arg === "string")) { - throw new Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array."); + get formErrors() { + return this.flatten(); } - return { command, argsPrefix: parsed }; } -function runSshCommand(machine, command, input, resolved) { - const ssh = resolveSshSpawnSpec(); - const result = spawnSync2(ssh.command, [...ssh.argsPrefix, resolved.target, command], { - encoding: "utf8", - env: process.env, - input, - maxBuffer: 64 * 1024 * 1024 - }); - if ((result.status ?? 1) !== 0) { - const route = resolved.source === "open-machines" ? ` via ${resolved.route ?? "resolved"}:${resolved.target}` : ""; - throw new Error(`ssh ${machine}${route} failed: ${(result.stderr || result.stdout || String(result.status)).trim()}`); +ZodError2.create = (issues) => { + const error51 = new ZodError2(issues); + return error51; +}; +var errorMap = (issue2, _ctx) => { + let message; + switch (issue2.code) { + case ZodIssueCode2.invalid_type: + if (issue2.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue2.expected}, received ${issue2.received}`; + } + break; + case ZodIssueCode2.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode2.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; + break; + case ZodIssueCode2.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode2.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; + break; + case ZodIssueCode2.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; + break; + case ZodIssueCode2.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode2.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode2.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode2.invalid_string: + if (typeof issue2.validation === "object") { + if ("includes" in issue2.validation) { + message = `Invalid input: must include "${issue2.validation.includes}"`; + if (typeof issue2.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; + } + } else if ("startsWith" in issue2.validation) { + message = `Invalid input: must start with "${issue2.validation.startsWith}"`; + } else if ("endsWith" in issue2.validation) { + message = `Invalid input: must end with "${issue2.validation.endsWith}"`; + } else { + util.assertNever(issue2.validation); + } + } else if (issue2.validation !== "regex") { + message = `Invalid ${issue2.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode2.too_small: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "bigint") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode2.too_big: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "bigint") + message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode2.custom: + message = `Invalid input`; + break; + case ZodIssueCode2.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode2.not_multiple_of: + message = `Number must be a multiple of ${issue2.multipleOf}`; + break; + case ZodIssueCode2.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue2); } - return result.stdout || ""; + return { message }; +}; +var en_default2 = errorMap; +var overrideErrorMap = en_default2; +function setErrorMap2(map2) { + overrideErrorMap = map2; } -function parseRemoteJson(machine, action, raw) { - try { - return JSON.parse(raw); - } catch (error51) { - const preview2 = raw.trim().slice(0, 240); - throw new Error(`Remote knowledge ${action} on ${machine} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${preview2 || String(error51)}`); +function getErrorMap2() { + return overrideErrorMap; +} +var makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map2 of maps) { + errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap2(); + const issue2 = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + overrideMap, + overrideMap === en_default2 ? undefined : en_default2 + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue2); } -function assertRemoteSyncBundle(machine, value) { - if (typeof value !== "object" || value === null || !("format" in value) || value.format !== "knowledge-sync-bundle") { - throw new Error(`Remote knowledge sync export on ${machine} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`); + +class ParseStatus { + constructor() { + this.value = "valid"; } - const protocolVersion = value.protocol_version; - const minProtocolVersion = value.min_protocol_version; - if (typeof protocolVersion !== "number" || typeof minProtocolVersion !== "number" || protocolVersion < KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION || minProtocolVersion > KNOWLEDGE_SYNC_PROTOCOL_VERSION) { - throw new Error(`Remote knowledge sync export on ${machine} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`); + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; } } -function assertRemoteSyncApplyResult(machine, value) { - if (typeof value !== "object" || value === null || !("ok" in value) || !("target" in value) || !("tables" in value) || !("artifacts" in value) || !("conflicts_created" in value)) { - throw new Error(`Remote knowledge sync import on ${machine} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`); +var INVALID = Object.freeze({ + status: "aborted" +}); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); + +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; } - const protocolVersion = value.protocol_version; - const minProtocolVersion = value.min_protocol_version; - if (typeof protocolVersion !== "number" || typeof minProtocolVersion !== "number" || protocolVersion < KNOWLEDGE_SYNC_MIN_PROTOCOL_VERSION || minProtocolVersion > KNOWLEDGE_SYNC_PROTOCOL_VERSION) { - throw new Error(`Remote knowledge sync import on ${machine} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`); + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; } } -function normalizeMode(value) { - if (!value) - return; - const normalized = value.trim().toLowerCase(); - if (normalized === "local" || normalized === "offline") - return "local"; - if (normalized === "hosted" || normalized === "remote" || normalized === "knowledge.md") - return "hosted"; - throw new Error("Invalid setup mode. Use hosted or local."); +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error51 = new ZodError2(ctx.common.issues); + this._error = error51; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; } -class KnowledgeService { - options; - ensuredWorkspace; - cachedConfig; - constructor(options = {}) { - this.options = options; +class ZodType2 { + get description() { + return this._def.description; } - get scope() { - return this.options.scope ?? "global"; + _getType(input) { + return getParsedType2(input.data); } - get workspace() { - return this.ensuredWorkspace ?? resolveScopedWorkspace(this.options.scope, this.options.cwd); + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType2(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus, + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType2(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType2(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType2(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); } - ensureWorkspace() { - if (!this.ensuredWorkspace) - this.ensuredWorkspace = ensureKnowledgeWorkspace(this.workspace.home); - return this.ensuredWorkspace; + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; } - jsonStorePath() { - return this.ensureWorkspace().jsonStorePath; + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType2(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); } - itemStore() { - const workspace = this.ensureWorkspace(); - return resolveItemStore({ - storePath: workspace.jsonStorePath, - storePathOverridden: false + refine(check2, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check2(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode2.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } }); } - async listItems() { - return this.itemStore().listAll(); - } - async getItem(idOrShort) { - return this.itemStore().get(idOrShort); - } - async createItem(input) { - return this.itemStore().create(input); + refinement(check2, refinementData) { + return this._refinement((val, ctx) => { + if (!check2(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); } - async updateItem(idOrShort, patch) { - return this.itemStore().update(idOrShort, patch); + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect: { type: "refinement", refinement } + }); } - async deleteItem(idOrShort) { - return this.itemStore().delete(idOrShort); + superRefine(refinement) { + return this._refinement(refinement); } - async deleteItems(idsOrShorts) { - return this.itemStore().deleteMany(idsOrShorts); + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; } - async resolveInventory(options = {}) { - if (this.isApiMode()) - return this.cloudInventory(options); - return this.inventory(options); + optional() { + return ZodOptional2.create(this, this._def); } - config(options = {}) { - const workspace = options.ensure ? this.ensureWorkspace() : this.workspace; - if (!this.cachedConfig || options.ensure || existsSync14(workspace.configPath)) { - this.cachedConfig = existsSync14(workspace.configPath) ? readKnowledgeConfig(workspace.configPath) : defaultKnowledgeConfig(); - } - return this.cachedConfig; + nullable() { + return ZodNullable2.create(this, this._def); } - safetyPolicy() { - return resolveSafetyPolicy(this.config(), this.workspace); + nullish() { + return this.nullable().optional(); } - artifactStore() { - return createArtifactStore(this.config(), this.ensureWorkspace()); + array() { + return ZodArray2.create(this); } - storageContract() { - return resolveStorageContract(this.config(), this.workspace, this.scope); + promise() { + return ZodPromise2.create(this, this._def); } - validateStorage() { - return validateStorageConfig(this.config(), this.workspace); + or(option) { + return ZodUnion2.create([this, option], this._def); } - assertStorageValid(action) { - const validation = this.validateStorage(); - if (!validation.ok) { - throw new Error(`Storage contract invalid before ${action}: ${validation.errors.join("; ")}`); - } + and(incoming) { + return ZodIntersection2.create(this, incoming, this._def); } - migrateLegacyPath(options = {}) { - const current = this.workspace; - const legacy = resolveLegacyScopedWorkspace(this.options.scope, this.options.cwd); - const result = migrateLegacyKnowledgeWorkspace({ - scope: this.scope, - current, - legacy, - approveWrite: options.approveWrite, - approvedBy: options.approvedBy + transform(transform2) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect: { type: "transform", transform: transform2 } }); - if (!result.dry_run && result.ok) { - this.ensuredWorkspace = undefined; - this.cachedConfig = undefined; - } - return result; } - mergeLegacyPath(options = {}) { - const current = this.workspace; - const legacy = resolveLegacyScopedWorkspace(this.options.scope, this.options.cwd); - const result = mergeLegacyKnowledgeWorkspace({ - scope: this.scope, - current, - legacy, - approveWrite: options.approveWrite, - approvedBy: options.approvedBy + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault2({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind2.ZodDefault }); - if (!result.dry_run && result.ok) { - this.ensuredWorkspace = undefined; - this.cachedConfig = undefined; - } - return result; - } - setup(options = {}) { - const workspace = this.ensureWorkspace(); - const current = this.config({ ensure: true }); - const mode2 = normalizeMode(options.mode) ?? current.mode; - const apiUrl = options.apiUrl ? normalizeKnowledgeApiOrigin(options.apiUrl) : current.hosted?.api_url ? normalizeKnowledgeApiOrigin(current.hosted.api_url) : null; - const nextConfig = { - ...current, - mode: mode2, - hosted: { - ...current.hosted ?? {}, - ...apiUrl ? { api_url: apiUrl } : {} - }, - storage: options.canonicalExample ? canonicalExampleKnowledgeStorage() : current.storage - }; - writeKnowledgeConfig(workspace.configPath, nextConfig); - this.cachedConfig = nextConfig; - const storage = resolveStorageContract(nextConfig, workspace, this.scope); - return { - ok: true, - mode: mode2, - api_url: nextConfig.hosted?.api_url ?? null, - storage_type: nextConfig.storage.type, - artifact_uri_prefix: storage.artifact_store.uri_prefix, - canonical_example: storage.canonical_example, - config_path: workspace.configPath, - next: mode2 === "hosted" ? ["knowledge auth login --api-key <key>", "knowledge storage status --json"] : ["knowledge search <query>", "knowledge <prompt>"], - message: `Set knowledge mode to ${mode2}` - }; - } - authStatus(env = process.env) { - return knowledgeAuthStatus(this.config(), env); - } - saveAuth(input, env = process.env) { - const apiUrl = input.apiUrl ?? this.config().hosted?.api_url; - return saveKnowledgeAuth({ - api_key: input.apiKey, - email: input.email, - org_id: input.orgId, - org_slug: input.orgSlug, - user_id: input.userId, - api_url: apiUrl - }, env); } - clearAuth(env = process.env) { - return clearKnowledgeAuth(env); + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind2.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); } - paths() { - const workspace = this.workspace; - return { - ok: true, - scope: this.scope, - home: workspace.home, - exists: existsSync14(workspace.home), - config_path: workspace.configPath, - config_exists: existsSync14(workspace.configPath), - json_store_path: workspace.jsonStorePath, - json_store_exists: existsSync14(workspace.jsonStorePath), - knowledge_db_path: workspace.knowledgeDbPath, - knowledge_db_exists: existsSync14(workspace.knowledgeDbPath), - artifacts_dir: workspace.artifactsDir, - indexes_dir: workspace.indexesDir, - logs_dir: workspace.logsDir, - runs_dir: workspace.runsDir, - schemas_dir: workspace.schemasDir, - wiki_dir: workspace.wikiDir, - config: this.config(), - message: workspace.home - }; + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch2({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind2.ZodCatch + }); } - initDb() { - return migrateKnowledgeDb(this.ensureWorkspace().knowledgeDbPath); + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); } - dbStats() { - assertLocalCatalogMode("reading knowledge.db stats"); - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) - return emptyKnowledgeDbStats(); - return getKnowledgeDbStats(workspace.knowledgeDbPath); + pipe(target) { + return ZodPipeline.create(this, target); } - enqueuePromotion(input) { - return enqueueKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, input); + readonly() { + return ZodReadonly2.create(this); } - promotionInbox(options = {}) { - return listKnowledgePromotions(this.ensureWorkspace().knowledgeDbPath, options); + isOptional() { + return this.safeParse(undefined).success; } - getPromotion(id) { - return getKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id); + isNullable() { + return this.safeParse(null).success; } - reviewPromotion(id, now) { - return reviewKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, now); +} +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var durationRegex = /^[-+]?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)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex; +var ipv4Regex = /^(?:(?: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])$/; +var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; +var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var dateRegexSource = `((\\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])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } - promoteCandidate(id, options = {}) { - return promoteKnowledgeCandidate(this.ensureWorkspace().knowledgeDbPath, id, options); + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version2) { + if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { + return true; } - rejectPromotion(id, options = {}) { - return rejectKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, options); + if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { + return true; } - durableRecords(options = {}) { - return listDurableKnowledgeRecords(this.ensureWorkspace().knowledgeDbPath, options); + return false; +} +function isValidJWT2(jwt2, alg) { + if (!jwtRegex.test(jwt2)) + return false; + try { + const [header] = jwt2.split("."); + if (!header) + return false; + const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base643)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; } - itemOnlyInventory(params) { - const workspace = this.workspace; - const { items, limit, includeArchived, storePath, storeExists, storeReadError } = params; - const activeItems = items.filter((item) => item.archived !== true); - const visibleItems = includeArchived ? items : activeItems; - const stats = emptyKnowledgeDbStats(); - const summary = { - legacy_items: items.length, - active_items: activeItems.length, - archived_items: items.length - activeItems.length, - schema_version: stats.schema_version, - sources: stats.sources, - source_revisions: stats.source_revisions, - chunks: stats.chunks, - wiki_pages: stats.wiki_pages, - citations: stats.citations, - indexes: stats.indexes, - runs: stats.runs, - run_events: stats.run_events, - storage_objects: stats.storage_objects, - embeddings: stats.embeddings, - vector_entries: stats.vector_entries, - reindex_queue: stats.reindex_queue, - redaction_findings: stats.redaction_findings, - audit_events: stats.audit_events, - approval_gates: stats.approval_gates, - knowledge_machines: stats.knowledge_machines, - sync_snapshots: stats.sync_snapshots, - sync_changes: stats.sync_changes, - sync_conflicts: stats.sync_conflicts, - sync_table_clocks: stats.sync_table_clocks, - sync_imports: stats.sync_imports, - promotion_candidates: stats.promotion_candidates, - durable_records: stats.durable_records - }; - return { - ok: true, - scope: this.scope, - home: workspace.home, - limit, - paths: { - json_store_path: workspace.jsonStorePath, - json_store_exists: existsSync14(workspace.jsonStorePath), - knowledge_db_path: workspace.knowledgeDbPath, - knowledge_db_exists: existsSync14(workspace.knowledgeDbPath), - artifacts_dir: workspace.artifactsDir, - indexes_dir: workspace.indexesDir, - logs_dir: workspace.logsDir, - wiki_dir: workspace.wikiDir - }, - summary, - legacy_store: { - path: storePath, - exists: storeExists, - read_error: storeReadError, - total_items: items.length, - active_items: activeItems.length, - archived_items: items.length - activeItems.length, - items_returned: Math.min(visibleItems.length, limit) - }, - items: visibleItems.slice(0, limit).map(legacyInventoryItem), - sources: [], - source_revisions: [], - chunks: [], - wiki_pages: [], - indexes: [], - storage_objects: [], - runs: [], - vector_indexes: [], - reindex_queue: [], - machines: [], - sync_conflicts: [], - approval_gates: [], - audit_events: [], - promotion_candidates: [], - durable_records: [], - message: `${items.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)` - }; +} +function isValidCidr(ip, version2) { + if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { + return true; } - async cloudInventory(options = {}) { - const limit = inventoryLimit(options.limit); - const items = await this.fetchCloudItems(); - const cloud = resolveKnowledgeCloudStore(); - return this.itemOnlyInventory({ - items, - limit, - includeArchived: options.includeArchived ?? false, - storePath: cloud?.baseUrl ?? "cloud", - storeExists: true, - storeReadError: null - }); + if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { + return true; } - inventory(options = {}) { - const workspace = this.workspace; - const limit = inventoryLimit(options.limit); - const storePath = options.storePath ?? workspace.jsonStorePath; - const legacyStore = readLegacyInventoryStore(storePath); - const activeItems = legacyStore.items.filter((item) => item.archived !== true); - const visibleItems = options.includeArchived ? legacyStore.items : activeItems; - const dbExists = existsSync14(workspace.knowledgeDbPath); - if (!dbExists) { - return this.itemOnlyInventory({ - items: legacyStore.items, - limit, - includeArchived: options.includeArchived ?? false, - storePath, - storeExists: legacyStore.exists, - storeReadError: legacyStore.read_error + return false; +} + +class ZodString2 extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType }); + return INVALID; } - migrateKnowledgeDb(workspace.knowledgeDbPath); - const stats = getKnowledgeDbStats(workspace.knowledgeDbPath); - const db = openKnowledgeDb(workspace.knowledgeDbPath); - try { - const sources = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT - s.id, - s.uri, - s.kind, - s.title, - s.metadata_json, - s.acl_json, - s.created_at, - s.updated_at, - COUNT(DISTINCT sr.id) AS revisions, - COUNT(DISTINCT c.id) AS chunks - FROM sources s - LEFT JOIN source_revisions sr ON sr.source_id = s.id - LEFT JOIN chunks c ON c.source_revision_id = sr.id - GROUP BY s.id - ORDER BY s.updated_at DESC, s.created_at DESC - LIMIT ? - `, [limit]), ["metadata_json", "acl_json"]); - const sourceRevisions = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT - sr.id, - s.uri AS source_uri, - sr.revision, - sr.hash, - sr.extracted_text_uri, - sr.metadata_json, - sr.created_at - FROM source_revisions sr - JOIN sources s ON s.id = sr.source_id - ORDER BY sr.created_at DESC - LIMIT ? - `, [limit])); - const chunks = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT - c.id, - c.kind, - c.ordinal, - substr(c.text, 1, 220) AS text_preview, - c.token_count, - c.start_offset, - c.end_offset, - c.metadata_json, - c.created_at, - s.uri AS source_uri, - sr.revision AS source_revision, - wp.path AS wiki_path, - wp.title AS wiki_title - FROM chunks c - LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id - LEFT JOIN sources s ON s.id = sr.source_id - LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id - ORDER BY c.created_at DESC, c.ordinal ASC - LIMIT ? - `, [limit])); - const wikiPages = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at - FROM wiki_pages - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit])); - const indexes = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at - FROM knowledge_indexes - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit])); - const storageObjects = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at - FROM storage_objects - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit])); - const runs = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT - id, - type, - substr(prompt, 1, 220) AS prompt_preview, - status, - provider, - model, - cost_tokens, - cost_usd, - metadata_json, - created_at, - updated_at - FROM runs - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit])); - const vectorIndexes = selectInventoryRows(db, ` - SELECT provider, model, dimensions, status, COUNT(*) AS entries - FROM vector_index_entries - GROUP BY provider, model, dimensions, status - ORDER BY entries DESC - LIMIT ? - `, [limit]); - const reindexQueue = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT id, kind, target_id, source_uri, reason, status, attempts, metadata_json, created_at, updated_at - FROM reindex_queue - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit])); - const machines = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT - machine_id, - hostname, - platform, - user_label, - workspace_home, - tailscale_dns, - tailscale_ips_json, - ssh_target, - last_seen_at, - capabilities_json, - metadata_json, - created_at, - updated_at - FROM knowledge_machines - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit]), ["tailscale_ips_json", "capabilities_json", "metadata_json"]); - const syncConflicts = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT - id, - entity_kind, - entity_id, - local_machine_id, - remote_machine_id, - status, - resolution_strategy, - proposed_patch_uri, - approved_by, - resolved_at, - metadata_json, - created_at - FROM knowledge_sync_conflicts - ORDER BY created_at DESC - LIMIT ? - `, [limit])); - const approvalGates = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at - FROM approval_gates - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit])); - const auditEvents = rowsWithJsonFields(selectInventoryRows(db, ` - SELECT id, event_type, action, target_uri, decision, metadata_json, created_at - FROM audit_events - ORDER BY created_at DESC - LIMIT ? - `, [limit])); - const promotionCandidates = selectInventoryRows(db, ` - SELECT - id, - record_kind, - title, - substr(content, 1, 220) AS content_preview, - canonical_key, - content_hash, - source_kind, - source_refs_json, - evidence_refs_json, - status, - requires_approval, - checks_json, - duplicate_of, - approved_by, - promoted_record_id, - metadata_json, - created_at, - updated_at, - reviewed_at, - promoted_at - FROM knowledge_promotion_candidates - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit]).map(promotionCandidateInventoryRow); - const durableRecords = selectInventoryRows(db, ` - SELECT - id, - record_kind, - title, - substr(content, 1, 220) AS content_preview, - canonical_key, - content_hash, - status, - source_refs_json, - evidence_refs_json, - confidence, - valid_from, - valid_to, - promoted_from_candidate_id, - approved_by, - metadata_json, - created_at, - updated_at - FROM durable_knowledge_records - ORDER BY updated_at DESC, created_at DESC - LIMIT ? - `, [limit]).map(durableRecordInventoryRow); - const summary = { - legacy_items: legacyStore.items.length, - active_items: activeItems.length, - archived_items: legacyStore.items.length - activeItems.length, - schema_version: stats.schema_version, - sources: stats.sources, - source_revisions: stats.source_revisions, - chunks: stats.chunks, - wiki_pages: stats.wiki_pages, - citations: stats.citations, - indexes: stats.indexes, - runs: stats.runs, - run_events: stats.run_events, - storage_objects: stats.storage_objects, - embeddings: stats.embeddings, - vector_entries: stats.vector_entries, - reindex_queue: stats.reindex_queue, - redaction_findings: stats.redaction_findings, - audit_events: stats.audit_events, - approval_gates: stats.approval_gates, - knowledge_machines: stats.knowledge_machines, - sync_snapshots: stats.sync_snapshots, - sync_changes: stats.sync_changes, - sync_conflicts: stats.sync_conflicts, - sync_table_clocks: stats.sync_table_clocks, - sync_imports: stats.sync_imports, - promotion_candidates: stats.promotion_candidates, - durable_records: stats.durable_records - }; - return { - ok: true, - scope: this.scope, - home: workspace.home, - limit, - paths: { - json_store_path: storePath, - json_store_exists: legacyStore.exists, - knowledge_db_path: workspace.knowledgeDbPath, - knowledge_db_exists: true, - artifacts_dir: workspace.artifactsDir, - indexes_dir: workspace.indexesDir, - logs_dir: workspace.logsDir, - wiki_dir: workspace.wikiDir - }, - summary, - legacy_store: { - path: storePath, - exists: legacyStore.exists, - read_error: legacyStore.read_error, - total_items: legacyStore.items.length, - active_items: activeItems.length, - archived_items: legacyStore.items.length - activeItems.length, - items_returned: Math.min(visibleItems.length, limit) - }, - items: visibleItems.slice(0, limit).map(legacyInventoryItem), - sources, - source_revisions: sourceRevisions, - chunks, - wiki_pages: wikiPages, - indexes, - storage_objects: storageObjects, - runs, - vector_indexes: vectorIndexes, - reindex_queue: reindexQueue, - machines, - sync_conflicts: syncConflicts, - approval_gates: approvalGates, - audit_events: auditEvents, - promotion_candidates: promotionCandidates, - durable_records: durableRecords, - message: `${legacyStore.items.length} item(s), ${stats.sources} source(s), ${stats.chunks} chunk(s), ${stats.wiki_pages} wiki page(s), ${stats.storage_objects} artifact(s)` - }; - } finally { - db.close(); + const status = new ParseStatus; + let ctx = undefined; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.length < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.length > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "length") { + const tooBig = input.data.length > check2.value; + const tooSmall = input.data.length < check2.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } + status.dirty(); + } + } else if (check2.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "regex") { + check2.regex.lastIndex = 0; + const testResult = check2.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "trim") { + input.data = input.data.trim(); + } else if (check2.kind === "includes") { + if (!input.data.includes(check2.value, check2.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { includes: check2.value, position: check2.position }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check2.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check2.kind === "startsWith") { + if (!input.data.startsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { startsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "endsWith") { + if (!input.data.endsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { endsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "datetime") { + const regex = datetimeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "datetime", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "date", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "time") { + const regex = timeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "time", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ip") { + if (!isValidIP(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "jwt") { + if (!isValidJWT2(input.data, check2.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cidr") { + if (!isValidCidr(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } } + return { status: status.value, value: input.data }; } - assertAppWikiWrite(allowGlobal) { - assertAppWikiWriteAllowed({ - scope: this.scope, - workspace: this.workspace, - safetyPolicy: this.safetyPolicy(), - allowGlobal + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode2.invalid_string, + ...errorUtil.errToObj(message) }); } - async initAppWiki(options = {}) { - this.assertAppWikiWrite(options.allowGlobal); - const workspace = this.ensureWorkspace(); - return initAppWikiScope({ - scope: this.scope, - workspace, - store: this.artifactStore(), - safetyPolicy: this.safetyPolicy(), - allowGlobal: options.allowGlobal + _addCheck(check2) { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, check2] }); } - async addAppWikiNote(options) { - this.assertAppWikiWrite(options.allowGlobal); - const workspace = this.ensureWorkspace(); - return writeAppWikiNote({ - scope: this.scope, - workspace, - store: this.artifactStore(), - safetyPolicy: this.safetyPolicy(), - allowGlobal: options.allowGlobal, - title: options.title, - content: options.content, - tags: options.tags, - sourceRefs: options.sourceRefs, - path: options.path, - metadata: options.metadata - }); + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } - listAppWikiNotes(options = {}) { - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) - return []; - return listAppWikiNotes({ - dbPath: workspace.knowledgeDbPath, - limit: options.limit - }); + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } - async getAppWikiNote(id, options = {}) { - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) - return null; - return getAppWikiNote({ - dbPath: workspace.knowledgeDbPath, - store: this.artifactStore(), - id, - includeContent: options.includeContent - }); + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } - async addAppWikiSourceRef(options) { - this.assertAppWikiWrite(options.allowGlobal); - const workspace = this.ensureWorkspace(); - return ingestAppWikiSourceRef({ - scope: this.scope, - workspace, - sourceRef: options.sourceRef, - purpose: options.purpose, - config: this.config(), - safetyPolicy: this.safetyPolicy(), - allowGlobal: options.allowGlobal + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) }); } - async searchAppWiki(options) { - return this.search(options); + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } - async queryAppWiki(options) { - return this.retrieveContext(options); + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } - async initWiki() { - const workspace = this.ensureWorkspace(); - migrateKnowledgeDb(workspace.knowledgeDbPath); - const result = await initializeWikiLayout(this.artifactStore()); - const db = openKnowledgeDb(workspace.knowledgeDbPath); - try { - recordStorageObjects(db, result.artifacts); - recordWikiLayoutCatalog(db, result.artifacts); - } finally { - db.close(); - } - return result; + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } - async compileWiki(options = {}) { - const workspace = this.ensureWorkspace(); - return compileWikiPage({ - ...options, - dbPath: workspace.knowledgeDbPath, - store: this.artifactStore() + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) }); } - async fileAnswer(options) { - const workspace = this.ensureWorkspace(); - const context = await this.retrieveContext({ - query: options.prompt, - limit: options.limit, - semantic: options.semantic, - modelRef: options.modelRef, - dimensions: options.dimensions, - fake: options.fake + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) }); - return fileAnswerToWiki({ - dbPath: workspace.knowledgeDbPath, - store: this.artifactStore(), - prompt: options.prompt, - answer: options.answer, - context, - approveWrite: options.approveWrite + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) }); } - lintWiki() { - const workspace = this.ensureWorkspace(); - return lintWiki({ dbPath: workspace.knowledgeDbPath }); + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); } - async ingestManifest(input) { - const workspace = this.ensureWorkspace(); - return ingestOpenFilesManifest({ - dbPath: workspace.knowledgeDbPath, - input, - config: this.config(), - safetyPolicy: this.safetyPolicy() + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) }); } - async ingestSource(sourceRef, purpose) { - const workspace = this.ensureWorkspace(); - return ingestSourceRef({ - dbPath: workspace.knowledgeDbPath, - sourceRef, - purpose, - config: this.config(), - safetyPolicy: this.safetyPolicy() + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) }); } - async importRulesProvenance(options = {}) { - const dryRun = options.dryRun !== false; - const workspace = dryRun ? this.workspace : this.ensureWorkspace(); - return importRulesProvenance({ - root: options.root ?? this.options.cwd ?? process.cwd(), - scope: this.scope, - owner: options.owner, - dryRun, - deprecateLegacy: options.deprecateLegacy, - includeLegacy: options.includeLegacy, - legacyStorePath: workspace.jsonStorePath, - dbPath: workspace.knowledgeDbPath, - safetyPolicy: this.safetyPolicy(), - maxItems: options.maxItems, - limit: options.limit + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) }); } - async resolveSource(sourceRef, options = {}) { - const workspace = this.ensureWorkspace(); - return resolveOpenFilesSource({ - dbPath: workspace.knowledgeDbPath, - sourceRef, - purpose: options.purpose, - limit: options.limit, - safetyPolicy: this.safetyPolicy() + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) }); } - async consumeOutbox(input) { - const workspace = this.ensureWorkspace(); - return consumeOpenFilesOutbox({ - dbPath: workspace.knowledgeDbPath, - input, - config: this.config(), - safetyPolicy: this.safetyPolicy() + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) }); } - reindexHealth(options = {}) { - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) - return emptyReindexHealth(); - return reindexHealth({ - ...options, - dbPath: workspace.knowledgeDbPath, - config: this.config() + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] }); } - enqueueReindex(options = {}) { - const workspace = this.ensureWorkspace(); - return enqueueMissingEmbeddings({ - ...options, - dbPath: workspace.knowledgeDbPath, - config: this.config() + toLowerCase() { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] }); } - async refreshEmbeddings(options = {}) { - const workspace = this.ensureWorkspace(); - return refreshEmbeddingIndex({ - ...options, - dbPath: workspace.knowledgeDbPath, - config: this.config() + toUpperCase() { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] }); } - providerStatus(env = process.env) { - return providerStatus(this.config(), env); + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodString2.create = (params) => { + return new ZodString2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder2(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} + +class ZodNumber2 extends ZodType2 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus; + for (const check2 of this._def.checks) { + if (check2.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: "integer", + received: "float", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (floatSafeRemainder2(input.data, check2.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.not_finite, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; } - modelRegistry() { - return listModelRegistry(this.config()); + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); } - embeddingStatus() { - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) - return emptyEmbeddingStatus(); - return embeddingIndexStatus(workspace.knowledgeDbPath); + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); } - async indexEmbeddings(options = {}) { - const workspace = this.ensureWorkspace(); - return indexKnowledgeEmbeddings({ - ...options, - dbPath: workspace.knowledgeDbPath, - config: this.config() - }); + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); } - isApiMode() { - return isKnowledgeApiMode(); + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); } - async fetchCloudItems() { - const cloud = resolveKnowledgeCloudStore(); - if (!cloud) - throw new Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY)."); - return fetchAllCloudItems(cloud); + setLimit(kind, value, inclusive, message) { + return new ZodNumber2({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); } - async semanticSearch(options) { - const workspace = this.workspace; - if (this.isApiMode()) { - const items = await this.fetchCloudItems(); - const search = await hybridSearchItems(items, { ...options }, ["semantic_search_requires_local_catalog"]); - return { - provider: "openai", - model: "text-embedding-3-small", - dimensions: options.dimensions ?? 1536, - query: options.query, - results: search.results - }; - } - if (!existsSync14(workspace.knowledgeDbPath)) { - return { - provider: "openai", - model: "text-embedding-3-small", - dimensions: options.dimensions ?? 1536, - query: options.query, - results: [] - }; - } - return searchVectorIndex({ - ...options, - dbPath: workspace.knowledgeDbPath, - config: this.config() + _addCheck(check2) { + return new ZodNumber2({ + ...this._def, + checks: [...this._def.checks, check2] }); } - async search(options) { - const workspace = this.workspace; - if (this.isApiMode()) { - const items = await this.fetchCloudItems(); - return hybridSearchItems(items, options); - } - const legacyStorePath = legacyStorePathForRead(this.scope, workspace, options.legacyStorePath); - if (!existsSync14(workspace.knowledgeDbPath)) { - if (existsSync14(legacyStorePath)) { - return hybridSearchLegacyStore({ - ...options, - legacyStorePath, - config: this.config() - }); - } - return emptySearchResult(options.query, Math.max(1, Math.min(options.limit ?? 10, 100)), options.semantic === true || options.fake === true || Boolean(options.modelRef)); - } - return hybridSearch({ - ...options, - dbPath: workspace.knowledgeDbPath, - legacyStorePath, - config: this.config() + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) }); } - async retrieveContext(options) { - const workspace = this.workspace; - if (this.isApiMode()) { - const items = await this.fetchCloudItems(); - return retrieveKnowledgeContextFromItems(items, options); - } - const legacyStorePath = legacyStorePathForRead(this.scope, workspace, options.legacyStorePath); - if (!existsSync14(workspace.knowledgeDbPath)) { - if (existsSync14(legacyStorePath)) { - const search = await hybridSearchLegacyStore({ - ...options, - legacyStorePath, - config: this.config() - }); - return retrieveKnowledgeContextFromSearch(search, { - contextChars: options.contextChars - }); - } - return emptyContextPack(options.query, Math.max(1, Math.min(options.limit ?? 10, 100)), options.semantic === true || options.fake === true || Boolean(options.modelRef)); - } - return retrieveKnowledgeContext({ - ...options, - dbPath: workspace.knowledgeDbPath, - legacyStorePath, - config: this.config() + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) }); } - async contextPack(options) { - const workspace = this.workspace; - if (this.isApiMode()) { - const query2 = (options.query ?? options.topic ?? "").trim(); - if (query2 && options.source !== "loops" && options.source !== "runs") { - const items = await this.fetchCloudItems(); - const search = await hybridSearchItems(items, { ...options, query: query2 }); - const context = retrieveKnowledgeContextFromSearch(search, { contextChars: options.contextChars }); - return legacyAgentContextPack(options, context, this.safetyPolicy()); - } - return emptyAgentContextPack(options); - } - const legacyStorePath = legacyStorePathForRead(this.scope, workspace, options.legacyStorePath); - if (!existsSync14(workspace.knowledgeDbPath)) { - const query2 = (options.query ?? options.topic ?? "").trim(); - if (query2 && options.source !== "loops" && options.source !== "runs" && existsSync14(legacyStorePath)) { - const search = await hybridSearchLegacyStore({ - ...options, - query: query2, - legacyStorePath, - config: this.config() - }); - const context = retrieveKnowledgeContextFromSearch(search, { - contextChars: options.contextChars - }); - return legacyAgentContextPack(options, context, this.safetyPolicy()); - } - return emptyAgentContextPack(options); - } - return buildKnowledgeAgentContextPack({ - ...options, - dbPath: workspace.knowledgeDbPath, - legacyStorePath, - config: this.config(), - safetyPolicy: this.safetyPolicy() + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) }); } - async runPrompt(options) { - if (this.isApiMode()) { - const items = await this.fetchCloudItems(); - return runKnowledgePromptOverItems(items, { ...options, config: this.config() }); - } - const workspace = this.ensureWorkspace(); - const legacyStorePath = options.legacyStorePath ?? workspace.jsonStorePath; - if (!options.legacyStorePath) - ensureStore(legacyStorePath); - return runKnowledgePrompt({ - ...options, - dbPath: workspace.knowledgeDbPath, - legacyStorePath, - config: this.config() + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) }); } - async webSearch(options) { - const workspace = this.ensureWorkspace(); - return runProviderWebSearch({ - ...options, - dbPath: workspace.knowledgeDbPath, - config: this.config(), - safetyPolicy: this.safetyPolicy() + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) }); } - async machineTopology(options = {}) { - const workspace = this.workspace; - return discoverKnowledgeMachineTopology({ - ...options, - knowledge: { - scope: this.scope, - workspace_home: workspace.home - } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) }); } - async machinePreflight(options = {}) { - const workspace = this.workspace; - return preflightKnowledgeMachine({ - ...options, - knowledge: { - scope: this.scope, - workspace_home: workspace.home - } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) }); } - syncStatus() { - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) { - return emptySyncStatus({ - scope: this.scope, - workspaceHome: workspace.home - }); - } - return getKnowledgeSyncStatus({ - dbPath: workspace.knowledgeDbPath, - scope: this.scope, - workspaceHome: workspace.home + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) }); } - async syncDoctor(options = {}) { - const workspace = this.ensureWorkspace(); - migrateKnowledgeDb(workspace.knowledgeDbPath); - const status = this.syncStatus(); - const storage = this.storageContract(); - const validation = this.validateStorage(); - const artifactManifest = artifactManifestStatus(workspace.knowledgeDbPath, storage); - const machine = options.machine?.trim() || null; - const peerWorkspace = options.peerWorkspace?.trim() || null; - const warnings = []; - let resolvedRoute = null; - let resolvedWorkspace = null; - if (machine && !serviceMachineIsLocal(machine)) { - const route = await resolveKnowledgeMachineRoute({ - machineId: machine, - includeTailscale: options.includeTailscale - }); - resolvedRoute = routeSummary(route); - warnings.push(...route.warnings); + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } } - if (machine || peerWorkspace) { - const workspaceResolution = await resolveKnowledgeMachineWorkspace({ - machineId: machine ?? workspaceMachineId(workspace), - peerWorkspace, - includeTailscale: options.includeTailscale - }); - if (machine && !peerWorkspace && (resolvedRoute?.source === "raw" || !workspaceResolution.ok || !workspaceResolution.project_root)) { - const registryRow = findRegistryMachine(workspace.knowledgeDbPath, machine); - if (registryRow) { - if (resolvedRoute?.source === "raw" && registryRow.ssh_target) { - resolvedRoute = routeSummary(routeFromRegistry(registryRow, machine, { - target: resolvedRoute.target, - route: resolvedRoute.route, - targetKind: resolvedRoute.target_kind, - confidence: resolvedRoute.confidence, - source: resolvedRoute.source, - adapter: resolvedRoute.adapter, - evidence: resolvedRoute.evidence, - cacheability: resolvedRoute.cacheability, - warnings: [] - })); - } - if (!workspaceResolution.ok || !workspaceResolution.project_root) { - const registryWorkspace = workspaceFromRegistry(registryRow, machine, workspaceResolution); - if (registryWorkspace) { - resolvedWorkspace = workspaceSummary(registryWorkspace, registryWorkspace.project_root); - warnings.push(...registryWorkspace.warnings); - } - } - } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } - resolvedWorkspace = workspaceResolution.ok && workspaceResolution.project_root ? workspaceSummary(workspaceResolution, workspaceResolution.project_root) : resolvedWorkspace ?? { - ...workspaceSummary(workspaceResolution, peerWorkspace ?? ""), - project_root: workspaceResolution.project_root ?? peerWorkspace ?? "" - }; - warnings.push(...workspaceResolution.warnings); } - if (!validation.ok) - warnings.push(...validation.errors.map((error51) => `storage:${error51}`)); - const openFiles = openFilesBoundaryStatus(workspace.knowledgeDbPath, resolvedWorkspace); - if (!openFiles.ok) - warnings.push("open_files_boundary_raw_payload_sentinels"); - if (!artifactManifest.ok) - warnings.push(...artifactManifest.warnings); - const diagnosticFailures = resolvedWorkspace?.diagnostics.filter((entry) => entry.severity === "fail") ?? []; - const ok = validation.ok && artifactManifest.ok && openFiles.ok && diagnosticFailures.length === 0 && (resolvedWorkspace?.project_root !== "" || !resolvedWorkspace); - const recommendedCommands = doctorRecommendations({ - scope: this.scope, - machine, - peerWorkspace, - tables: options.tables, - resolvedWorkspace, - openConflicts: status.conflicts.open - }); - return { - ok, - read_only: true, - generated_at: new Date().toISOString(), - scope: this.scope, - workspace_home: workspace.home, - database: { - sqlite_schema_version: status.sqlite_schema_version, - table_counts: status.table_counts - }, - storage: { - contract: storage, - validation, - artifact_manifest: artifactManifest - }, - sync: { - machines: status.machines.total, - snapshots: status.snapshots.total, - clocks: status.clocks.total, - imports: status.imports.total, - open_conflicts: status.conflicts.open, - table_clocks: status.clocks.rows - }, - open_files: openFiles, - resolved_route: resolvedRoute, - resolved_workspace: resolvedWorkspace, - recommended_commands: recommendedCommands, - warnings: [...new Set(warnings)], - message: ok ? `Sync readiness ok: ${status.clocks.total} table clock(s), ${status.conflicts.open} open conflict(s)` : `Sync readiness needs attention: ${[...new Set(warnings)].join(", ") || "workspace diagnostics failed"}` - }; + return max; } - repairArtifactManifestKeys(options = {}) { - const workspace = this.ensureWorkspace(); - migrateKnowledgeDb(workspace.knowledgeDbPath); - const storage = this.storageContract(); - const storagePrefix = storagePrefixKey(storage); - const candidates = artifactManifestKeyRepairCandidates(workspace.knowledgeDbPath, storage); - const dryRun = options.dryRun === true || options.approveWrite !== true; - if (candidates.length === 0) { - return { - ok: true, - dry_run: dryRun, - approval_required: false, - storage_type: storage.storage_type, - storage_prefix: storagePrefix, - candidates, - repaired: 0, - audit_event_id: null, - message: "No legacy S3 artifact manifest keys found" - }; + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } } - if (options.dryRun === true) { - return { - ok: true, - dry_run: true, - approval_required: false, - storage_type: storage.storage_type, - storage_prefix: storagePrefix, - candidates, - repaired: 0, - audit_event_id: null, - message: `Would repair ${candidates.length} legacy S3 artifact manifest key(s)` - }; + return Number.isFinite(min) && Number.isFinite(max); + } +} +ZodNumber2.create = (params) => { + return new ZodNumber2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; + +class ZodBigInt2 extends ZodType2 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } } - if (options.approveWrite !== true || !options.approvedBy) { - return { - ok: false, - dry_run: true, - approval_required: true, - storage_type: storage.storage_type, - storage_prefix: storagePrefix, - candidates, - repaired: 0, - audit_event_id: null, - message: "Artifact key repair requires --approve-write and --approved-by <name>" - }; + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.bigint) { + return this._getInvalidInput(input); } - const db = openKnowledgeDb(workspace.knowledgeDbPath); - try { - const now = new Date().toISOString(); - const update = db.transaction((entries) => { - const statement = db.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"); - const currentRows = db.query("SELECT id, metadata_json FROM storage_objects").all(); - const metadataById = new Map(currentRows.map((row) => [row.id, parseMetadataJson(row.metadata_json)])); - for (const entry of entries) { - const metadata = metadataById.get(entry.id) ?? {}; - metadata.key = entry.repaired_key; - statement.run(JSON.stringify(metadata), now, entry.id); + let ctx = undefined; + const status = new ParseStatus; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + type: "bigint", + minimum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); } - }); - update(candidates); - const auditEventId = recordAuditEvent(db, { - event_type: "artifact_manifest_key_repair", - action: "storage.artifact_manifest.repair_keys", - target_uri: `knowledge-storage://${workspace.home}/storage_objects`, - decision: "allow", - metadata: { - approved_by: options.approvedBy, - repaired: candidates.length, - storage_type: storage.storage_type, - storage_prefix: storagePrefix, - artifact_uris: candidates.map((entry) => entry.artifact_uri) + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + type: "bigint", + maximum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (input.data % check2.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); } - }); - return { - ok: true, - dry_run: false, - approval_required: false, - storage_type: storage.storage_type, - storage_prefix: storagePrefix, - candidates, - repaired: candidates.length, - audit_event_id: auditEventId, - message: `Repaired ${candidates.length} legacy S3 artifact manifest key(s)` - }; - } finally { - db.close(); + } else { + util.assertNever(check2); + } } + return { status: status.value, value: input.data }; } - async createSyncSnapshot(options = {}) { - const workspace = this.ensureWorkspace(); - const topology = await this.machineTopology({ - includeTailscale: options.includeTailscale !== false - }); - return createKnowledgeSyncSnapshot({ - dbPath: workspace.knowledgeDbPath, - scope: this.scope, - workspaceHome: workspace.home, - storage: this.storageContract(), - topology, - machineId: options.machineId + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType }); + return INVALID; } - syncConflicts(options = {}) { - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) - return []; - return listKnowledgeSyncConflicts(workspace.knowledgeDbPath, options); + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); } - syncConflict(id) { - const workspace = this.ensureWorkspace(); - const conflict = getKnowledgeSyncConflict(workspace.knowledgeDbPath, id); - if (!conflict) - throw new Error(`Sync conflict not found: ${id}`); - return conflict; + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); } - proposeSyncConflictResolution(id) { - const workspace = this.ensureWorkspace(); - return proposeKnowledgeSyncConflictResolution(workspace.knowledgeDbPath, id); + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); } - async proposeSyncConflictResolutionWithAi(options) { - const workspace = this.ensureWorkspace(); - return proposeKnowledgeSyncConflictResolutionWithAi({ - dbPath: workspace.knowledgeDbPath, - id: options.id, - config: this.config(), - modelRef: options.modelRef, - fake: options.fake, - env: options.env - }); + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); } - resolveSyncConflict(options) { - const workspace = this.ensureWorkspace(); - const proposal = proposeKnowledgeSyncConflictResolution(workspace.knowledgeDbPath, options.id); - if (options.approveWrite !== true || !options.approvedBy) { - return { - ok: false, - approval_required: true, - conflict: proposal.conflict, - proposal, - message: "Sync conflict resolution requires --approve-write and --approved-by <name>" - }; - } - const conflict = resolveKnowledgeSyncConflict(workspace.knowledgeDbPath, { - id: options.id, - strategy: options.strategy ?? proposal.proposed_strategy, - approvedBy: options.approvedBy, - proposedPatchUri: options.proposedPatchUri - }); - const db = openKnowledgeDb(workspace.knowledgeDbPath); - try { - const auditEventId = recordAuditEvent(db, { - event_type: "sync_conflict_resolution", - action: "sync.conflict.resolve", - target_uri: `knowledge-sync-conflict://${options.id}`, - decision: "allow", - metadata: { - conflict_id: options.id, - entity_kind: conflict.entity_kind, - entity_id: conflict.entity_id, - strategy: conflict.resolution_strategy, - approved_by: conflict.approved_by, - proposed_patch_uri: conflict.proposed_patch_uri + setLimit(kind, value, inclusive, message) { + return new ZodBigInt2({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) } - }); - return { - ok: true, - approval_required: false, - conflict, - audit_event_id: auditEventId, - message: `Resolved sync conflict ${options.id}` - }; - } finally { - db.close(); - } - } - syncMachines() { - const workspace = this.workspace; - if (!existsSync14(workspace.knowledgeDbPath)) - return []; - return listKnowledgeMachines(workspace.knowledgeDbPath); - } - exportSyncBundle(options = {}) { - const workspace = this.ensureWorkspace(); - this.assertStorageValid("sync export"); - migrateKnowledgeDb(workspace.knowledgeDbPath); - return createKnowledgeSyncBundle({ - dbPath: workspace.knowledgeDbPath, - scope: this.scope, - workspaceHome: workspace.home, - storage: this.storageContract(), - machineId: options.machineId ?? null, - tables: options.tables, - includeArtifactContent: options.includeArtifactContent, - recordClocks: options.recordClocks !== false - }); - } - async importSyncBundle(options) { - const workspace = this.ensureWorkspace(); - this.assertStorageValid("sync import"); - migrateKnowledgeDb(workspace.knowledgeDbPath); - return applyKnowledgeSyncBundle({ - targetDbPath: workspace.knowledgeDbPath, - targetScope: this.scope, - targetWorkspaceHome: workspace.home, - targetStorage: this.storageContract(), - targetStore: this.artifactStore(), - bundle: options.bundle, - direction: options.direction ?? "import", - dryRun: options.dryRun, - localMachineId: options.machineId ?? null + ] }); } - async syncRemotePeer(options) { - const direction = options.direction ?? "both"; - const dryRun = options.dryRun === true; - const localWorkspace = this.ensureWorkspace(); - migrateKnowledgeDb(localWorkspace.knowledgeDbPath); - const tableArgs = options.tables?.length ? ["--tables", options.tables.join(",")] : []; - const artifactArgs = options.includeArtifactContent === false ? ["--no-artifact-content"] : []; - const scopeArgs = ["--scope", this.scope, "--json"]; - let resolvedMachine = await resolveKnowledgeMachineRoute({ - machineId: options.machine, - includeTailscale: options.includeTailscale - }); - let resolvedWorkspace = await resolveKnowledgeMachineWorkspace({ - machineId: options.machine, - peerWorkspace: options.peerWorkspace, - includeTailscale: options.includeTailscale + _addCheck(check2) { + return new ZodBigInt2({ + ...this._def, + checks: [...this._def.checks, check2] }); - if (!options.peerWorkspace && resolvedMachine.source === "raw" || !resolvedWorkspace.ok || !resolvedWorkspace.project_root) { - const registryRow = findRegistryMachine(localWorkspace.knowledgeDbPath, options.machine); - if (registryRow) { - if (!options.peerWorkspace && resolvedMachine.source === "raw" && registryRow.ssh_target) { - resolvedMachine = routeFromRegistry(registryRow, options.machine, resolvedMachine); - } - if (!resolvedWorkspace.ok || !resolvedWorkspace.project_root) { - const registryWorkspace = workspaceFromRegistry(registryRow, options.machine, resolvedWorkspace); - if (registryWorkspace) - resolvedWorkspace = registryWorkspace; - } - } - } - if (!resolvedWorkspace.ok || !resolvedWorkspace.project_root) { - throw new Error([ - `Unable to resolve peer workspace for ${options.machine}.`, - `Pass --peer-workspace <repo-or-knowledge-home> or configure workspace path mapping in machines.`, - resolvedWorkspace.warnings.length ? `Warnings: ${resolvedWorkspace.warnings.join(", ")}` : null - ].filter(Boolean).join(" ")); - } - const peerWorkspace = resolvedWorkspace.project_root; - const result = { - ok: true, - dry_run: dryRun, - direction, - transport: "ssh", - machine: options.machine, - resolved_machine: resolvedMachine.target, - resolved_route: routeSummary(resolvedMachine), - resolved_workspace: workspaceSummary(resolvedWorkspace, resolvedWorkspace.project_root), - peer_workspace: peerWorkspace, - message: "" - }; - let resolverEvidenceRecorded = false; - const recordResolverEvidence = () => { - if (dryRun || resolverEvidenceRecorded) - return; - recordKnowledgeMachineResolverEvidence(localWorkspace.knowledgeDbPath, { - machineId: options.machine, - route: resolvedMachine, - workspace: resolvedWorkspace - }); - resolverEvidenceRecorded = true; - }; - if (direction === "pull" || direction === "both") { - const remoteExport = remoteKnowledgeCommand(peerWorkspace, [ - "sync", - "export", - ...scopeArgs, - ...tableArgs, - ...artifactArgs - ]); - const raw = runSshCommand(options.machine, remoteExport, undefined, resolvedMachine); - const bundle = parseRemoteJson(options.machine, "sync export", raw); - assertRemoteSyncBundle(options.machine, bundle); - result.pull = await this.importSyncBundle({ - bundle, - dryRun, - direction: "pull", - machineId: options.machineId ?? null - }); - } - if (direction === "push" || direction === "both") { - recordResolverEvidence(); - const bundle = this.exportSyncBundle({ - machineId: options.machineId ?? null, - tables: options.tables, - includeArtifactContent: options.includeArtifactContent, - recordClocks: !dryRun - }); - const remoteImport = remoteKnowledgeCommand(peerWorkspace, [ - "sync", - "import", - ...scopeArgs, - ...dryRun ? ["--dry-run"] : [] - ]); - const applyResult = parseRemoteJson(options.machine, "sync import", runSshCommand(options.machine, remoteImport, JSON.stringify(bundle), resolvedMachine)); - assertRemoteSyncApplyResult(options.machine, applyResult); - result.push = applyResult; - } - result.ok = (result.pull?.ok ?? true) && (result.push?.ok ?? true); - recordResolverEvidence(); - result.message = [ - workspaceReadinessMessage(result.resolved_workspace), - result.pull ? `pull: ${result.pull.message}` : null, - result.push ? `push: ${result.push.message}` : null - ].filter(Boolean).join("; "); - return result; } - async syncPeer(options) { - const direction = options.direction ?? "both"; - const localWorkspace = this.ensureWorkspace(); - migrateKnowledgeDb(localWorkspace.knowledgeDbPath); - const peerWorkspaceInput = resolve5(options.peerWorkspace); - const peerWorkspace = resolvePeerWorkspace(peerWorkspaceInput); - migrateKnowledgeDb(peerWorkspace.knowledgeDbPath); - const peerConfig = readKnowledgeConfig(peerWorkspace.configPath); - const peerStorage = resolveStorageContract(peerConfig, peerWorkspace, this.scope); - const peerStore = createArtifactStore(peerConfig, peerWorkspace); - const localMachineId2 = options.machineId ?? workspaceMachineId(localWorkspace); - const peerMachineId = workspaceMachineId(peerWorkspace); - const resolvedWorkspace = await resolveKnowledgeMachineWorkspace({ - machineId: options.machineId ?? peerMachineId, - peerWorkspace: peerWorkspaceInput, - includeTailscale: false - }); - const localBundle = () => createKnowledgeSyncBundle({ - dbPath: localWorkspace.knowledgeDbPath, - scope: this.scope, - workspaceHome: localWorkspace.home, - storage: this.storageContract(), - machineId: localMachineId2, - tables: options.tables, - includeArtifactContent: options.includeArtifactContent, - recordClocks: options.dryRun !== true - }); - const peerBundle = () => createKnowledgeSyncBundle({ - dbPath: peerWorkspace.knowledgeDbPath, - scope: this.scope, - workspaceHome: peerWorkspace.home, - storage: peerStorage, - machineId: peerMachineId, - tables: options.tables, - includeArtifactContent: options.includeArtifactContent, - recordClocks: options.dryRun !== true + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) }); - const result = { - ok: true, - dry_run: options.dryRun === true, - direction, - resolved_workspace: workspaceSummary(resolvedWorkspace, resolvedWorkspace.project_root ?? peerWorkspaceInput), - message: "" - }; - if (direction === "pull" || direction === "both") { - result.pull = await applyKnowledgeSyncBundle({ - targetDbPath: localWorkspace.knowledgeDbPath, - targetScope: this.scope, - targetWorkspaceHome: localWorkspace.home, - targetStorage: this.storageContract(), - targetStore: this.artifactStore(), - bundle: peerBundle(), - targetBundle: localBundle(), - direction: "pull", - dryRun: options.dryRun, - localMachineId: localMachineId2 - }); - } - if (direction === "push" || direction === "both") { - result.push = await applyKnowledgeSyncBundle({ - targetDbPath: peerWorkspace.knowledgeDbPath, - targetScope: this.scope, - targetWorkspaceHome: peerWorkspace.home, - targetStorage: peerStorage, - targetStore: peerStore, - bundle: localBundle(), - targetBundle: peerBundle(), - direction: "push", - dryRun: options.dryRun, - localMachineId: peerMachineId - }); - } - result.ok = (result.pull?.ok ?? true) && (result.push?.ok ?? true); - result.message = [ - workspaceReadinessMessage(result.resolved_workspace), - result.pull ? `pull: ${result.pull.message}` : null, - result.push ? `push: ${result.push.message}` : null - ].filter(Boolean).join("; "); - return result; } -} -function createKnowledgeService(options = {}) { - return new KnowledgeService(options); -} - -// src/sdk.ts -function createKnowledgeClient(options = {}) { - const service = createKnowledgeService(options); - return { - unstable_service: service, - paths: () => service.paths(), - setup: (input = {}) => service.setup(input), - auth: { - status: (env = process.env) => service.authStatus(env), - login: (input, env = process.env) => service.saveAuth(input, env), - logout: (env = process.env) => service.clearAuth(env) - }, - storage: { - status: () => service.storageContract(), - validate: () => service.validateStorage(), - migrateLegacyPath: (input = {}) => service.migrateLegacyPath(input), - mergeLegacyPath: (input = {}) => service.mergeLegacyPath(input), - artifactStore: () => service.artifactStore() - }, - sync: { - status: () => service.syncStatus(), - doctor: (input = {}) => service.syncDoctor(input), - snapshot: (input = {}) => service.createSyncSnapshot(input), - conflicts: (input = {}) => service.syncConflicts(input), - conflict: (id) => service.syncConflict(id), - proposeConflictResolution: (id) => service.proposeSyncConflictResolution(id), - proposeConflictResolutionAi: (input) => service.proposeSyncConflictResolutionWithAi(input), - resolveConflict: (input) => service.resolveSyncConflict(input), - machines: () => service.syncMachines(), - exportBundle: (input = {}) => service.exportSyncBundle(input), - importBundle: (input) => service.importSyncBundle(input), - peer: (input) => service.syncPeer(input), - remotePeer: (input) => service.syncRemotePeer(input) - }, - items: { - store: () => service.itemStore(), - list: () => service.listItems(), - get: (idOrShort) => service.getItem(idOrShort), - create: (input) => service.createItem(input), - update: (idOrShort, patch) => service.updateItem(idOrShort, patch), - delete: (idOrShort) => service.deleteItem(idOrShort), - deleteMany: (idsOrShorts) => service.deleteItems(idsOrShorts) - }, - inventory: (input = {}) => service.resolveInventory(input), - db: { - init: () => service.initDb(), - stats: () => service.dbStats() - }, - wiki: { - init: () => service.initWiki(), - compile: (input = {}) => service.compileWiki(input), - fileAnswer: (input) => service.fileAnswer(input), - lint: () => service.lintWiki() - }, - appWiki: { - paths: () => service.paths(), - init: (input = {}) => service.initAppWiki(input), - notes: { - add: (input) => service.addAppWikiNote(input), - list: (input = {}) => service.listAppWikiNotes(input), - get: (id, input = {}) => service.getAppWikiNote(id, input) - }, - sources: { - add: (input) => service.addAppWikiSourceRef(input) - }, - search: (input) => service.searchAppWiki(input), - query: (input) => service.queryAppWiki(input) - }, - ingest: { - manifest: (input) => service.ingestManifest(input), - source: (sourceRef, purpose) => service.ingestSource(sourceRef, purpose), - rules: (input = {}) => service.importRulesProvenance(input) - }, - sources: { - resolve: (sourceRef, input = {}) => service.resolveSource(sourceRef, input), - consumeOutbox: (input) => service.consumeOutbox(input) - }, - reindex: { - health: (input = {}) => service.reindexHealth(input), - enqueue: (input = {}) => service.enqueueReindex(input), - refreshEmbeddings: (input = {}) => service.refreshEmbeddings(input) - }, - providers: { - status: (env = process.env) => service.providerStatus(env), - models: () => service.modelRegistry() - }, - embeddings: { - status: () => service.embeddingStatus(), - index: (input = {}) => service.indexEmbeddings(input), - search: (input) => service.semanticSearch(input) - }, - search: (input) => service.search(input), - retrieveContext: (input) => service.retrieveContext(input), - contextPack: (input) => service.contextPack(input), - context: { - pack: (input) => service.contextPack(input) - }, - ask: (prompt, input = {}) => service.runPrompt({ ...input, prompt }), - build: (prompt, input = {}) => service.runPrompt({ ...input, prompt }), - web: { - search: (input) => service.webSearch(input) - } - }; -} -var createKnowledgeSdk = createKnowledgeClient; -function withDefaultAllowGlobal(input, allowGlobal) { - if (allowGlobal !== true) - return input; - return { ...input ?? {}, allowGlobal: input?.allowGlobal ?? true }; -} -function createAppWikiScope(options = {}) { - const { allowGlobal, ...clientOptions } = options; - const client = createKnowledgeClient({ - ...clientOptions, - scope: clientOptions.scope ?? "project" - }); - return { - paths: () => client.appWiki.paths(), - init: (input = {}) => client.appWiki.init(withDefaultAllowGlobal(input, allowGlobal)), - notes: { - add: (input) => client.appWiki.notes.add(withDefaultAllowGlobal(input, allowGlobal)), - list: (input = {}) => client.appWiki.notes.list(input), - get: (id, input = {}) => client.appWiki.notes.get(id, input) - }, - sources: { - add: (input) => client.appWiki.sources.add(withDefaultAllowGlobal(input, allowGlobal)) - }, - search: (input) => client.appWiki.search(input), - query: (input) => client.appWiki.query(input) - }; -} -function openProjectWiki(options = {}) { - return createAppWikiScope({ ...options, scope: "project" }); -} -function openGlobalWiki(options) { - return createAppWikiScope({ ...options, scope: "global", allowGlobal: true }); -} -// node_modules/@hasna/contracts/dist/index.js -var __defProp5 = Object.defineProperty; -var __returnValue5 = (v) => v; -function __exportSetter5(name, newValue) { - this[name] = __returnValue5.bind(null, newValue); -} -var __export5 = (target, all) => { - for (var name in all) - __defProp5(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter5.bind(all, name) + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) }); -}; -var exports_external5 = {}; -__export5(exports_external5, { - void: () => voidType4, - util: () => util4, - unknown: () => unknownType4, - union: () => unionType4, - undefined: () => undefinedType4, - tuple: () => tupleType4, - transformer: () => effectsType4, - symbol: () => symbolType4, - string: () => stringType4, - strictObject: () => strictObjectType4, - setErrorMap: () => setErrorMap5, - set: () => setType4, - record: () => recordType4, - quotelessJson: () => quotelessJson4, - promise: () => promiseType4, - preprocess: () => preprocessType4, - pipeline: () => pipelineType4, - ostring: () => ostring4, - optional: () => optionalType4, - onumber: () => onumber4, - oboolean: () => oboolean4, - objectUtil: () => objectUtil4, - object: () => objectType4, - number: () => numberType4, - nullable: () => nullableType4, - null: () => nullType4, - never: () => neverType4, - nativeEnum: () => nativeEnumType4, - nan: () => nanType4, - map: () => mapType4, - makeIssue: () => makeIssue4, - literal: () => literalType4, - lazy: () => lazyType4, - late: () => late4, - isValid: () => isValid4, - isDirty: () => isDirty4, - isAsync: () => isAsync4, - isAborted: () => isAborted4, - intersection: () => intersectionType4, - instanceof: () => instanceOfType4, - getParsedType: () => getParsedType5, - getErrorMap: () => getErrorMap5, - function: () => functionType4, - enum: () => enumType4, - effect: () => effectsType4, - discriminatedUnion: () => discriminatedUnionType4, - defaultErrorMap: () => en_default5, - datetimeRegex: () => datetimeRegex4, - date: () => dateType4, - custom: () => custom5, - coerce: () => coerce4, - boolean: () => booleanType4, - bigint: () => bigIntType4, - array: () => arrayType4, - any: () => anyType4, - addIssueToContext: () => addIssueToContext4, - ZodVoid: () => ZodVoid5, - ZodUnknown: () => ZodUnknown5, - ZodUnion: () => ZodUnion5, - ZodUndefined: () => ZodUndefined5, - ZodType: () => ZodType5, - ZodTuple: () => ZodTuple5, - ZodTransformer: () => ZodEffects4, - ZodSymbol: () => ZodSymbol5, - ZodString: () => ZodString5, - ZodSet: () => ZodSet5, - ZodSchema: () => ZodType5, - ZodRecord: () => ZodRecord5, - ZodReadonly: () => ZodReadonly5, - ZodPromise: () => ZodPromise5, - ZodPipeline: () => ZodPipeline4, - ZodParsedType: () => ZodParsedType4, - ZodOptional: () => ZodOptional5, - ZodObject: () => ZodObject5, - ZodNumber: () => ZodNumber5, - ZodNullable: () => ZodNullable5, - ZodNull: () => ZodNull5, - ZodNever: () => ZodNever5, - ZodNativeEnum: () => ZodNativeEnum4, - ZodNaN: () => ZodNaN5, - ZodMap: () => ZodMap5, - ZodLiteral: () => ZodLiteral5, - ZodLazy: () => ZodLazy5, - ZodIssueCode: () => ZodIssueCode5, - ZodIntersection: () => ZodIntersection5, - ZodFunction: () => ZodFunction5, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind5, - ZodError: () => ZodError5, - ZodEnum: () => ZodEnum5, - ZodEffects: () => ZodEffects4, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion5, - ZodDefault: () => ZodDefault5, - ZodDate: () => ZodDate5, - ZodCatch: () => ZodCatch5, - ZodBranded: () => ZodBranded4, - ZodBoolean: () => ZodBoolean5, - ZodBigInt: () => ZodBigInt5, - ZodArray: () => ZodArray5, - ZodAny: () => ZodAny5, - Schema: () => ZodType5, - ParseStatus: () => ParseStatus4, - OK: () => OK4, - NEVER: () => NEVER5, - INVALID: () => INVALID4, - EMPTY_PATH: () => EMPTY_PATH4, - DIRTY: () => DIRTY4, - BRAND: () => BRAND4 -}); -var util4; -(function(util22) { - util22.assertEqual = (_) => {}; - function assertIs2(_arg) {} - util22.assertIs = assertIs2; - function assertNever2(_x) { - throw new Error; } - util22.assertNever = assertNever2; - util22.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util22.getValidEnumValues = (obj) => { - const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util22.objectValues(filtered); - }; - util22.objectValues = (obj) => { - return util22.objectKeys(obj).map(function(e) { - return obj[e]; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) }); - }; - util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { - const keys = []; - for (const key in object2) { - if (Object.prototype.hasOwnProperty.call(object2, key)) { - keys.push(key); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } } - return keys; - }; - util22.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues2(array2, separator = " | ") { - return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + return min; } - util22.joinValues = joinValues2; - util22.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util4 || (util4 = {})); -var objectUtil4; -(function(objectUtil22) { - objectUtil22.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; -})(objectUtil4 || (objectUtil4 = {})); -var ZodParsedType4 = util4.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType5 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType4.undefined; - case "string": - return ZodParsedType4.string; - case "number": - return Number.isNaN(data) ? ZodParsedType4.nan : ZodParsedType4.number; - case "boolean": - return ZodParsedType4.boolean; - case "function": - return ZodParsedType4.function; - case "bigint": - return ZodParsedType4.bigint; - case "symbol": - return ZodParsedType4.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType4.array; - } - if (data === null) { - return ZodParsedType4.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType4.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType4.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType4.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType4.date; + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } - return ZodParsedType4.object; - default: - return ZodParsedType4.unknown; + } + return max; } -}; -var ZodIssueCode5 = util4.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson4 = (obj) => { - const json3 = JSON.stringify(obj, null, 2); - return json3.replace(/"([^"]+)":/g, "$1:"); +} +ZodBigInt2.create = (params) => { + return new ZodBigInt2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); }; -class ZodError5 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; +class ZodBoolean2 extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); } - this.name = "ZodError"; - this.issues = issues; + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - format(_mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error51) => { - for (const issue2 of error51.issues) { - if (issue2.code === "invalid_union") { - issue2.unionErrors.map(processError); - } else if (issue2.code === "invalid_return_type") { - processError(issue2.returnTypeError); - } else if (issue2.code === "invalid_arguments") { - processError(issue2.argumentsError); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i++; - } +} +ZodBoolean2.create = (params) => { + return new ZodBoolean2({ + typeName: ZodFirstPartyTypeKind2.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; + +class ZodDate2 extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_date + }); + return INVALID; + } + const status = new ParseStatus; + let ctx = undefined; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.getTime() < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + message: check2.message, + inclusive: true, + exact: false, + minimum: check2.value, + type: "date" + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.getTime() > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + message: check2.message, + inclusive: true, + exact: false, + maximum: check2.value, + type: "date" + }); + status.dirty(); } + } else { + util.assertNever(check2); } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError5)) { - throw new Error(`Not a ZodError: ${value}`); } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; } - toString() { - return this.message; + _addCheck(check2) { + return new ZodDate2({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - get message() { - return JSON.stringify(this.issues, util4.jsonStringifyReplacer, 2); + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); } - get isEmpty() { - return this.issues.length === 0; + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); } - flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } } - return { formErrors, fieldErrors }; + return min != null ? new Date(min) : null; } - get formErrors() { - return this.flatten(); + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; } } -ZodError5.create = (issues) => { - const error51 = new ZodError5(issues); - return error51; +ZodDate2.create = (params) => { + return new ZodDate2({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind2.ZodDate, + ...processCreateParams(params) + }); }; -var errorMap4 = (issue2, _ctx) => { - let message; - switch (issue2.code) { - case ZodIssueCode5.invalid_type: - if (issue2.received === ZodParsedType4.undefined) { - message = "Required"; - } else { - message = `Expected ${issue2.expected}, received ${issue2.received}`; - } - break; - case ZodIssueCode5.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util4.jsonStringifyReplacer)}`; - break; - case ZodIssueCode5.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util4.joinValues(issue2.keys, ", ")}`; - break; - case ZodIssueCode5.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode5.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util4.joinValues(issue2.options)}`; - break; - case ZodIssueCode5.invalid_enum_value: - message = `Invalid enum value. Expected ${util4.joinValues(issue2.options)}, received '${issue2.received}'`; - break; - case ZodIssueCode5.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode5.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode5.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode5.invalid_string: - if (typeof issue2.validation === "object") { - if ("includes" in issue2.validation) { - message = `Invalid input: must include "${issue2.validation.includes}"`; - if (typeof issue2.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; - } - } else if ("startsWith" in issue2.validation) { - message = `Invalid input: must start with "${issue2.validation.startsWith}"`; - } else if ("endsWith" in issue2.validation) { - message = `Invalid input: must end with "${issue2.validation.endsWith}"`; - } else { - util4.assertNever(issue2.validation); - } - } else if (issue2.validation !== "regex") { - message = `Invalid ${issue2.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode5.too_small: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "bigint") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode5.too_big: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "bigint") - message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode5.custom: - message = `Invalid input`; - break; - case ZodIssueCode5.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode5.not_multiple_of: - message = `Number must be a multiple of ${issue2.multipleOf}`; - break; - case ZodIssueCode5.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util4.assertNever(issue2); + +class ZodSymbol2 extends ZodType2 { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - return { message }; -}; -var en_default5 = errorMap4; -var overrideErrorMap4 = en_default5; -function setErrorMap5(map2) { - overrideErrorMap4 = map2; -} -function getErrorMap5() { - return overrideErrorMap4; } -var makeIssue4 = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map2 of maps) { - errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; +ZodSymbol2.create = (params) => { + return new ZodSymbol2({ + typeName: ZodFirstPartyTypeKind2.ZodSymbol, + ...processCreateParams(params) + }); +}; + +class ZodUndefined2 extends ZodType2 { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; +} +ZodUndefined2.create = (params) => { + return new ZodUndefined2({ + typeName: ZodFirstPartyTypeKind2.ZodUndefined, + ...processCreateParams(params) + }); }; -var EMPTY_PATH4 = []; -function addIssueToContext4(ctx, issueData) { - const overrideMap = getErrorMap5(); - const issue2 = makeIssue4({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default5 ? undefined : en_default5 - ].filter((x) => !!x) + +class ZodNull2 extends ZodType2 { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +} +ZodNull2.create = (params) => { + return new ZodNull2({ + typeName: ZodFirstPartyTypeKind2.ZodNull, + ...processCreateParams(params) }); - ctx.common.issues.push(issue2); +}; + +class ZodAny2 extends ZodType2 { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } } +ZodAny2.create = (params) => { + return new ZodAny2({ + typeName: ZodFirstPartyTypeKind2.ZodAny, + ...processCreateParams(params) + }); +}; -class ParseStatus4 { +class ZodUnknown2 extends ZodType2 { constructor() { - this.value = "valid"; + super(...arguments); + this._unknown = true; } - dirty() { - if (this.value === "valid") - this.value = "dirty"; + _parse(input) { + return OK(input.data); } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; +} +ZodUnknown2.create = (params) => { + return new ZodUnknown2({ + typeName: ZodFirstPartyTypeKind2.ZodUnknown, + ...processCreateParams(params) + }); +}; + +class ZodNever2 extends ZodType2 { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID4; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); +} +ZodNever2.create = (params) => { + return new ZodNever2({ + typeName: ZodFirstPartyTypeKind2.ZodNever, + ...processCreateParams(params) + }); +}; + +class ZodVoid2 extends ZodType2 { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; } - return { status: status.value, value: arrayValue }; + return OK(input.data); } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value +} +ZodVoid2.create = (params) => { + return new ZodVoid2({ + typeName: ZodFirstPartyTypeKind2.ZodVoid, + ...processCreateParams(params) + }); +}; + +class ZodArray2 extends ZodType2 { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType }); + return INVALID; } - return ParseStatus4.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID4; - if (value.status === "aborted") - return INVALID4; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, + minimum: tooSmall ? def.exactLength.value : undefined, + maximum: tooBig ? def.exactLength.value : undefined, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; } } - return { status: status.value, value: finalObject }; - } -} -var INVALID4 = Object.freeze({ - status: "aborted" -}); -var DIRTY4 = (value) => ({ status: "dirty", value }); -var OK4 = (value) => ({ status: "valid", value }); -var isAborted4 = (x) => x.status === "aborted"; -var isDirty4 = (x) => x.status === "dirty"; -var isValid4 = (x) => x.status === "valid"; -var isAsync4 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil4; -(function(errorUtil22) { - errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil4 || (errorUtil4 = {})); - -class ParseInputLazyPath4 { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); } } - return this._cachedPath; - } -} -var handleResult4 = (ctx, result) => { - if (isValid4(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error51 = new ZodError5(ctx.common.issues); - this._error = error51; - return this._error; + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); } - }; - } -}; -function processCreateParams4(params) { - if (!params) - return {}; - const { errorMap: errorMap22, invalid_type_error, required_error, description } = params; - if (errorMap22 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap22) - return { errorMap: errorMap22, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -class ZodType5 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType5(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType5(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); } - _processInputParams(input) { - return { - status: new ParseStatus4, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType5(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; + get element() { + return this._def.type; } - _parseSync(input) { - const result = this._parse(input); - if (isAsync4(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; + min(minLength, message) { + return new ZodArray2({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); + max(maxLength, message) { + return new ZodArray2({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; + length(len, message) { + return new ZodArray2({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType5(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult4(ctx, result); + nonempty(message) { + return this.min(1, message); } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType5(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid4(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } +} +ZodArray2.create = (schema, params) => { + return new ZodArray2({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind2.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject2) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema)); } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid4(result) ? { - value: result.value - } : { - issues: ctx.common.issues + return new ZodObject2({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray2) { + return new ZodArray2({ + ...schema._def, + type: deepPartialify(schema.element) }); + } else if (schema instanceof ZodOptional2) { + return ZodOptional2.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable2) { + return ZodNullable2.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple2) { + return ZodTuple2.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; +} + +class ZodObject2 extends ZodType2 { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType5(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync4(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult4(ctx, result); + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; } - refine(check2, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check2(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode5.custom, - ...getIssueProperties(val) + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } } - if (!result) { - setError(); - return false; - } else { - return true; + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever2) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode2.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") {} else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } - }); - } - refinement(check2, refinementData) { - return this._refinement((val, ctx) => { - if (!check2(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); } - }); - } - _refinement(refinement) { - return new ZodEffects4({ - schema: this, - typeName: ZodFirstPartyTypeKind5.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional5.create(this, this._def); - } - nullable() { - return ZodNullable5.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray5.create(this); - } - promise() { - return ZodPromise5.create(this, this._def); - } - or(option) { - return ZodUnion5.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection5.create(this, incoming, this._def); + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } } - transform(transform2) { - return new ZodEffects4({ - ...processCreateParams4(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind5.ZodEffects, - effect: { type: "transform", transform: transform2 } - }); + get shape() { + return this._def.shape(); } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault5({ - ...processCreateParams4(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind5.ZodDefault + strict(message) { + errorUtil.errToObj; + return new ZodObject2({ + ...this._def, + unknownKeys: "strict", + ...message !== undefined ? { + errorMap: (issue2, ctx) => { + const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; + if (issue2.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} }); } - brand() { - return new ZodBranded4({ - typeName: ZodFirstPartyTypeKind5.ZodBranded, - type: this, - ...processCreateParams4(this._def) + strip() { + return new ZodObject2({ + ...this._def, + unknownKeys: "strip" }); } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch5({ - ...processCreateParams4(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind5.ZodCatch + passthrough() { + return new ZodObject2({ + ...this._def, + unknownKeys: "passthrough" }); } - describe(description) { - const This = this.constructor; - return new This({ + extend(augmentation) { + return new ZodObject2({ ...this._def, - description + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) }); } - pipe(target) { - return ZodPipeline4.create(this, target); - } - readonly() { - return ZodReadonly5.create(this); + merge(merging) { + const merged = new ZodObject2({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind2.ZodObject + }); + return merged; } - isOptional() { - return this.safeParse(undefined).success; + setKey(key, schema) { + return this.augment({ [key]: schema }); } - isNullable() { - return this.safeParse(null).success; + catchall(index) { + return new ZodObject2({ + ...this._def, + catchall: index + }); } -} -var cuidRegex4 = /^c[^\s-]{8,}$/i; -var cuid2Regex4 = /^[0-9a-z]+$/; -var ulidRegex4 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex4 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex4 = /^[a-z0-9_-]{21}$/i; -var jwtRegex4 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex4 = /^[-+]?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)?)??$/; -var emailRegex4 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex4 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex4; -var ipv4Regex4 = /^(?:(?: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])$/; -var ipv4CidrRegex4 = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex4 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex4 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex4 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex4 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource4 = `((\\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])))`; -var dateRegex4 = new RegExp(`^${dateRegexSource4}$`); -function timeRegexSource4(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject2({ + ...this._def, + shape: () => shape + }); } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex4(args) { - return new RegExp(`^${timeRegexSource4(args)}$`); -} -function datetimeRegex4(args) { - let regex = `${dateRegexSource4}T${timeRegexSource4(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP4(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4Regex4.test(ip)) { - return true; + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject2({ + ...this._def, + shape: () => shape + }); } - if ((version2 === "v6" || !version2) && ipv6Regex4.test(ip)) { - return true; + deepPartial() { + return deepPartialify(this); } - return false; -} -function isValidJWT5(jwt2, alg) { - if (!jwtRegex4.test(jwt2)) - return false; - try { - const [header] = jwt2.split("."); - if (!header) - return false; - const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base643)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new ZodObject2({ + ...this._def, + shape: () => newShape + }); } -} -function isValidCidr4(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4CidrRegex4.test(ip)) { - return true; + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional2) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new ZodObject2({ + ...this._def, + shape: () => newShape + }); } - if ((version2 === "v6" || !version2) && ipv6CidrRegex4.test(ip)) { - return true; + keyof() { + return createZodEnum(util.objectKeys(this.shape)); } - return false; } +ZodObject2.create = (shape, params) => { + return new ZodObject2({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject2.strictCreate = (shape, params) => { + return new ZodObject2({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject2.lazycreate = (shape, params) => { + return new ZodObject2({ + shape, + unknownKeys: "strip", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams(params) + }); +}; -class ZodString5 extends ZodType5 { +class ZodUnion2 extends ZodType2 { _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext4(ctx2, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.string, - received: ctx2.parsedType - }); - return INVALID4; - } - const status = new ParseStatus4; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.length < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.length > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "length") { - const tooBig = input.data.length > check2.value; - const tooSmall = input.data.length < check2.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } else if (tooSmall) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } - status.dirty(); - } - } else if (check2.kind === "email") { - if (!emailRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "email", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "emoji") { - if (!emojiRegex4) { - emojiRegex4 = new RegExp(_emojiRegex4, "u"); - } - if (!emojiRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "emoji", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "uuid") { - if (!uuidRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "uuid", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "nanoid") { - if (!nanoidRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "nanoid", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid") { - if (!cuidRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "cuid", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid2") { - if (!cuid2Regex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "cuid2", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ulid") { - if (!ulidRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "ulid", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "url", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "regex") { - check2.regex.lastIndex = 0; - const testResult = check2.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "regex", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "trim") { - input.data = input.data.trim(); - } else if (check2.kind === "includes") { - if (!input.data.includes(check2.value, check2.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_string, - validation: { includes: check2.value, position: check2.position }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check2.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check2.kind === "startsWith") { - if (!input.data.startsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_string, - validation: { startsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "endsWith") { - if (!input.data.endsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_string, - validation: { endsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "datetime") { - const regex = datetimeRegex4(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_string, - validation: "datetime", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "date") { - const regex = dateRegex4; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_string, - validation: "date", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "time") { - const regex = timeRegex4(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_string, - validation: "time", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "duration") { - if (!durationRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "duration", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ip") { - if (!isValidIP4(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "ip", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "jwt") { - if (!isValidJWT5(input.data, check2.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "jwt", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; } - } else if (check2.kind === "cidr") { - if (!isValidCidr4(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "cidr", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; } - } else if (check2.kind === "base64") { - if (!base64Regex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "base64", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); + } + const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; } - } else if (check2.kind === "base64url") { - if (!base64urlRegex4.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - validation: "base64url", - code: ZodIssueCode5.invalid_string, - message: check2.message - }); - status.dirty(); + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); } - } else { - util4.assertNever(check2); } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError2(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_union, + unionErrors + }); + return INVALID; } - return { status: status.value, value: input.data }; } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode5.invalid_string, - ...errorUtil4.errToObj(message) - }); + get options() { + return this._def.options; } - _addCheck(check2) { - return new ZodString5({ - ...this._def, - checks: [...this._def.checks, check2] - }); +} +ZodUnion2.create = (types, params) => { + return new ZodUnion2({ + options: types, + typeName: ZodFirstPartyTypeKind2.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy2) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral2) { + return [type.value]; + } else if (type instanceof ZodEnum2) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault2) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined2) { + return [undefined]; + } else if (type instanceof ZodNull2) { + return [null]; + } else if (type instanceof ZodOptional2) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable2) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly2) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch2) { + return getDiscriminator(type._def.innerType); + } else { + return []; } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil4.errToObj(message) }); +}; + +class ZodDiscriminatedUnion2 extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil4.errToObj(message) }); + get discriminator() { + return this._def.discriminator; } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil4.errToObj(message) }); + get options() { + return this._def.options; } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil4.errToObj(message) }); + get optionsMap() { + return this._def.optionsMap; } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil4.errToObj(message) }); + static create(discriminator, options, params) { + const optionsMap = new Map; + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion2({ + typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil4.errToObj(message) }); +} +function mergeValues2(a, b) { + const aType = getParsedType2(a); + const bType = getParsedType2(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues2(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0;index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues2(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil4.errToObj(message) }); +} + +class ZodIntersection2 extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues2(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil4.errToObj(message) }); +} +ZodIntersection2.create = (left, right, params) => { + return new ZodIntersection2({ + left, + right, + typeName: ZodFirstPartyTypeKind2.ZodIntersection, + ...processCreateParams(params) + }); +}; + +class ZodTuple2 extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil4.errToObj(message) }); + get items() { + return this._def.items; } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil4.errToObj(message) + rest(rest) { + return new ZodTuple2({ + ...this._def, + rest }); } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil4.errToObj(options) }); +} +ZodTuple2.create = (schemas3, params) => { + if (!Array.isArray(schemas3)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil4.errToObj(options) }); + return new ZodTuple2({ + items: schemas3, + typeName: ZodFirstPartyTypeKind2.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; + +class ZodRecord2 extends ZodType2 { + get keySchema() { + return this._def.keyType; } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil4.errToObj(options) }); + get valueSchema() { + return this._def.valueType; } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType }); + return INVALID; } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil4.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data }); } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil4.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil4.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil4.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil4.errToObj(options?.message) - }); + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil4.errToObj(message) - }); + get element() { + return this._def.valueType; } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil4.errToObj(message) + static create(first, second, third) { + if (second instanceof ZodType2) { + return new ZodRecord2({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind2.ZodRecord, + ...processCreateParams(third) + }); + } + return new ZodRecord2({ + keyType: ZodString2.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind2.ZodRecord, + ...processCreateParams(second) }); } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil4.errToObj(message) - }); +} + +class ZodMap2 extends ZodType2 { + get keySchema() { + return this._def.keyType; } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil4.errToObj(message) - }); + get valueSchema() { + return this._def.valueType; } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil4.errToObj(message) + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; }); + if (ctx.common.async) { + const finalMap = new Map; + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = new Map; + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } } - nonempty(message) { - return this.min(1, errorUtil4.errToObj(message)); - } - trim() { - return new ZodString5({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); +} +ZodMap2.create = (keyType, valueType, params) => { + return new ZodMap2({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind2.ZodMap, + ...processCreateParams(params) + }); +}; + +class ZodSet2 extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = new Set; + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } } - toLowerCase() { - return new ZodString5({ + min(minSize, message) { + return new ZodSet2({ ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] + minSize: { value: minSize, message: errorUtil.toString(message) } }); } - toUpperCase() { - return new ZodString5({ + max(maxSize, message) { + return new ZodSet2({ ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] + maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; + size(size, message) { + return this.min(size, message).max(size, message); } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; + nonempty(message) { + return this.min(1, message); } } -ZodString5.create = (params) => { - return new ZodString5({ - checks: [], - typeName: ZodFirstPartyTypeKind5.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams4(params) +ZodSet2.create = (valueType, params) => { + return new ZodSet2({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind2.ZodSet, + ...processCreateParams(params) }); }; -function floatSafeRemainder5(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -class ZodNumber5 extends ZodType5 { +class ZodFunction2 extends ZodType2 { constructor() { super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; + this.validate = this.implement; } _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext4(ctx2, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.number, - received: ctx2.parsedType + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType }); - return INVALID4; + return INVALID; } - let ctx = undefined; - const status = new ParseStatus4; - for (const check2 of this._def.checks) { - if (check2.kind === "int") { - if (!util4.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: "integer", - received: "float", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - minimum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); + function makeArgsIssue(args, error51) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), + issueData: { + code: ZodIssueCode2.invalid_arguments, + argumentsError: error51 } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - maximum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); + }); + } + function makeReturnsIssue(returns, error51) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), + issueData: { + code: ZodIssueCode2.invalid_return_type, + returnTypeError: error51 } - } else if (check2.kind === "multipleOf") { - if (floatSafeRemainder5(input.data, check2.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise2) { + const me = this; + return OK(async function(...args) { + const error51 = new ZodError2([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error51.addIssue(makeArgsIssue(args, e)); + throw error51; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error51.addIssue(makeReturnsIssue(result, e)); + throw error51; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); } - } else if (check2.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.not_finite, - message: check2.message - }); - status.dirty(); + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); } - } else { - util4.assertNever(check2); - } + return parsedReturns.data; + }); } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil4.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil4.toString(message)); } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil4.toString(message)); + parameters() { + return this._def.args; } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil4.toString(message)); + returnType() { + return this._def.returns; } - setLimit(kind, value, inclusive, message) { - return new ZodNumber5({ + args(...items) { + return new ZodFunction2({ ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil4.toString(message) - } - ] + args: ZodTuple2.create(items).rest(ZodUnknown2.create()) }); } - _addCheck(check2) { - return new ZodNumber5({ + returns(returnType) { + return new ZodFunction2({ ...this._def, - checks: [...this._def.checks, check2] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil4.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil4.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil4.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil4.toString(message) + returns: returnType }); } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil4.toString(message) - }); + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil4.toString(message) - }); + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil4.toString(message) + static create(args, returns, params) { + return new ZodFunction2({ + args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), + returns: returns || ZodUnknown2.create(), + typeName: ZodFirstPartyTypeKind2.ZodFunction, + ...processCreateParams(params) }); } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil4.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil4.toString(message) - }); +} + +class ZodLazy2 extends ZodType2 { + get schema() { + return this._def.getter(); } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } +} +ZodLazy2.create = (getter, params) => { + return new ZodLazy2({ + getter, + typeName: ZodFirstPartyTypeKind2.ZodLazy, + ...processCreateParams(params) + }); +}; + +class ZodLiteral2 extends ZodType2 { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_literal, + expected: this._def.value + }); + return INVALID; } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util4.isInteger(ch.value)); + return { status: "valid", value: input.data }; } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); + get value() { + return this._def.value; } } -ZodNumber5.create = (params) => { - return new ZodNumber5({ - checks: [], - typeName: ZodFirstPartyTypeKind5.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams4(params) +ZodLiteral2.create = (value, params) => { + return new ZodLiteral2({ + value, + typeName: ZodFirstPartyTypeKind2.ZodLiteral, + ...processCreateParams(params) }); }; +function createZodEnum(values, params) { + return new ZodEnum2({ + values, + typeName: ZodFirstPartyTypeKind2.ZodEnum, + ...processCreateParams(params) + }); +} -class ZodBigInt5 extends ZodType5 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } +class ZodEnum2 extends ZodType2 { _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode2.invalid_type + }); + return INVALID; } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.bigint) { - return this._getInvalidInput(input); + if (!this._cache) { + this._cache = new Set(this._def.values); } - let ctx = undefined; - const status = new ParseStatus4; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - type: "bigint", - minimum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - type: "bigint", - maximum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (input.data % check2.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else { - util4.assertNever(check2); - } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_enum_value, + options: expectedValues + }); + return INVALID; } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.bigint, - received: ctx.parsedType - }); - return INVALID4; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil4.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil4.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil4.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil4.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt5({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil4.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodBigInt5({ - ...this._def, - checks: [...this._def.checks, check2] - }); + return OK(input.data); } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil4.toString(message) - }); + get options() { + return this._def.values; } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil4.toString(message) - }); + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil4.toString(message) - }); + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil4.toString(message) + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum2.create(values, { + ...this._def, + ...newDef }); } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil4.toString(message) + exclude(values, newDef = this._def) { + return ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef }); } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } +} +ZodEnum2.create = createZodEnum; + +class ZodNativeEnum extends ZodType2 { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode2.invalid_type + }); + return INVALID; } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); } - return max; + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; } } -ZodBigInt5.create = (params) => { - return new ZodBigInt5({ - checks: [], - typeName: ZodFirstPartyTypeKind5.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams4(params) +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, + ...processCreateParams(params) }); }; -class ZodBoolean5 extends ZodType5 { +class ZodPromise2 extends ZodType2 { + unwrap() { + return this._def.type; + } _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.boolean, + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.promise, received: ctx.parsedType }); - return INVALID4; + return INVALID; } - return OK4(input.data); + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); } } -ZodBoolean5.create = (params) => { - return new ZodBoolean5({ - typeName: ZodFirstPartyTypeKind5.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams4(params) +ZodPromise2.create = (schema, params) => { + return new ZodPromise2({ + type: schema, + typeName: ZodFirstPartyTypeKind2.ZodPromise, + ...processCreateParams(params) }); }; -class ZodDate5 extends ZodType5 { +class ZodEffects extends ZodType2 { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext4(ctx2, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.date, - received: ctx2.parsedType - }); - return INVALID4; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext4(ctx2, { - code: ZodIssueCode5.invalid_date - }); - return INVALID4; - } - const status = new ParseStatus4; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.getTime() < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - message: check2.message, - inclusive: true, - exact: false, - minimum: check2.value, - type: "date" - }); + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { status.dirty(); } - } else if (check2.kind === "max") { - if (input.data.getTime() > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - message: check2.message, - inclusive: true, - exact: false, - maximum: check2.value, - type: "date" + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx }); - status.dirty(); - } + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); } else { - util4.assertNever(check2); + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; } } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check2) { - return new ZodDate5({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil4.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil4.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); } } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); } } - return max != null ? new Date(max) : null; + util.assertNever(effect); } } -ZodDate5.create = (params) => { - return new ZodDate5({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind5.ZodDate, - ...processCreateParams4(params) +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect, + ...processCreateParams(params) }); }; - -class ZodSymbol5 extends ZodType5 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.symbol, - received: ctx.parsedType - }); - return INVALID4; - } - return OK4(input.data); - } -} -ZodSymbol5.create = (params) => { - return new ZodSymbol5({ - typeName: ZodFirstPartyTypeKind5.ZodSymbol, - ...processCreateParams4(params) +ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess2 }, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + ...processCreateParams(params) }); }; -class ZodUndefined5 extends ZodType5 { +class ZodOptional2 extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.undefined, - received: ctx.parsedType - }); - return INVALID4; + if (parsedType2 === ZodParsedType.undefined) { + return OK(undefined); } - return OK4(input.data); + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; } } -ZodUndefined5.create = (params) => { - return new ZodUndefined5({ - typeName: ZodFirstPartyTypeKind5.ZodUndefined, - ...processCreateParams4(params) +ZodOptional2.create = (type, params) => { + return new ZodOptional2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodOptional, + ...processCreateParams(params) }); }; -class ZodNull5 extends ZodType5 { +class ZodNullable2 extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.null, - received: ctx.parsedType - }); - return INVALID4; + if (parsedType2 === ZodParsedType.null) { + return OK(null); } - return OK4(input.data); - } -} -ZodNull5.create = (params) => { - return new ZodNull5({ - typeName: ZodFirstPartyTypeKind5.ZodNull, - ...processCreateParams4(params) - }); -}; - -class ZodAny5 extends ZodType5 { - constructor() { - super(...arguments); - this._any = true; + return this._def.innerType._parse(input); } - _parse(input) { - return OK4(input.data); + unwrap() { + return this._def.innerType; } } -ZodAny5.create = (params) => { - return new ZodAny5({ - typeName: ZodFirstPartyTypeKind5.ZodAny, - ...processCreateParams4(params) +ZodNullable2.create = (type, params) => { + return new ZodNullable2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodNullable, + ...processCreateParams(params) }); }; -class ZodUnknown5 extends ZodType5 { - constructor() { - super(...arguments); - this._unknown = true; - } +class ZodDefault2 extends ZodType2 { _parse(input) { - return OK4(input.data); + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; } } -ZodUnknown5.create = (params) => { - return new ZodUnknown5({ - typeName: ZodFirstPartyTypeKind5.ZodUnknown, - ...processCreateParams4(params) +ZodDefault2.create = (type, params) => { + return new ZodDefault2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) }); }; -class ZodNever5 extends ZodType5 { +class ZodCatch2 extends ZodType2 { _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.never, - received: ctx.parsedType + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } }); - return INVALID4; + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError2(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError2(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; } } -ZodNever5.create = (params) => { - return new ZodNever5({ - typeName: ZodFirstPartyTypeKind5.ZodNever, - ...processCreateParams4(params) +ZodCatch2.create = (type, params) => { + return new ZodCatch2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) }); }; -class ZodVoid5 extends ZodType5 { +class ZodNaN2 extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.undefined) { + if (parsedType2 !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.void, + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.nan, received: ctx.parsedType }); - return INVALID4; + return INVALID; } - return OK4(input.data); + return { status: "valid", value: input.data }; } } -ZodVoid5.create = (params) => { - return new ZodVoid5({ - typeName: ZodFirstPartyTypeKind5.ZodVoid, - ...processCreateParams4(params) +ZodNaN2.create = (params) => { + return new ZodNaN2({ + typeName: ZodFirstPartyTypeKind2.ZodNaN, + ...processCreateParams(params) }); }; +var BRAND = Symbol("zod_brand"); -class ZodArray5 extends ZodType5 { +class ZodBranded extends ZodType2 { _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType4.array) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.array, - received: ctx.parsedType - }); - return INVALID4; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext4(ctx, { - code: tooBig ? ZodIssueCode5.too_big : ZodIssueCode5.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath4(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus4.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath4(ctx, item, ctx.path, i)); - }); - return ParseStatus4.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray5({ - ...this._def, - minLength: { value: minLength, message: errorUtil4.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray5({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil4.toString(message) } - }); - } - length(len, message) { - return new ZodArray5({ - ...this._def, - exactLength: { value: len, message: errorUtil4.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray5.create = (schema, params) => { - return new ZodArray5({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind5.ZodArray, - ...processCreateParams4(params) - }); -}; -function deepPartialify4(schema) { - if (schema instanceof ZodObject5) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional5.create(deepPartialify4(fieldSchema)); - } - return new ZodObject5({ - ...schema._def, - shape: () => newShape + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx }); - } else if (schema instanceof ZodArray5) { - return new ZodArray5({ - ...schema._def, - type: deepPartialify4(schema.element) - }); - } else if (schema instanceof ZodOptional5) { - return ZodOptional5.create(deepPartialify4(schema.unwrap())); - } else if (schema instanceof ZodNullable5) { - return ZodNullable5.create(deepPartialify4(schema.unwrap())); - } else if (schema instanceof ZodTuple5) { - return ZodTuple5.create(schema.items.map((item) => deepPartialify4(item))); - } else { - return schema; + } + unwrap() { + return this._def.type; } } -class ZodObject5 extends ZodType5 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util4.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } +class ZodPipeline extends ZodType2 { _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext4(ctx2, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.object, - received: ctx2.parsedType - }); - return INVALID4; - } const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever5 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath4(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever5) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.unrecognized_keys, - keys: extraKeys - }); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } + }; + return handleAsync(); } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath4(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx }); } } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus4.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus4.mergeObjectSync(status, pairs); - } } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil4.errToObj; - return new ZodObject5({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue2, ctx) => { - const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; - if (issue2.code === "unrecognized_keys") - return { - message: errorUtil4.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind2.ZodPipeline }); } - strip() { - return new ZodObject5({ - ...this._def, - unknownKeys: "strip" - }); +} + +class ZodReadonly2 extends ZodType2 { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } - passthrough() { - return new ZodObject5({ - ...this._def, - unknownKeys: "passthrough" - }); + unwrap() { + return this._def.innerType; } - extend(augmentation) { - return new ZodObject5({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) +} +ZodReadonly2.create = (type, params) => { + return new ZodReadonly2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodReadonly, + ...processCreateParams(params) + }); +}; +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom2(check2, _params = {}, fatal) { + if (check2) + return ZodAny2.create().superRefine((data, ctx) => { + const r = check2(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; }); - } - merge(merging) { - const merged = new ZodObject5({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind5.ZodObject + return ZodAny2.create(); +} +var late = { + object: ZodObject2.lazycreate +}; +var ZodFirstPartyTypeKind2; +(function(ZodFirstPartyTypeKind22) { + ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom2((data) => data instanceof cls, params); +var stringType = ZodString2.create; +var numberType = ZodNumber2.create; +var nanType = ZodNaN2.create; +var bigIntType = ZodBigInt2.create; +var booleanType = ZodBoolean2.create; +var dateType = ZodDate2.create; +var symbolType = ZodSymbol2.create; +var undefinedType = ZodUndefined2.create; +var nullType = ZodNull2.create; +var anyType = ZodAny2.create; +var unknownType = ZodUnknown2.create; +var neverType = ZodNever2.create; +var voidType = ZodVoid2.create; +var arrayType = ZodArray2.create; +var objectType = ZodObject2.create; +var strictObjectType = ZodObject2.strictCreate; +var unionType = ZodUnion2.create; +var discriminatedUnionType = ZodDiscriminatedUnion2.create; +var intersectionType = ZodIntersection2.create; +var tupleType = ZodTuple2.create; +var recordType = ZodRecord2.create; +var mapType = ZodMap2.create; +var setType = ZodSet2.create; +var functionType = ZodFunction2.create; +var lazyType = ZodLazy2.create; +var literalType = ZodLiteral2.create; +var enumType = ZodEnum2.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise2.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional2.create; +var nullableType = ZodNullable2.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: (arg) => ZodString2.create({ ...arg, coerce: true }), + number: (arg) => ZodNumber2.create({ ...arg, coerce: true }), + boolean: (arg) => ZodBoolean2.create({ + ...arg, + coerce: true + }), + bigint: (arg) => ZodBigInt2.create({ ...arg, coerce: true }), + date: (arg) => ZodDate2.create({ ...arg, coerce: true }) +}; +var NEVER2 = INVALID; +var SCHEMA_IDS = { + actorRef: "hasna.actor_ref.v1", + resourceRef: "hasna.resource_ref.v1", + evidenceRef: "hasna.evidence_ref.v1", + workRun: "hasna.work_run.v1", + taskToPrProjection: "hasna.task_to_pr_projection.v1", + decisionEnvelope: "hasna.decision_envelope.v1", + costEstimate: "hasna.cost_estimate.v1", + capabilityCard: "hasna.capability_card.v1", + providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", + contextPack: "hasna.context_pack.v1", + integrationRef: "hasna.integration_ref.v1", + projectManifest: "hasna.project_manifest.v1", + projectPanel: "hasna.project_panel.v1", + projectSnapshot: "hasna.project_snapshot.v1", + renderManifest: "hasna.render_manifest.v1", + agentTrajectory: "hasna.agent_trajectory.v1", + validationPlan: "hasna.validation_plan.v1", + proofBundle: "hasna.proof_bundle.v1", + scaffoldManifest: "hasna.scaffold_manifest.v1", + scaffoldInstallRecord: "hasna.scaffold_install_record.v1", + appCloudManifest: "hasna.app_cloud_manifest.v1", + noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", + secureLocalStorePolicy: "hasna.secure_local_store_policy.v1", + serviceContract: "hasna.service_contract.v1", + commsEventEnvelope: "hasna.comms_event_envelope.v1", + commsChannelMetadata: "hasna.comms_channel_metadata.v1", + commsMessageMetadata: "hasna.comms_message_metadata.v1", + app: "hasna.app.v1", + release: "hasna.release.v1", + rolloutRecord: "hasna.rollout_record.v1", + announcement: "hasna.announcement.v1", + audience: "hasna.audience.v1" +}; +var SchemaIdSchema = exports_external2.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); +var TimestampSchema = exports_external2.string().datetime(); +var NonEmptyStringSchema = exports_external2.string().trim().min(1); +var UriSchema = NonEmptyStringSchema.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); +var Sha256DigestSchema = exports_external2.string().regex(/^[a-fA-F0-9]{64}$/); +var HashStringSchema = exports_external2.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); +var MetadataSchema = exports_external2.record(exports_external2.unknown()); +var TagsSchema = exports_external2.array(exports_external2.string().min(1)).default([]); +var OptionalTimestampSchema = TimestampSchema.nullable().optional(); +var TerminalStatuses = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); +var ContractStatusSchema = exports_external2.enum([ + "pending", + "running", + "succeeded", + "failed", + "cancelled", + "blocked", + "skipped", + "unknown" +]); +function contractBaseSchema(schema) { + return exports_external2.object({ + schema: exports_external2.literal(schema), + id: exports_external2.string().min(1), + createdAt: TimestampSchema, + updatedAt: OptionalTimestampSchema, + metadata: MetadataSchema.optional() + }).strict(); +} +var ContractEnvelopeSchema = exports_external2.object({ + schema: SchemaIdSchema, + id: exports_external2.string().min(1), + createdAt: TimestampSchema, + updatedAt: OptionalTimestampSchema, + metadata: MetadataSchema.optional() +}).strict(); +var ActorKindSchema = exports_external2.enum([ + "agent", + "human", + "service", + "model", + "workflow", + "system" +]); +var ActorRefSchema = contractBaseSchema(SCHEMA_IDS.actorRef).extend({ + kind: ActorKindSchema, + name: exports_external2.string().min(1).optional(), + provider: exports_external2.string().min(1).optional(), + accountId: exports_external2.string().min(1).optional(), + machineId: exports_external2.string().min(1).optional(), + capabilities: exports_external2.array(exports_external2.string().min(1)).default([]) +}).strict(); +var ActorPointerSchema = exports_external2.object({ + kind: ActorKindSchema, + id: exports_external2.string().min(1), + name: exports_external2.string().min(1).optional(), + provider: exports_external2.string().min(1).optional(), + accountId: exports_external2.string().min(1).optional(), + machineId: exports_external2.string().min(1).optional() +}).strict(); +var ResourceKindSchema = exports_external2.enum([ + "task", + "project", + "repo", + "run", + "loop", + "workflow", + "action", + "event", + "integration", + "session", + "machine", + "model", + "tool", + "file", + "document", + "url", + "artifact", + "knowledge", + "email", + "conversation", + "dashboard", + "render", + "panel", + "report", + "commit", + "branch", + "pull_request", + "issue", + "comment", + "verification", + "finding", + "context_pack", + "proof_bundle", + "memento", + "eval", + "budget", + "cost", + "alert", + "incident", + "app", + "release", + "rollout", + "announcement", + "audience", + "feedback", + "unknown" +]); +var ResourceRefSchema = contractBaseSchema(SCHEMA_IDS.resourceRef).extend({ + kind: ResourceKindSchema, + name: exports_external2.string().min(1).optional(), + uri: UriSchema.optional(), + externalId: NonEmptyStringSchema.optional(), + sourcePackage: NonEmptyStringSchema.optional(), + tags: TagsSchema +}).strict().superRefine((value, ctx) => { + if (!value.uri && !(value.externalId && value.sourcePackage)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Resource refs require uri or both sourcePackage and externalId", + path: ["uri"] }); - return merged; } - setKey(key, schema) { - return this.augment({ [key]: schema }); +}); +var ResourcePointerSchema = exports_external2.object({ + kind: ResourceKindSchema, + id: exports_external2.string().min(1), + name: exports_external2.string().min(1).optional(), + uri: UriSchema.optional(), + externalId: NonEmptyStringSchema.optional(), + sourcePackage: NonEmptyStringSchema.optional(), + tags: TagsSchema +}).strict().superRefine((value, ctx) => { + if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Resource pointers with external package locators require both sourcePackage and externalId", + path: value.externalId ? ["sourcePackage"] : ["externalId"] + }); } - catchall(index) { - return new ZodObject5({ - ...this._def, - catchall: index +}); +var EvidenceKindSchema = exports_external2.enum([ + "file", + "command_output", + "screenshot", + "log", + "diff", + "report", + "artifact", + "url", + "video", + "har", + "test_result", + "metric", + "trace", + "other" +]); +var RedactionStateSchema = exports_external2.enum(["none", "partial", "full", "unknown"]); +var EvidenceRefSchema = contractBaseSchema(SCHEMA_IDS.evidenceRef).extend({ + kind: EvidenceKindSchema, + uri: UriSchema, + sha256: Sha256DigestSchema.optional(), + summary: exports_external2.string().min(1).optional(), + contentType: exports_external2.string().min(1).optional(), + sizeBytes: exports_external2.number().int().nonnegative().optional(), + redaction: RedactionStateSchema.default("unknown"), + producer: ActorPointerSchema.optional(), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + tags: TagsSchema +}).strict(); +var EvidencePointerSchema = exports_external2.object({ + id: exports_external2.string().min(1), + kind: EvidenceKindSchema.optional(), + uri: UriSchema.optional(), + sha256: Sha256DigestSchema.optional(), + summary: exports_external2.string().min(1).optional() +}).strict(); +var CostEstimateSchema = contractBaseSchema(SCHEMA_IDS.costEstimate).extend({ + currency: exports_external2.string().regex(/^[A-Z]{3}$/).default("USD"), + amountMicros: exports_external2.number().int().nonnegative(), + provider: exports_external2.string().min(1).optional(), + model: exports_external2.string().min(1).optional(), + accountId: exports_external2.string().min(1).optional(), + promptTokens: exports_external2.number().int().nonnegative().optional(), + completionTokens: exports_external2.number().int().nonnegative().optional(), + totalTokens: exports_external2.number().int().nonnegative().optional(), + basis: exports_external2.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "totalTokens must equal promptTokens plus completionTokens when all are present", + path: ["totalTokens"] }); } - pick(mask) { - const shape = {}; - for (const key of util4.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject5({ - ...this._def, - shape: () => shape - }); +}); +var DecisionStatusSchema = exports_external2.enum([ + "allowed", + "denied", + "warned", + "approval_required", + "selected", + "skipped", + "unknown" +]); +var DecisionEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.decisionEnvelope).extend({ + decisionType: exports_external2.enum([ + "guardrail", + "model_route", + "tool_select", + "budget", + "secret_access", + "approval", + "policy", + "other" + ]), + status: DecisionStatusSchema, + actor: ActorPointerSchema.optional(), + traceId: exports_external2.string().min(1).optional(), + inputHash: HashStringSchema.optional(), + policyBundleId: exports_external2.string().min(1).optional(), + selected: exports_external2.array(ResourcePointerSchema).default([]), + skipped: exports_external2.array(ResourcePointerSchema).default([]), + reason: exports_external2.string().min(1), + obligations: exports_external2.array(exports_external2.string().min(1)).default([]), + redactions: exports_external2.array(exports_external2.string().min(1)).default([]), + costEstimate: CostEstimateSchema.optional(), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.status === "selected" && value.selected.length === 0) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); + } + if (value.status === "skipped" && value.skipped.length === 0) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); } - omit(mask) { - const shape = {}; - for (const key of util4.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } + if (value.status === "denied") { + if (value.selected.length > 0) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); } - return new ZodObject5({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify4(this); - } - partial(mask) { - const newShape = {}; - for (const key of util4.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } + if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Denied decisions require policy, evidence, or obligations", + path: ["policyBundleId"] + }); } - return new ZodObject5({ - ...this._def, - shape: () => newShape - }); } - required(mask) { - const newShape = {}; - for (const key of util4.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional5) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject5({ - ...this._def, - shape: () => newShape + if (value.status === "approval_required" && value.obligations.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Approval-required decisions require actionable obligations", + path: ["obligations"] }); } - keyof() { - return createZodEnum4(util4.objectKeys(this.shape)); - } -} -ZodObject5.create = (shape, params) => { - return new ZodObject5({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever5.create(), - typeName: ZodFirstPartyTypeKind5.ZodObject, - ...processCreateParams4(params) - }); -}; -ZodObject5.strictCreate = (shape, params) => { - return new ZodObject5({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever5.create(), - typeName: ZodFirstPartyTypeKind5.ZodObject, - ...processCreateParams4(params) - }); -}; -ZodObject5.lazycreate = (shape, params) => { - return new ZodObject5({ - shape, - unknownKeys: "strip", - catchall: ZodNever5.create(), - typeName: ZodFirstPartyTypeKind5.ZodObject, - ...processCreateParams4(params) - }); -}; - -class ZodUnion5 extends ZodType5 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError5(result.ctx.common.issues)); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_union, - unionErrors +}); +var CapabilityCardSchema = contractBaseSchema(SCHEMA_IDS.capabilityCard).extend({ + kind: exports_external2.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), + name: exports_external2.string().min(1), + version: exports_external2.string().min(1).optional(), + status: exports_external2.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), + capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), + limitations: exports_external2.array(exports_external2.string().min(1)).default([]), + riskLevel: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), + costEstimate: CostEstimateSchema.optional(), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict(); +var ProviderModeSchema = exports_external2.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); +var ProviderSideEffectClassSchema = exports_external2.enum([ + "none", + "read_only", + "external_notification", + "external_mutation", + "money_movement", + "dns_or_domain_change", + "bulk_message_or_call", + "legal_or_filing", + "compute_or_infra_mutation", + "irreversible" +]); +var CredentialRequirementSchema = exports_external2.object({ + refName: NonEmptyStringSchema, + requiredForModes: exports_external2.array(ProviderModeSchema).min(1), + allowedSecretInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), + failClosedDiagnostic: NonEmptyStringSchema, + revocationCheck: exports_external2.boolean().default(true) +}).strict(); +var ProviderOperationCardSchema = exports_external2.object({ + operation: NonEmptyStringSchema, + supportedModes: exports_external2.array(ProviderModeSchema).min(1), + sideEffectClass: ProviderSideEffectClassSchema, + requiresApproval: exports_external2.boolean().default(false), + requiresIdempotencyKey: exports_external2.boolean().default(false), + requiresSandboxEvidence: exports_external2.boolean().default(false), + requiresRollbackOrRevocation: exports_external2.boolean().default(false), + rollbackOrRevocation: NonEmptyStringSchema.optional(), + noSideEffectSmoke: NonEmptyStringSchema.optional(), + reconciliation: NonEmptyStringSchema.optional() +}).strict().superRefine((value, ctx) => { + if (value.supportedModes.includes("live_mutating")) { + if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating operations must declare a side-effecting class", + path: ["sideEffectClass"] }); - return INVALID4; } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError5(issues2)); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_union, - unionErrors + if (!value.requiresApproval) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating operations require approval", + path: ["requiresApproval"] }); - return INVALID4; } - } - get options() { - return this._def.options; - } -} -ZodUnion5.create = (types, params) => { - return new ZodUnion5({ - options: types, - typeName: ZodFirstPartyTypeKind5.ZodUnion, - ...processCreateParams4(params) - }); -}; -var getDiscriminator4 = (type) => { - if (type instanceof ZodLazy5) { - return getDiscriminator4(type.schema); - } else if (type instanceof ZodEffects4) { - return getDiscriminator4(type.innerType()); - } else if (type instanceof ZodLiteral5) { - return [type.value]; - } else if (type instanceof ZodEnum5) { - return type.options; - } else if (type instanceof ZodNativeEnum4) { - return util4.objectValues(type.enum); - } else if (type instanceof ZodDefault5) { - return getDiscriminator4(type._def.innerType); - } else if (type instanceof ZodUndefined5) { - return [undefined]; - } else if (type instanceof ZodNull5) { - return [null]; - } else if (type instanceof ZodOptional5) { - return [undefined, ...getDiscriminator4(type.unwrap())]; - } else if (type instanceof ZodNullable5) { - return [null, ...getDiscriminator4(type.unwrap())]; - } else if (type instanceof ZodBranded4) { - return getDiscriminator4(type.unwrap()); - } else if (type instanceof ZodReadonly5) { - return getDiscriminator4(type.unwrap()); - } else if (type instanceof ZodCatch5) { - return getDiscriminator4(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion5 extends ZodType5 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType4.object) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.object, - received: ctx.parsedType + if (!value.requiresIdempotencyKey) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating operations require idempotency keys", + path: ["requiresIdempotencyKey"] }); - return INVALID4; } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] + if (!value.requiresSandboxEvidence) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating operations require sandbox evidence before live proof", + path: ["requiresSandboxEvidence"] }); - return INVALID4; } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx + if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating operations require rollback or revocation instructions", + path: ["rollbackOrRevocation"] }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx + } + if (!value.reconciliation) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating operations require reconciliation behavior", + path: ["reconciliation"] }); } } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator4(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion5({ - typeName: ZodFirstPartyTypeKind5.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams4(params) +}); +var ProviderCapabilityCardSchema = exports_external2.object({ + providerId: NonEmptyStringSchema, + appId: NonEmptyStringSchema, + adapterId: NonEmptyStringSchema, + ownerPackage: NonEmptyStringSchema, + modes: exports_external2.array(ProviderModeSchema).min(1), + defaultMode: ProviderModeSchema, + credentialRequirements: exports_external2.array(CredentialRequirementSchema).default([]), + operations: exports_external2.array(ProviderOperationCardSchema).min(1), + rateLimitPosture: NonEmptyStringSchema, + costPosture: NonEmptyStringSchema.optional(), + auditEvents: exports_external2.array(NonEmptyStringSchema).default([]), + redactionRules: exports_external2.array(NonEmptyStringSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (!value.modes.includes(value.defaultMode)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "defaultMode must be one of modes", + path: ["defaultMode"] }); } -} -function mergeValues5(a, b) { - const aType = getParsedType5(a); - const bType = getParsedType5(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType4.object && bType === ZodParsedType4.object) { - const bKeys = util4.objectKeys(b); - const sharedKeys = util4.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues5(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType4.array && bType === ZodParsedType4.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues5(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); + const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); + for (const mode2 of operationModes) { + if (!value.modes.includes(mode2)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `operation mode ${mode2} is not declared in provider modes`, + path: ["operations"] + }); } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType4.date && bType === ZodParsedType4.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; } -} - -class ZodIntersection5 extends ZodType5 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted4(parsedLeft) || isAborted4(parsedRight)) { - return INVALID4; - } - const merged = mergeValues5(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_intersection_types - }); - return INVALID4; - } - if (isDirty4(parsedLeft) || isDirty4(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); + if (operationModes.has("live_mutating")) { + const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); + if (!liveCredential) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating providers require at least one live credential reference requirement", + path: ["credentialRequirements"] + }); } - } -} -ZodIntersection5.create = (left, right, params) => { - return new ZodIntersection5({ - left, - right, - typeName: ZodFirstPartyTypeKind5.ZodIntersection, - ...processCreateParams4(params) - }); -}; - -class ZodTuple5 extends ZodType5 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType4.array) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.array, - received: ctx.parsedType + if (value.auditEvents.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "live_mutating providers require audit events", + path: ["auditEvents"] }); - return INVALID4; } - if (ctx.data.length < this._def.items.length) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" + } +}); +var ProviderLiveModeTargetSchema = exports_external2.object({ + appId: NonEmptyStringSchema, + repo: NonEmptyStringSchema, + priority: exports_external2.enum(["p0", "p1", "p2"]).default("p1"), + requiredEvidence: exports_external2.array(NonEmptyStringSchema).min(1), + firstOperations: exports_external2.array(NonEmptyStringSchema).min(1), + blockedUntil: exports_external2.array(NonEmptyStringSchema).default([]) +}).strict(); +var ProviderLiveModeStandardSchema = contractBaseSchema(SCHEMA_IDS.providerLiveModeStandard).extend({ + name: NonEmptyStringSchema, + version: NonEmptyStringSchema, + modes: exports_external2.array(ProviderModeSchema).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode2) => modes.includes(mode2)), "provider live-mode standard must include every canonical provider mode"), + requiredCapabilityFields: exports_external2.array(NonEmptyStringSchema).min(1), + liveMutationGate: exports_external2.object({ + requiredMode: exports_external2.literal("live_mutating"), + requiredChecks: exports_external2.array(NonEmptyStringSchema).min(1), + forbiddenBypassSignals: exports_external2.array(NonEmptyStringSchema).min(1), + disabledLiveSmoke: NonEmptyStringSchema + }).strict(), + noSideEffectSmoke: exports_external2.object({ + requiredForModes: exports_external2.array(ProviderModeSchema).min(1), + commandEvidence: exports_external2.array(NonEmptyStringSchema).min(1), + secretOutputScan: exports_external2.boolean().default(true) + }).strict(), + credentialPolicy: exports_external2.object({ + acceptedInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1), + rawSecretInputsAllowed: exports_external2.literal(false), + missingCredentialBehavior: exports_external2.literal("fail_closed"), + revocationCheckRequired: exports_external2.boolean().default(true) + }).strict(), + operationCards: exports_external2.array(ProviderCapabilityCardSchema).min(1), + firstAdoptionTargets: exports_external2.array(ProviderLiveModeTargetSchema).min(1), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); + const operationApps = new Set(value.operationCards.map((card) => card.appId)); + for (const appId of firstTargetApps) { + if (!operationApps.has(appId)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `first adoption target ${appId} requires a provider capability card`, + path: ["firstAdoptionTargets"] }); - return INVALID4; } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" + } +}); +var ContextPackItemSchema = exports_external2.object({ + id: exports_external2.string().min(1), + title: exports_external2.string().min(1).optional(), + summary: exports_external2.string().min(1), + text: exports_external2.string().optional(), + tokens: exports_external2.number().int().nonnegative().optional(), + source: EvidencePointerSchema, + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) +}).strict(); +var ContextPackSchema = contractBaseSchema(SCHEMA_IDS.contextPack).extend({ + objective: exports_external2.string().min(1), + budget: exports_external2.object({ + maxTokens: exports_external2.number().int().positive().optional(), + maxBytes: exports_external2.number().int().positive().optional() + }).strict().optional(), + items: exports_external2.array(ContextPackItemSchema).default([]), + citations: exports_external2.array(EvidencePointerSchema).default([]), + freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), + permissions: exports_external2.array(exports_external2.string().min(1)).default([]), + redactions: exports_external2.array(exports_external2.string().min(1)).default([]), + conflicts: exports_external2.array(exports_external2.string().min(1)).default([]), + uncertainty: exports_external2.string().min(1).optional() +}).strict(); +var RelativeProjectPathSchema = NonEmptyStringSchema.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); +var ProjectSlugSchema = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); +var ProjectClassificationSchema = exports_external2.enum(["public", "internal", "private", "sensitive"]); +var ProjectStatusSchema = exports_external2.enum(["draft", "active", "paused", "archived"]); +var ProjectIntegrationKindSchema = exports_external2.enum([ + "todos", + "files", + "mailery", + "conversations", + "knowledge", + "mementos", + "reports", + "actions", + "render", + "contracts", + "custom" +]); +var IntegrationRefSchema = contractBaseSchema(SCHEMA_IDS.integrationRef).extend({ + kind: ProjectIntegrationKindSchema, + name: exports_external2.string().min(1), + projectId: ProjectSlugSchema.optional(), + sourcePackage: NonEmptyStringSchema.optional(), + externalId: NonEmptyStringSchema.optional(), + uri: UriSchema.optional(), + enabled: exports_external2.boolean().default(true), + readOnly: exports_external2.boolean().default(true), + capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), + freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), + resourceRef: ResourcePointerSchema.optional(), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + config: MetadataSchema.optional() +}).strict().superRefine((value, ctx) => { + if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", + path: ["uri"] + }); + } +}); +var ProjectLayoutSchema = exports_external2.object({ + schemaRoot: RelativeProjectPathSchema.default(".hasna/project"), + dashboardManifest: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), + snapshotsDir: RelativeProjectPathSchema.default(".hasna/project/snapshots"), + documentsDir: RelativeProjectPathSchema.default("documents"), + reportsDir: RelativeProjectPathSchema.default("reports"), + evidenceDir: RelativeProjectPathSchema.default(".hasna/project/evidence"), + privateDir: RelativeProjectPathSchema.default(".hasna/project/private") +}).strict(); +var ProjectManifestSchema = contractBaseSchema(SCHEMA_IDS.projectManifest).extend({ + projectId: ProjectSlugSchema, + slug: ProjectSlugSchema, + name: exports_external2.string().min(1), + summary: exports_external2.string().min(1).optional(), + status: ProjectStatusSchema.default("active"), + classification: ProjectClassificationSchema.default("private"), + owner: ActorPointerSchema.optional(), + layout: ProjectLayoutSchema.default({}), + integrations: exports_external2.array(IntegrationRefSchema).default([]), + renderManifests: exports_external2.array(ResourcePointerSchema).default([]), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + tags: TagsSchema +}).strict().superRefine((value, ctx) => { + const integrationIds = new Set; + const renderManifestIds = new Set; + if (value.projectId !== value.slug) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "projectId and slug must match for canonical project manifests", + path: ["slug"] + }); + } + for (const [index, integration] of value.integrations.entries()) { + if (integrationIds.has(integration.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project manifest integration ids must be unique", + path: ["integrations", index, "id"] }); - status.dirty(); } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath4(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus4.mergeArray(status, results); + integrationIds.add(integration.id); + if (integration.projectId && integration.projectId !== value.projectId) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Integration projectId must match the manifest projectId", + path: ["integrations", index, "projectId"] }); - } else { - return ParseStatus4.mergeArray(status, items); } } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple5({ - ...this._def, - rest - }); - } -} -ZodTuple5.create = (schemas3, params) => { - if (!Array.isArray(schemas3)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple5({ - items: schemas3, - typeName: ZodFirstPartyTypeKind5.ZodTuple, - rest: null, - ...processCreateParams4(params) - }); -}; - -class ZodRecord5 extends ZodType5 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType4.object) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.object, - received: ctx.parsedType + for (const [index, renderManifest] of value.renderManifests.entries()) { + if (renderManifest.kind !== "render") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project renderManifests must use resource kind render", + path: ["renderManifests", index, "kind"] }); - return INVALID4; } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath4(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath4(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data + if (renderManifestIds.has(renderManifest.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project renderManifest refs must be unique", + path: ["renderManifests", index, "id"] }); } - if (ctx.common.async) { - return ParseStatus4.mergeObjectAsync(status, pairs); - } else { - return ParseStatus4.mergeObjectSync(status, pairs); - } + renderManifestIds.add(renderManifest.id); } - get element() { - return this._def.valueType; +}); +var RenderImportKindSchema = exports_external2.enum(["local", "package", "provider", "url"]); +var RenderImportSchema = exports_external2.object({ + id: exports_external2.string().min(1), + kind: RenderImportKindSchema, + specifier: exports_external2.string().min(1), + path: RelativeProjectPathSchema.optional(), + packageName: exports_external2.string().min(1).optional(), + uri: UriSchema.optional(), + provider: ProjectIntegrationKindSchema.optional(), + schemaId: SchemaIdSchema.optional(), + integrity: HashStringSchema.optional(), + resourceRef: ResourcePointerSchema.optional(), + optional: exports_external2.boolean().default(false) +}).strict().superRefine((value, ctx) => { + if (value.kind === "local" && !value.path) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); } - static create(first, second, third) { - if (second instanceof ZodType5) { - return new ZodRecord5({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind5.ZodRecord, - ...processCreateParams4(third) - }); - } - return new ZodRecord5({ - keyType: ZodString5.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind5.ZodRecord, - ...processCreateParams4(second) - }); + if (value.kind === "package" && !value.packageName) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); } -} - -class ZodMap5 extends ZodType5 { - get keySchema() { - return this._def.keyType; + if (value.kind === "provider" && !value.provider) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); } - get valueSchema() { - return this._def.valueType; + if (value.kind === "url" && !value.uri) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType4.map) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.map, - received: ctx.parsedType - }); - return INVALID4; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath4(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath4(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID4; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; +}); +var RenderViewKindSchema = exports_external2.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); +var RenderViewSchema = exports_external2.object({ + id: exports_external2.string().min(1), + title: exports_external2.string().min(1), + kind: RenderViewKindSchema, + default: exports_external2.boolean().default(false), + entry: RelativeProjectPathSchema.optional(), + imports: exports_external2.array(RenderImportSchema).default([]), + panelRefs: exports_external2.array(ResourcePointerSchema).default([]), + dataRefs: exports_external2.array(ResourcePointerSchema).default([]), + layout: MetadataSchema.optional() +}).strict(); +var RenderManifestSchema = contractBaseSchema(SCHEMA_IDS.renderManifest).extend({ + projectId: ProjectSlugSchema, + name: exports_external2.string().min(1), + version: exports_external2.string().min(1), + manifestPath: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), + renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), + views: exports_external2.array(RenderViewSchema).min(1), + imports: exports_external2.array(RenderImportSchema).default([]), + theme: MetadataSchema.optional(), + compatibility: exports_external2.object({ + minProjectsVersion: exports_external2.string().min(1).optional(), + minContractsVersion: exports_external2.string().min(1).optional() + }).strict().optional(), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + const defaults = value.views.filter((view) => view.default); + const viewIds = new Set; + const importIds = new Set; + if (defaults.length > 1) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); + } + for (const [index, importRef] of value.imports.entries()) { + if (importIds.has(importRef.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Render manifest import ids must be unique", + path: ["imports", index, "id"] }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID4; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; } + importIds.add(importRef.id); } -} -ZodMap5.create = (keyType, valueType, params) => { - return new ZodMap5({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind5.ZodMap, - ...processCreateParams4(params) - }); -}; - -class ZodSet5 extends ZodType5 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType4.set) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.set, - received: ctx.parsedType + for (const [viewIndex, view] of value.views.entries()) { + if (viewIds.has(view.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Render manifest view ids must be unique", + path: ["views", viewIndex, "id"] }); - return INVALID4; } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message + viewIds.add(view.id); + const viewImportIds = new Set; + for (const [importIndex, importRef] of view.imports.entries()) { + if (viewImportIds.has(importRef.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Render view import ids must be unique", + path: ["views", viewIndex, "imports", importIndex, "id"] }); - status.dirty(); } + viewImportIds.add(importRef.id); } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message + for (const [panelIndex, panelRef] of view.panelRefs.entries()) { + if (panelRef.kind !== "panel") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Render view panelRefs must use resource kind panel", + path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID4; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath4(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); } } - min(minSize, message) { - return new ZodSet5({ - ...this._def, - minSize: { value: minSize, message: errorUtil4.toString(message) } +}); +var ProjectPanelStateSchema = exports_external2.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); +var ProjectPanelKindSchema = exports_external2.enum([ + "overview", + "tasks", + "files", + "mailery", + "conversations", + "knowledge", + "mementos", + "reports", + "actions", + "timeline", + "risks", + "documents", + "custom" +]); +var ProjectPanelMetricSchema = exports_external2.object({ + id: exports_external2.string().min(1), + label: exports_external2.string().min(1), + value: exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]), + unit: exports_external2.string().min(1).optional(), + status: exports_external2.enum(["good", "warning", "critical", "unknown"]).default("unknown"), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) +}).strict(); +var ProjectPanelItemSchema = exports_external2.object({ + id: exports_external2.string().min(1), + title: exports_external2.string().min(1), + summary: exports_external2.string().min(1).optional(), + status: exports_external2.string().min(1).optional(), + priority: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), + timestamp: TimestampSchema.optional(), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + metadata: MetadataSchema.optional() +}).strict(); +var ProjectRenderFragmentSchema = exports_external2.object({ + renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), + title: exports_external2.string().min(1).optional(), + entry: RelativeProjectPathSchema.optional(), + imports: exports_external2.array(RenderImportSchema).default([]), + spec: MetadataSchema.default({}) +}).strict(); +var ProjectPanelSchema = contractBaseSchema(SCHEMA_IDS.projectPanel).extend({ + projectId: ProjectSlugSchema, + provider: exports_external2.object({ + kind: ProjectIntegrationKindSchema, + id: exports_external2.string().min(1), + name: exports_external2.string().min(1).optional(), + sourcePackage: NonEmptyStringSchema.optional(), + externalId: NonEmptyStringSchema.optional() + }).strict(), + kind: ProjectPanelKindSchema, + title: exports_external2.string().min(1), + summary: exports_external2.string().min(1).optional(), + state: ProjectPanelStateSchema.default("ready"), + stateReason: exports_external2.string().min(1).optional(), + generatedAt: TimestampSchema, + freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), + metrics: exports_external2.array(ProjectPanelMetricSchema).default([]), + items: exports_external2.array(ProjectPanelItemSchema).default([]), + actions: exports_external2.array(ResourcePointerSchema).default([]), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + renderFragment: ProjectRenderFragmentSchema.optional(), + warnings: exports_external2.array(exports_external2.string().min(1)).default([]) +}).strict().superRefine((value, ctx) => { + const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); + const metricIds = new Set; + const itemIds = new Set; + if (reasonStates.has(value.state) && !value.stateReason) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Non-ready provider states require stateReason", + path: ["stateReason"] }); } - max(maxSize, message) { - return new ZodSet5({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil4.toString(message) } + if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", + path: ["state"] }); } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); + for (const [index, metric] of value.metrics.entries()) { + if (metricIds.has(metric.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project panel metric ids must be unique", + path: ["metrics", index, "id"] + }); + } + metricIds.add(metric.id); } -} -ZodSet5.create = (valueType, params) => { - return new ZodSet5({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind5.ZodSet, - ...processCreateParams4(params) - }); -}; - -class ZodFunction5 extends ZodType5 { - constructor() { - super(...arguments); - this.validate = this.implement; + for (const [index, item] of value.items.entries()) { + if (itemIds.has(item.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project panel item ids must be unique", + path: ["items", index, "id"] + }); + } + itemIds.add(item.id); } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType4.function) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.function, - received: ctx.parsedType + for (const [index, action] of value.actions.entries()) { + if (action.kind !== "action") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project panel actions must use resource kind action", + path: ["actions", index, "kind"] }); - return INVALID4; } - function makeArgsIssue(args, error51) { - return makeIssue4({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap5(), en_default5].filter((x) => !!x), - issueData: { - code: ZodIssueCode5.invalid_arguments, - argumentsError: error51 - } + } +}); +var ProjectSnapshotSchema = contractBaseSchema(SCHEMA_IDS.projectSnapshot).extend({ + projectId: ProjectSlugSchema, + generatedAt: TimestampSchema, + status: ContractStatusSchema.default("unknown"), + manifestRef: ResourcePointerSchema, + renderManifestRef: ResourcePointerSchema.optional(), + panels: exports_external2.array(ProjectPanelSchema).default([]), + contextPacks: exports_external2.array(ContextPackSchema).default([]), + proofBundleRefs: exports_external2.array(ResourcePointerSchema).default([]), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + warnings: exports_external2.array(exports_external2.string().min(1)).default([]), + freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") +}).strict().superRefine((value, ctx) => { + const panelIds = new Set; + const contextPackIds = new Set; + if (value.manifestRef.kind !== "project") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project snapshot manifestRef must use resource kind project", + path: ["manifestRef", "kind"] + }); + } + if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project snapshot renderManifestRef must use resource kind render", + path: ["renderManifestRef", "kind"] + }); + } + for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { + if (proofBundleRef.kind !== "proof_bundle") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", + path: ["proofBundleRefs", index, "kind"] }); } - function makeReturnsIssue(returns, error51) { - return makeIssue4({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap5(), en_default5].filter((x) => !!x), - issueData: { - code: ZodIssueCode5.invalid_return_type, - returnTypeError: error51 - } + } + for (const [index, panel] of value.panels.entries()) { + if (panel.projectId !== value.projectId) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Panel projectId must match snapshot projectId", + path: ["panels", index, "projectId"] }); } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise5) { - const me = this; - return OK4(async function(...args) { - const error51 = new ZodError5([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error51.addIssue(makeArgsIssue(args, e)); - throw error51; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error51.addIssue(makeReturnsIssue(result, e)); - throw error51; - }); - return parsedReturns; + if (panelIds.has(panel.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project snapshot panel ids must be unique", + path: ["panels", index, "id"] }); - } else { - const me = this; - return OK4(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError5([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError5([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; + } + panelIds.add(panel.id); + } + for (const [index, contextPack] of value.contextPacks.entries()) { + if (contextPackIds.has(contextPack.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Project snapshot context pack ids must be unique", + path: ["contextPacks", index, "id"] }); } + contextPackIds.add(contextPack.id); } - parameters() { - return this._def.args; +}); +var ValidationCheckSchema = exports_external2.object({ + id: exports_external2.string().min(1), + kind: exports_external2.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), + required: exports_external2.boolean().default(true), + command: exports_external2.string().min(1).optional(), + expected: exports_external2.string().min(1).optional(), + timeoutMs: exports_external2.number().int().positive().optional(), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); + if (actionableKinds.has(value.kind) && !value.command && !value.expected) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Actionable validation checks require command or expected", + path: ["command"] + }); } - returnType() { - return this._def.returns; +}); +var ValidationPlanSchema = contractBaseSchema(SCHEMA_IDS.validationPlan).extend({ + objective: exports_external2.string().min(1), + subject: ResourcePointerSchema.optional(), + checks: exports_external2.array(ValidationCheckSchema).min(1), + verifier: ActorPointerSchema.optional(), + requiredEvidenceKinds: exports_external2.array(EvidenceKindSchema).default([]) +}).strict(); +var ScaffoldTypeSchema = exports_external2.enum([ + "open_source", + "internal_app", + "platform", + "app", + "agent", + "content", + "overlay", + "other" +]); +var ScaffoldStatusSchema = exports_external2.enum(["draft", "active", "deprecated", "archived"]); +var ScaffoldCapabilitySchema = exports_external2.enum([ + "cli", + "mcp", + "library", + "sdk", + "rest_api", + "dashboard", + "database", + "auth", + "billing", + "worker", + "daemon", + "native", + "browser_extension", + "ai_provider", + "media_pipeline", + "data_pipeline", + "tests", + "ci", + "deployment", + "docs", + "other" +]); +var ScaffoldEnvVarSchema = exports_external2.object({ + key: exports_external2.string().regex(/^[A-Z][A-Z0-9_]*$/), + description: exports_external2.string().min(1), + required: exports_external2.boolean().default(false), + ["secret"]: exports_external2.boolean().default(false), + group: exports_external2.string().min(1).optional(), + default: exports_external2.string().optional() +}).strict().superRefine((value, ctx) => { + if (value.secret && value.default !== undefined) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Secret scaffold env vars cannot include defaults", + path: ["default"] + }); } - args(...items) { - return new ZodFunction5({ - ...this._def, - args: ZodTuple5.create(items).rest(ZodUnknown5.create()) +}); +var ScaffoldScriptSchema = exports_external2.object({ + name: exports_external2.string().min(1), + command: exports_external2.string().min(1), + description: exports_external2.string().min(1).optional(), + required: exports_external2.boolean().default(false) +}).strict(); +var ScaffoldOutputShapeSchema = exports_external2.object({ + packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), + languages: exports_external2.array(exports_external2.string().min(1)).default([]), + requiredFiles: exports_external2.array(exports_external2.string().min(1)).default([]), + requiredDirectories: exports_external2.array(exports_external2.string().min(1)).default([]), + optionalDirectories: exports_external2.array(exports_external2.string().min(1)).default([]) +}).strict(); +var ScaffoldManifestSchema = contractBaseSchema(SCHEMA_IDS.scaffoldManifest).extend({ + name: exports_external2.string().min(1), + version: exports_external2.string().min(1), + summary: exports_external2.string().min(1), + type: ScaffoldTypeSchema, + status: ScaffoldStatusSchema.default("draft"), + capabilities: exports_external2.array(ScaffoldCapabilitySchema).default([]), + techStack: exports_external2.array(exports_external2.string().min(1)).default([]), + tags: TagsSchema, + source: ResourcePointerSchema.optional(), + output: ScaffoldOutputShapeSchema, + env: exports_external2.array(ScaffoldEnvVarSchema).default([]), + scripts: exports_external2.array(ScaffoldScriptSchema).default([]), + validationChecks: exports_external2.array(ValidationCheckSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.source?.uri?.startsWith("file://")) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Public scaffold manifest source refs cannot use local file:// URIs", + path: ["source", "uri"] }); } - returns(returnType) { - return new ZodFunction5({ - ...this._def, - returns: returnType + if (value.status === "active" && value.validationChecks.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Active scaffold manifests require validation checks", + path: ["validationChecks"] }); } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction5({ - args: args ? args : ZodTuple5.create([]).rest(ZodUnknown5.create()), - returns: returns || ZodUnknown5.create(), - typeName: ZodFirstPartyTypeKind5.ZodFunction, - ...processCreateParams4(params) + if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Active scaffold manifests require at least one required file or directory", + path: ["output"] }); } -} - -class ZodLazy5 extends ZodType5 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); +}); +var ScaffoldInstallStatusSchema = exports_external2.enum(["installed", "failed", "cancelled", "partial", "unknown"]); +var ScaffoldInstallRecordSchema = contractBaseSchema(SCHEMA_IDS.scaffoldInstallRecord).extend({ + scaffoldId: exports_external2.string().min(1), + scaffoldVersion: exports_external2.string().min(1).optional(), + manifestRef: ResourcePointerSchema.optional(), + target: ResourcePointerSchema, + status: ScaffoldInstallStatusSchema, + installedAt: TimestampSchema.optional(), + installer: ActorPointerSchema.optional(), + packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), + options: MetadataSchema.optional(), + generatedFiles: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + proofBundleRefs: exports_external2.array(ResourcePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.status === "installed" && !value.installedAt) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Installed scaffold records require installedAt", + path: ["installedAt"] + }); } -} -ZodLazy5.create = (getter, params) => { - return new ZodLazy5({ - getter, - typeName: ZodFirstPartyTypeKind5.ZodLazy, - ...processCreateParams4(params) - }); -}; - -class ZodLiteral5 extends ZodType5 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - received: ctx.data, - code: ZodIssueCode5.invalid_literal, - expected: this._def.value - }); - return INVALID4; - } - return { status: "valid", value: input.data }; + if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Installed scaffold records require generated files, evidence, or proof bundle refs", + path: ["generatedFiles"] + }); } - get value() { - return this._def.value; + if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Failed or partial scaffold records require evidence or proof bundle refs", + path: ["evidenceRefs"] + }); } -} -ZodLiteral5.create = (value, params) => { - return new ZodLiteral5({ - value, - typeName: ZodFirstPartyTypeKind5.ZodLiteral, - ...processCreateParams4(params) - }); -}; -function createZodEnum4(values, params) { - return new ZodEnum5({ - values, - typeName: ZodFirstPartyTypeKind5.ZodEnum, - ...processCreateParams4(params) - }); -} - -class ZodEnum5 extends ZodType5 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext4(ctx, { - expected: util4.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode5.invalid_type - }); - return INVALID4; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext4(ctx, { - received: ctx.data, - code: ZodIssueCode5.invalid_enum_value, - options: expectedValues +}); +var AppIdSchema = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); +var NpmPackageNameSchema = exports_external2.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); +var SemverSchema = exports_external2.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); +var GitShaSchema = exports_external2.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); +var GithubUrlSchema = NonEmptyStringSchema.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); +var AppLifecycleSchema = exports_external2.enum(["active", "stub", "deprecated", "archived"]); +var ReleaseChannelSchema = exports_external2.enum(["stable", "beta", "canary", "internal"]); +var AppMcpSurfaceSchema = exports_external2.object({ + transport: exports_external2.enum(["http", "stdio"]).default("http"), + bin: exports_external2.string().min(1).optional(), + url: UriSchema.optional() +}).strict(); +var AppHttpSurfaceSchema = exports_external2.object({ + healthPath: exports_external2.string().min(1).default("/health"), + port: exports_external2.number().int().positive().optional(), + baseUrl: UriSchema.optional() +}).strict(); +var AppSurfacesSchema = exports_external2.object({ + bins: exports_external2.array(exports_external2.string().min(1)).default([]), + mcp: AppMcpSurfaceSchema.optional(), + http: AppHttpSurfaceSchema.optional() +}).strict(); +var AppSchema = contractBaseSchema(SCHEMA_IDS.app).extend({ + appId: AppIdSchema, + npmName: NpmPackageNameSchema, + repoFolder: AppIdSchema, + githubUrl: GithubUrlSchema, + projectSlug: ProjectSlugSchema, + surfaces: AppSurfacesSchema.default({}), + lifecycle: AppLifecycleSchema, + releaseChannel: ReleaseChannelSchema.default("stable"), + summary: exports_external2.string().min(1).optional(), + tags: TagsSchema +}).strict().superRefine((value, ctx) => { + const seenBins = new Set; + for (const [index, bin] of value.surfaces.bins.entries()) { + if (seenBins.has(bin)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "App surface bins must be unique", + path: ["surfaces", "bins", index] }); - return INVALID4; } - return OK4(input.data); - } - get options() { - return this._def.values; + seenBins.add(bin); } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; +}); +var PublishPathSchema = exports_external2.enum(["skill", "ci", "backfilled"]); +var ReleaseSchema = contractBaseSchema(SCHEMA_IDS.release).extend({ + appId: AppIdSchema, + package: NpmPackageNameSchema, + version: SemverSchema, + gitSha: GitShaSchema, + publishedAt: TimestampSchema, + publishPath: PublishPathSchema, + changelogRef: ResourcePointerSchema.optional(), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "skill and ci releases require publish evidence; only backfilled releases may omit it", + path: ["evidenceRefs"] + }); } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; +}); +var RolloutActionSchema = exports_external2.enum(["install", "update", "rollback", "freeze-blocked"]); +var RolloutVerificationSchema = exports_external2.object({ + cliVersion: exports_external2.string().min(1).optional(), + mcpHealth: exports_external2.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() +}).strict().superRefine((value, ctx) => { + if (!value.cliVersion && value.mcpHealth === undefined) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Rollout verification requires at least one concrete verifier field" + }); } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; +}); +var RolloutRecordSchema = contractBaseSchema(SCHEMA_IDS.rolloutRecord).extend({ + appId: AppIdSchema, + package: NpmPackageNameSchema, + version: SemverSchema, + machine: NonEmptyStringSchema, + action: RolloutActionSchema, + result: ContractStatusSchema, + verifiedBy: RolloutVerificationSchema.optional(), + at: TimestampSchema, + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "freeze-blocked rollout records must report result blocked or skipped", + path: ["result"] + }); } - extract(values, newDef = this._def) { - return ZodEnum5.create(values, { - ...this._def, - ...newDef + const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; + const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; + if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Succeeded install/update rollout records require concrete verification", + path: ["verifiedBy"] }); } - exclude(values, newDef = this._def) { - return ZodEnum5.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef +}); +var AnnouncementChannelKindSchema = exports_external2.enum([ + "email", + "telegram", + "slack", + "discord", + "x", + "blog", + "rss", + "webhook", + "github", + "other" +]); +var AnnouncementDeliveryStatusSchema = exports_external2.enum([ + "pending", + "queued", + "sent", + "failed", + "skipped", + "suppressed" +]); +var AnnouncementChannelSchema = exports_external2.object({ + channel: AnnouncementChannelKindSchema, + status: AnnouncementDeliveryStatusSchema, + deliveredAt: TimestampSchema.optional(), + detail: exports_external2.string().min(1).optional() +}).strict().superRefine((value, ctx) => { + if (value.status === "sent" && !value.deliveredAt) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Sent announcement channels require deliveredAt", + path: ["deliveredAt"] }); } -} -ZodEnum5.create = createZodEnum4; - -class ZodNativeEnum4 extends ZodType5 { - _parse(input) { - const nativeEnumValues = util4.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType4.string && ctx.parsedType !== ZodParsedType4.number) { - const expectedValues = util4.objectValues(nativeEnumValues); - addIssueToContext4(ctx, { - expected: util4.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode5.invalid_type - }); - return INVALID4; - } - if (!this._cache) { - this._cache = new Set(util4.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util4.objectValues(nativeEnumValues); - addIssueToContext4(ctx, { - received: ctx.data, - code: ZodIssueCode5.invalid_enum_value, - options: expectedValues - }); - return INVALID4; - } - return OK4(input.data); + if (value.status === "failed" && !value.detail) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Failed announcement channels require detail", + path: ["detail"] + }); } - get enum() { - return this._def.values; +}); +var AnnouncementSchema = contractBaseSchema(SCHEMA_IDS.announcement).extend({ + campaignId: NonEmptyStringSchema, + appId: AppIdSchema.optional(), + releaseRef: ResourcePointerSchema.optional(), + channels: exports_external2.array(AnnouncementChannelSchema).min(1), + audienceRef: ResourcePointerSchema, + sentAt: TimestampSchema +}).strict().superRefine((value, ctx) => { + if (value.releaseRef && value.releaseRef.kind !== "release") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Announcement releaseRef must use resource kind release", + path: ["releaseRef", "kind"] + }); } -} -ZodNativeEnum4.create = (values, params) => { - return new ZodNativeEnum4({ - values, - typeName: ZodFirstPartyTypeKind5.ZodNativeEnum, - ...processCreateParams4(params) - }); -}; - -class ZodPromise5 extends ZodType5 { - unwrap() { - return this._def.type; + if (value.audienceRef.kind !== "audience") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Announcement audienceRef must use resource kind audience", + path: ["audienceRef", "kind"] + }); } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType4.promise && ctx.common.async === false) { - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.promise, - received: ctx.parsedType - }); - return INVALID4; - } - const promisified = ctx.parsedType === ZodParsedType4.promise ? ctx.data : Promise.resolve(ctx.data); - return OK4(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); +}); +var AudiencePredicateKindSchema = exports_external2.enum(["tag", "attribute", "group"]); +var AudiencePredicateOpSchema = exports_external2.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); +var AudiencePredicateValueSchema = exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]); +var AudiencePredicateSchema = exports_external2.object({ + kind: AudiencePredicateKindSchema, + key: exports_external2.string().min(1).optional(), + op: AudiencePredicateOpSchema.default("eq"), + value: AudiencePredicateValueSchema.optional(), + values: exports_external2.array(AudiencePredicateValueSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.kind === "attribute" && !value.key) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Attribute predicates require key", + path: ["key"] + }); } -} -ZodPromise5.create = (schema, params) => { - return new ZodPromise5({ - type: schema, - typeName: ZodFirstPartyTypeKind5.ZodPromise, - ...processCreateParams4(params) - }); -}; - -class ZodEffects4 extends ZodType5 { - innerType() { - return this._def.schema; + if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "eq/neq predicates require value", + path: ["value"] + }); } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind5.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "in/not_in predicates require values", + path: ["values"] + }); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext4(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID4; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID4; - if (result.status === "dirty") - return DIRTY4(result.value); - if (status.value === "dirty") - return DIRTY4(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID4; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID4; - if (result.status === "dirty") - return DIRTY4(result.value); - if (status.value === "dirty") - return DIRTY4(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID4; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID4; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid4(base)) - return INVALID4; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid4(base)) - return INVALID4; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util4.assertNever(effect); +}); +var AudienceDefinitionSchema = exports_external2.object({ + match: exports_external2.enum(["all", "any"]).default("all"), + predicates: exports_external2.array(AudiencePredicateSchema).min(1) +}).strict(); +var ConsentPolicySchema = exports_external2.enum(["opt_in", "opt_out", "transactional", "none"]); +var AudienceSchema = contractBaseSchema(SCHEMA_IDS.audience).extend({ + audienceId: AppIdSchema, + name: NonEmptyStringSchema, + definition: AudienceDefinitionSchema, + consentPolicy: ConsentPolicySchema, + suppressionSyncedAt: OptionalTimestampSchema +}).strict(); +var FORBIDDEN_SHARED_CLOUD_RUNTIMES = ["@hasna/cloud", "open-cloud"]; +var AppCloudProviderSchema = exports_external2.enum([ + "aws", + "gcp", + "azure", + "cloudflare", + "vercel", + "neon", + "supabase", + "postgres", + "s3", + "rds", + "other" +]); +var AppCloudResourceSchema = exports_external2.object({ + id: exports_external2.string().min(1), + provider: AppCloudProviderSchema, + kind: exports_external2.enum([ + "database", + "bucket", + "queue", + "secret", + "function", + "worker", + "cache", + "topic", + "scheduler", + "object_store", + "other" + ]), + ownerPackage: exports_external2.string().min(1), + region: exports_external2.string().min(1).optional(), + accountId: exports_external2.string().min(1).optional(), + uri: UriSchema.optional(), + machineScoped: exports_external2.boolean().default(false) +}).strict(); +var AppCloudManifestSchema = contractBaseSchema(SCHEMA_IDS.appCloudManifest).extend({ + packageName: exports_external2.string().min(1), + packageVersion: exports_external2.string().min(1).optional(), + appId: exports_external2.string().min(1), + repository: ResourcePointerSchema.optional(), + storageMode: exports_external2.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), + cloudBoundary: exports_external2.enum(["none", "app_owned", "external_service", "local_cache"]), + cloudResources: exports_external2.array(AppCloudResourceSchema).default([]), + localCache: exports_external2.object({ + path: exports_external2.string().min(1).optional(), + pullMode: exports_external2.enum(["manual", "daemon", "ci", "none"]).default("manual"), + conflictPolicy: exports_external2.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") + }).strict().optional(), + forbiddenSharedRuntimes: exports_external2.array(exports_external2.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES]), + dependencies: exports_external2.array(exports_external2.string().min(1)).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES, ...value.forbiddenSharedRuntimes]); + if (effectiveForbiddenRuntimes.has(value.packageName)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "App-owned cloud manifests cannot be for a forbidden runtime", + path: ["packageName"] + }); } -} -ZodEffects4.create = (schema, effect, params) => { - return new ZodEffects4({ - schema, - typeName: ZodFirstPartyTypeKind5.ZodEffects, - effect, - ...processCreateParams4(params) - }); -}; -ZodEffects4.createWithPreprocess = (preprocess2, schema, params) => { - return new ZodEffects4({ - schema, - effect: { type: "preprocess", transform: preprocess2 }, - typeName: ZodFirstPartyTypeKind5.ZodEffects, - ...processCreateParams4(params) - }); -}; - -class ZodOptional5 extends ZodType5 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType4.undefined) { - return OK4(undefined); + for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES) { + if (!value.forbiddenSharedRuntimes.includes(runtime)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `forbiddenSharedRuntimes must include ${runtime}`, + path: ["forbiddenSharedRuntimes"] + }); } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; } -} -ZodOptional5.create = (type, params) => { - return new ZodOptional5({ - innerType: type, - typeName: ZodFirstPartyTypeKind5.ZodOptional, - ...processCreateParams4(params) - }); -}; - -class ZodNullable5 extends ZodType5 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType4.null) { - return OK4(null); + for (const runtime of effectiveForbiddenRuntimes) { + if (value.dependencies.includes(runtime)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `App-owned cloud manifests cannot depend on ${runtime}`, + path: ["dependencies"] + }); } - return this._def.innerType._parse(input); } - unwrap() { - return this._def.innerType; + if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "local_only storage requires cloudBoundary none", + path: ["cloudBoundary"] + }); } -} -ZodNullable5.create = (type, params) => { - return new ZodNullable5({ - innerType: type, - typeName: ZodFirstPartyTypeKind5.ZodNullable, - ...processCreateParams4(params) - }); -}; - -class ZodDefault5 extends ZodType5 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType4.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx + if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "app_owned_cloud storage requires cloudBoundary app_owned", + path: ["cloudBoundary"] }); } - removeDefault() { - return this._def.innerType; + if (value.storageMode === "hybrid_local_cache") { + if (value.cloudBoundary !== "local_cache") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "hybrid_local_cache storage requires cloudBoundary local_cache", + path: ["cloudBoundary"] + }); + } + if (!value.localCache) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "hybrid_local_cache storage requires localCache settings", + path: ["localCache"] + }); + } } -} -ZodDefault5.create = (type, params) => { - return new ZodDefault5({ - innerType: type, - typeName: ZodFirstPartyTypeKind5.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams4(params) - }); -}; - -class ZodCatch5 extends ZodType5 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync4(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError5(newCtx.common.issues); - }, - input: newCtx.data - }) - }; + if (value.storageMode === "external_service") { + if (value.cloudBoundary !== "external_service") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "external_service storage requires cloudBoundary external_service", + path: ["cloudBoundary"] + }); + } + if (value.cloudResources.length > 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "external_service storage must not declare app-owned cloudResources", + path: ["cloudResources"] }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError5(newCtx.common.issues); - }, - input: newCtx.data - }) - }; } } - removeCatch() { - return this._def.innerType; + if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Cloud-backed storage modes require explicit app-owned cloudResources", + path: ["cloudResources"] + }); } -} -ZodCatch5.create = (type, params) => { - return new ZodCatch5({ - innerType: type, - typeName: ZodFirstPartyTypeKind5.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams4(params) - }); -}; - -class ZodNaN5 extends ZodType5 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType4.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext4(ctx, { - code: ZodIssueCode5.invalid_type, - expected: ZodParsedType4.nan, - received: ctx.parsedType + if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "cloudBoundary none cannot declare cloudResources", + path: ["cloudResources"] + }); + } + value.cloudResources.forEach((resource, index) => { + if (resource.ownerPackage !== value.packageName) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Cloud resources must be owned by the app package that declares the manifest", + path: ["cloudResources", index, "ownerPackage"] }); - return INVALID4; } - return { status: "valid", value: input.data }; - } -} -ZodNaN5.create = (params) => { - return new ZodNaN5({ - typeName: ZodFirstPartyTypeKind5.ZodNaN, - ...processCreateParams4(params) }); -}; -var BRAND4 = Symbol("zod_brand"); - -class ZodBranded4 extends ZodType5 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); +}); +var NoCloudCheckKindSchema = exports_external2.enum([ + "package_manifest", + "lockfile", + "source_import", + "runtime_config", + "packed_artifact", + "published_metadata", + "app_cloud_manifest", + "remote_config", + "boundary_doc", + "other" +]); +var NoCloudFindingSeveritySchema = exports_external2.enum(["low", "medium", "high", "critical"]); +var NoCloudFindingSchema = exports_external2.object({ + id: exports_external2.string().min(1), + kind: NoCloudCheckKindSchema, + severity: NoCloudFindingSeveritySchema, + path: exports_external2.string().min(1).optional(), + packageName: exports_external2.string().min(1).optional(), + pattern: exports_external2.string().min(1), + message: exports_external2.string().min(1), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict(); +var NoCloudCheckResultSchema = exports_external2.object({ + id: exports_external2.string().min(1), + kind: NoCloudCheckKindSchema, + status: ContractStatusSchema, + target: exports_external2.string().min(1), + command: exports_external2.string().min(1).optional(), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + findings: exports_external2.array(NoCloudFindingSchema).default([]) +}).strict(); +var NoCloudEvidencePackSchema = contractBaseSchema(SCHEMA_IDS.noCloudEvidencePack).extend({ + subject: ResourcePointerSchema, + packageName: exports_external2.string().min(1).optional(), + packageVersion: exports_external2.string().min(1).optional(), + generatedBy: ActorPointerSchema.optional(), + scanMode: exports_external2.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), + status: ContractStatusSchema, + verdict: exports_external2.enum(["passed", "failed", "warning", "not_run"]), + appCloudManifest: AppCloudManifestSchema.optional(), + checks: exports_external2.array(NoCloudCheckResultSchema).min(1), + findings: exports_external2.array(NoCloudFindingSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + const allFindings = [...value.findings, ...value.checks.flatMap((check2) => check2.findings)]; + const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); + if (value.verdict === "passed") { + if (value.status !== "succeeded") { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); + } + if (blockingFindings.length > 0) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); + } + if (value.checks.some((check2) => check2.status !== "succeeded")) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); + } } - unwrap() { - return this._def.type; + if (value.verdict === "failed" && allFindings.length === 0) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); } -} - -class ZodPipeline4 extends ZodType5 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID4; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY4(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx + if (value.status === "succeeded" && value.checks.some((check2) => check2.status === "failed")) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); + } + value.checks.forEach((check2, index) => { + const checkBlockingFindings = check2.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); + if (check2.status === "succeeded" && checkBlockingFindings.length > 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Succeeded no-cloud checks cannot contain high or critical findings", + path: ["checks", index, "findings"] }); - if (inResult.status === "aborted") - return INVALID4; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx + } + }); +}); +var ProofCheckResultSchema = exports_external2.object({ + checkId: exports_external2.string().min(1), + status: ContractStatusSchema, + summary: exports_external2.string().min(1).optional(), + startedAt: OptionalTimestampSchema, + finishedAt: OptionalTimestampSchema, + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) +}).strict(); +var ProofBundleSchema = contractBaseSchema(SCHEMA_IDS.proofBundle).extend({ + subject: ResourcePointerSchema, + validationPlanRef: ResourcePointerSchema.optional(), + status: ContractStatusSchema, + verdict: exports_external2.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), + checks: exports_external2.array(ProofCheckResultSchema).default([]), + verifier: ActorPointerSchema.optional(), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + residualRisks: exports_external2.array(exports_external2.string().min(1)).default([]), + freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") +}).strict().superRefine((value, ctx) => { + if (value.verdict === "passed") { + if (value.status !== "succeeded") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Passed proof bundles must have status succeeded", + path: ["status"] + }); + } + if (value.checks.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Passed proof bundles require at least one check result", + path: ["checks"] + }); + } + value.checks.forEach((check2, index) => { + if (check2.status !== "succeeded") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Passed proof bundles require all checks to have status succeeded", + path: ["checks", index, "status"] }); } + }); + const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check2) => check2.evidenceRefs.length > 0); + if (!hasEvidence) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Passed proof bundles require evidence", + path: ["evidenceRefs"] + }); + } + if (!value.verifier) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Passed proof bundles require a verifier", + path: ["verifier"] + }); } } - static create(a, b) { - return new ZodPipeline4({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind5.ZodPipeline + if (value.verdict === "not_run" && value.checks.length > 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Not-run proof bundles cannot include check results", + path: ["checks"] }); } -} - -class ZodReadonly5 extends ZodType5 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid4(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync4(result) ? result.then((data) => freeze(data)) : freeze(result); + if (value.verdict === "failed" && !value.checks.some((check2) => check2.status === "failed") && value.evidenceRefs.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Failed proof bundles require a failed check or evidence", + path: ["checks"] + }); } - unwrap() { - return this._def.innerType; +}); +var WorkRunSchema = contractBaseSchema(SCHEMA_IDS.workRun).extend({ + objective: exports_external2.string().min(1), + status: ContractStatusSchema, + actor: ActorPointerSchema, + traceId: exports_external2.string().min(1).optional(), + startedAt: OptionalTimestampSchema, + finishedAt: OptionalTimestampSchema, + constraints: exports_external2.array(exports_external2.string().min(1)).default([]), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + decisions: exports_external2.array(DecisionEnvelopeSchema).default([]), + costEstimates: exports_external2.array(CostEstimateSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + validationPlanRefs: exports_external2.array(ResourcePointerSchema).default([]), + proofBundleRefs: exports_external2.array(ResourcePointerSchema).default([]) +}).strict().superRefine((value, ctx) => { + if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "finishedAt must be after or equal to startedAt", + path: ["finishedAt"] + }); } -} -ZodReadonly5.create = (type, params) => { - return new ZodReadonly5({ - innerType: type, - typeName: ZodFirstPartyTypeKind5.ZodReadonly, - ...processCreateParams4(params) - }); -}; -function cleanParams4(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom5(check2, _params = {}, fatal) { - if (check2) - return ZodAny5.create().superRefine((data, ctx) => { - const r = check2(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams4(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams4(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; + if (TerminalStatuses.has(value.status) && !value.finishedAt) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Terminal work runs require finishedAt", + path: ["finishedAt"] }); - return ZodAny5.create(); -} -var late4 = { - object: ZodObject5.lazycreate -}; -var ZodFirstPartyTypeKind5; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind5 || (ZodFirstPartyTypeKind5 = {})); -var instanceOfType4 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom5((data) => data instanceof cls, params); -var stringType4 = ZodString5.create; -var numberType4 = ZodNumber5.create; -var nanType4 = ZodNaN5.create; -var bigIntType4 = ZodBigInt5.create; -var booleanType4 = ZodBoolean5.create; -var dateType4 = ZodDate5.create; -var symbolType4 = ZodSymbol5.create; -var undefinedType4 = ZodUndefined5.create; -var nullType4 = ZodNull5.create; -var anyType4 = ZodAny5.create; -var unknownType4 = ZodUnknown5.create; -var neverType4 = ZodNever5.create; -var voidType4 = ZodVoid5.create; -var arrayType4 = ZodArray5.create; -var objectType4 = ZodObject5.create; -var strictObjectType4 = ZodObject5.strictCreate; -var unionType4 = ZodUnion5.create; -var discriminatedUnionType4 = ZodDiscriminatedUnion5.create; -var intersectionType4 = ZodIntersection5.create; -var tupleType4 = ZodTuple5.create; -var recordType4 = ZodRecord5.create; -var mapType4 = ZodMap5.create; -var setType4 = ZodSet5.create; -var functionType4 = ZodFunction5.create; -var lazyType4 = ZodLazy5.create; -var literalType4 = ZodLiteral5.create; -var enumType4 = ZodEnum5.create; -var nativeEnumType4 = ZodNativeEnum4.create; -var promiseType4 = ZodPromise5.create; -var effectsType4 = ZodEffects4.create; -var optionalType4 = ZodOptional5.create; -var nullableType4 = ZodNullable5.create; -var preprocessType4 = ZodEffects4.createWithPreprocess; -var pipelineType4 = ZodPipeline4.create; -var ostring4 = () => stringType4().optional(); -var onumber4 = () => numberType4().optional(); -var oboolean4 = () => booleanType4().optional(); -var coerce4 = { - string: (arg) => ZodString5.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber5.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean5.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt5.create({ ...arg, coerce: true }), - date: (arg) => ZodDate5.create({ ...arg, coerce: true }) -}; -var NEVER5 = INVALID4; -var SCHEMA_IDS4 = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema4 = exports_external5.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema4 = exports_external5.string().datetime(); -var NonEmptyStringSchema4 = exports_external5.string().trim().min(1); -var UriSchema4 = NonEmptyStringSchema4.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema4 = exports_external5.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema4 = exports_external5.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema4 = exports_external5.record(exports_external5.unknown()); -var TagsSchema4 = exports_external5.array(exports_external5.string().min(1)).default([]); -var OptionalTimestampSchema4 = TimestampSchema4.nullable().optional(); -var TerminalStatuses4 = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema4 = exports_external5.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema4(schema) { - return exports_external5.object({ - schema: exports_external5.literal(schema), - id: exports_external5.string().min(1), - createdAt: TimestampSchema4, - updatedAt: OptionalTimestampSchema4, - metadata: MetadataSchema4.optional() - }).strict(); -} -var ContractEnvelopeSchema4 = exports_external5.object({ - schema: SchemaIdSchema4, - id: exports_external5.string().min(1), - createdAt: TimestampSchema4, - updatedAt: OptionalTimestampSchema4, - metadata: MetadataSchema4.optional() -}).strict(); -var ActorKindSchema4 = exports_external5.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema4 = contractBaseSchema4(SCHEMA_IDS4.actorRef).extend({ - kind: ActorKindSchema4, - name: exports_external5.string().min(1).optional(), - provider: exports_external5.string().min(1).optional(), - accountId: exports_external5.string().min(1).optional(), - machineId: exports_external5.string().min(1).optional(), - capabilities: exports_external5.array(exports_external5.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema4 = exports_external5.object({ - kind: ActorKindSchema4, - id: exports_external5.string().min(1), - name: exports_external5.string().min(1).optional(), - provider: exports_external5.string().min(1).optional(), - accountId: exports_external5.string().min(1).optional(), - machineId: exports_external5.string().min(1).optional() -}).strict(); -var ResourceKindSchema4 = exports_external5.enum([ - "task", - "project", + } + const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; + if (value.status === "succeeded" && !hasEvidence) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Succeeded work runs require evidence or a proof bundle", + path: ["evidenceRefs"] + }); + } + if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", + path: ["evidenceRefs"] + }); + } +}); +var TASK_TO_PR_ROLE_AUTHORITIES = Object.freeze({ + work_run: Object.freeze(["codewith"]), + root_request: Object.freeze(["todos"]), + pr_group: Object.freeze(["todos"]), + leaf_task: Object.freeze(["todos"]), + attempt: Object.freeze(["todos"]), + writer_generation: Object.freeze(["todos"]), + writer_lease: Object.freeze(["repos"]), + writer_fence: Object.freeze(["repos"]), + provider_profile: Object.freeze(["codewith"]), + provider_route: Object.freeze(["codewith"]), + admission: Object.freeze(["codewith"]), + worker_actor: Object.freeze(["codewith"]), + worker: Object.freeze(["codewith"]), + runtime: Object.freeze(["codewith"]), + repo: Object.freeze(["repos"]), + worktree: Object.freeze(["repos"]), + branch: Object.freeze(["repos"]), + event_stream: Object.freeze(["todos"]), + replay_cursor: Object.freeze(["todos"]), + handoff: Object.freeze(["todos"]), + pull_request: Object.freeze(["todos"]), + commit: Object.freeze(["repos"]), + review: Object.freeze(["review"]), + reviewer: Object.freeze(["review"]), + review_run: Object.freeze(["review"]), + proof_bundle: Object.freeze(["review"]), + repair_cycle: Object.freeze(["todos"]), + merge_guard: Object.freeze(["todos"]), + merge_operator: Object.freeze(["merge_provider"]), + merge_operator_run: Object.freeze(["merge_provider"]), + merge_guard_receipt: Object.freeze(["merge_provider"]), + merge_outcome: Object.freeze(["merge_provider"]), + recovery: Object.freeze(["todos"]), + cancellation: Object.freeze(["todos"]), + cleanup_eligibility: Object.freeze(["repos"]), + cleanup_outcome: Object.freeze(["repos"]), + rollback_plan: Object.freeze(["todos"]), + rollback_outcome: Object.freeze(["repos"]), + terminal_disposition: Object.freeze(["todos"]), + openloops_invocation: Object.freeze(["openloops"]), + adapter_extension: Object.freeze(["adapter"]) +}); +var TaskToPrRefRoleSchema = exports_external2.enum([ + "work_run", + "root_request", + "pr_group", + "leaf_task", + "attempt", + "writer_generation", + "writer_lease", + "writer_fence", + "provider_profile", + "provider_route", + "admission", + "worker_actor", + "worker", + "runtime", "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", + "worktree", "branch", + "event_stream", + "replay_cursor", + "handoff", "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", + "commit", + "review", + "reviewer", + "review_run", "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" + "repair_cycle", + "merge_guard", + "merge_operator", + "merge_operator_run", + "merge_guard_receipt", + "merge_outcome", + "recovery", + "cancellation", + "cleanup_eligibility", + "cleanup_outcome", + "rollback_plan", + "rollback_outcome", + "terminal_disposition", + "openloops_invocation", + "adapter_extension" +]); +var TaskToPrAuthoritySchema = exports_external2.enum([ + "todos", + "codewith", + "repos", + "review", + "merge_provider", + "openloops", + "adapter" +]); +var LowerSha256DigestSchema = exports_external2.string().regex(/^[a-f0-9]{64}$/); +var OpaqueTaskToPrIdSchema = exports_external2.string().trim().min(3).max(256); +var NonsemanticOpaqueSuffixPattern = /^[a-f0-9]{32}$/; +function deriveTaskToPrRefId(role, authority, digest) { + return `${role}:${authority}:opaque-${digest.slice(0, 32)}`; +} +function deriveTaskToPrEvidenceId(digest) { + return `evidence:opaque-${digest.slice(0, 32)}`; +} +var TaskToPrProjectionIdSchema = OpaqueTaskToPrIdSchema.refine((value) => { + const prefix = "task_to_pr_projection:opaque-"; + const suffix = value.startsWith(prefix) ? value.slice(prefix.length) : ""; + return NonsemanticOpaqueSuffixPattern.test(suffix); +}, "Projection ids must use a nonsemantic 128-bit lowercase hexadecimal surrogate"); +var TaskToPrAttemptNonceSchema = OpaqueTaskToPrIdSchema.refine((value) => { + const prefix = "attempt_nonce:opaque-"; + const suffix = value.startsWith(prefix) ? value.slice(prefix.length) : ""; + return NonsemanticOpaqueSuffixPattern.test(suffix); +}, "Attempt nonces must use a nonsemantic 128-bit lowercase hexadecimal surrogate"); +var SensitiveTaskToPrRoles = new Set([ + "writer_lease", + "writer_fence", + "provider_profile", + "provider_route", + "admission", + "worker_actor", + "worker", + "runtime", + "worktree", + "merge_operator", + "merge_operator_run", + "merge_guard_receipt", + "merge_outcome", + "openloops_invocation", + "adapter_extension" ]); -var ResourceRefSchema4 = contractBaseSchema4(SCHEMA_IDS4.resourceRef).extend({ - kind: ResourceKindSchema4, - name: exports_external5.string().min(1).optional(), - uri: UriSchema4.optional(), - externalId: NonEmptyStringSchema4.optional(), - sourcePackage: NonEmptyStringSchema4.optional(), - tags: TagsSchema4 +var TaskToPrRefSchema = exports_external2.object({ + role: TaskToPrRefRoleSchema, + authority: TaskToPrAuthoritySchema, + id: OpaqueTaskToPrIdSchema, + digest: LowerSha256DigestSchema, + redaction: exports_external2.enum(["none", "partial", "full"]) }).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { + const allowedAuthorities = TASK_TO_PR_ROLE_AUTHORITIES[value.role]; + if (!allowedAuthorities.includes(value.authority)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] + code: exports_external2.ZodIssueCode.custom, + message: `${value.role} refs must be owned by ${allowedAuthorities.join(" or ")}`, + path: ["authority"] + }); + } + if (SensitiveTaskToPrRoles.has(value.role) && value.redaction === "none") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `${value.role} refs must be redacted and cannot carry a raw locator or credential`, + path: ["redaction"] + }); + } + const expectedId = deriveTaskToPrRefId(value.role, value.authority, value.digest); + if (value.id !== expectedId) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Reference ids must be nonsemantic authority-bound surrogates derived from the canonical role, authority, and owner-record digest", + path: ["id"] }); } }); -var ResourcePointerSchema4 = exports_external5.object({ - kind: ResourceKindSchema4, - id: exports_external5.string().min(1), - name: exports_external5.string().min(1).optional(), - uri: UriSchema4.optional(), - externalId: NonEmptyStringSchema4.optional(), - sourcePackage: NonEmptyStringSchema4.optional(), - tags: TagsSchema4 +var TaskToPrEvidenceRefSchema = exports_external2.object({ + id: OpaqueTaskToPrIdSchema, + digest: LowerSha256DigestSchema, + redaction: exports_external2.enum(["partial", "full"]) }).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { + if (value.id !== deriveTaskToPrEvidenceId(value.digest)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] + code: exports_external2.ZodIssueCode.custom, + message: "Evidence ids must be nonsemantic owner-resolvable surrogates derived from their canonical digest", + path: ["id"] }); } }); -var EvidenceKindSchema4 = exports_external5.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema4 = exports_external5.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema4 = contractBaseSchema4(SCHEMA_IDS4.evidenceRef).extend({ - kind: EvidenceKindSchema4, - uri: UriSchema4, - sha256: Sha256DigestSchema4.optional(), - summary: exports_external5.string().min(1).optional(), - contentType: exports_external5.string().min(1).optional(), - sizeBytes: exports_external5.number().int().nonnegative().optional(), - redaction: RedactionStateSchema4.default("unknown"), - producer: ActorPointerSchema4.optional(), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - tags: TagsSchema4 -}).strict(); -var EvidencePointerSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - kind: EvidenceKindSchema4.optional(), - uri: UriSchema4.optional(), - sha256: Sha256DigestSchema4.optional(), - summary: exports_external5.string().min(1).optional() -}).strict(); -var CostEstimateSchema4 = contractBaseSchema4(SCHEMA_IDS4.costEstimate).extend({ - currency: exports_external5.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external5.number().int().nonnegative(), - provider: exports_external5.string().min(1).optional(), - model: exports_external5.string().min(1).optional(), - accountId: exports_external5.string().min(1).optional(), - promptTokens: exports_external5.number().int().nonnegative().optional(), - completionTokens: exports_external5.number().int().nonnegative().optional(), - totalTokens: exports_external5.number().int().nonnegative().optional(), - basis: exports_external5.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]) +function requireDistinctTaskToPrEvidenceRefs(stopEvidenceRef, leaseRevocationEvidenceRef, ctx, path) { + if (stopEvidenceRef.id === leaseRevocationEvidenceRef.id || stopEvidenceRef.digest === leaseRevocationEvidenceRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Stop and lease-revocation facts require distinct evidence identities and digests", + path + }); + } +} +function taskToPrRefFor(role) { + return TaskToPrRefSchema.refine((value) => value.role === role, { + message: `Reference must use role ${role}`, + path: ["role"] + }); +} +function sameTaskToPrRef(left, right) { + return left.role === right.role && left.authority === right.authority && left.id === right.id && left.digest === right.digest && left.redaction === right.redaction; +} +function sameTaskToPrCanonicalRefId(left, right) { + return left.role === right.role && left.authority === right.authority && left.id === right.id; +} +function requireFreshTaskToPrRef(prior, successor, ctx, path, label) { + if (sameTaskToPrCanonicalRefId(prior, successor)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `${label} requires a fresh canonical role/authority/id`, + path + }); + } + if (prior.digest === successor.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `${label} requires a fresh canonical digest`, + path + }); + } +} +function taskToPrCanonicalRefKey(ref) { + return `${ref.role}\x00${ref.authority}\x00${ref.id}`; +} +function sameGitObjectId(left, right) { + return left.algorithm === right.algorithm && left.value === right.value; +} +var TaskToPrGitObjectIdSchema = exports_external2.object({ + algorithm: exports_external2.enum(["sha1", "sha256"]), + value: exports_external2.string().regex(/^[a-f0-9]+$/) }).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { + const requiredLength = value.algorithm === "sha1" ? 40 : 64; + if (value.value.length !== requiredLength) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] + code: exports_external2.ZodIssueCode.custom, + message: `${value.algorithm} object ids must contain exactly ${requiredLength} lowercase hex characters`, + path: ["value"] }); } }); -var DecisionStatusSchema4 = exports_external5.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema4 = contractBaseSchema4(SCHEMA_IDS4.decisionEnvelope).extend({ - decisionType: exports_external5.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema4, - actor: ActorPointerSchema4.optional(), - traceId: exports_external5.string().min(1).optional(), - inputHash: HashStringSchema4.optional(), - policyBundleId: exports_external5.string().min(1).optional(), - selected: exports_external5.array(ResourcePointerSchema4).default([]), - skipped: exports_external5.array(ResourcePointerSchema4).default([]), - reason: exports_external5.string().min(1), - obligations: exports_external5.array(exports_external5.string().min(1)).default([]), - redactions: exports_external5.array(exports_external5.string().min(1)).default([]), - costEstimate: CostEstimateSchema4.optional(), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) +function deriveTaskToPrIdentityDigest(input) { + if (input.canonicalizationVersion === 1) { + const legacyCanonicalBinding = JSON.stringify([ + "hasna.task_to_pr_projection.binding.v1", + input.canonicalizationVersion, + input.rootRequestRef.id, + input.rootRequestRef.digest, + input.prGroupRef.id, + input.prGroupRef.digest, + input.leafTaskRef.id, + input.leafTaskRef.digest, + input.repoRef.id, + input.repoRef.digest, + input.baseHead.algorithm, + input.baseHead.value, + input.frozenScopeDigest + ]); + return createHash22("sha256").update(legacyCanonicalBinding, "utf8").digest("hex"); + } + const canonicalBinding = JSON.stringify([ + "hasna.task_to_pr_projection.binding.v2", + input.canonicalizationVersion, + ...[input.rootRequestRef, input.prGroupRef, input.leafTaskRef, input.repoRef, input.worktreeRef, input.branchRef].flatMap((ref) => [ref.role, ref.authority, ref.id, ref.digest]), + input.baseHead.algorithm, + input.baseHead.value, + input.frozenScopeDigest + ]); + return createHash22("sha256").update(canonicalBinding, "utf8").digest("hex"); +} +var TaskToPrAttemptSchema = exports_external2.object({ + ref: taskToPrRefFor("attempt"), + nonce: TaskToPrAttemptNonceSchema, + admissionRef: taskToPrRefFor("admission"), + admissionWriterGenerationRef: taskToPrRefFor("writer_generation"), + workerActorRef: taskToPrRefFor("worker_actor"), + workerRef: taskToPrRefFor("worker"), + runtimeRef: taskToPrRefFor("runtime"), + writerGenerationRef: taskToPrRefFor("writer_generation"), + writerLeaseRef: taskToPrRefFor("writer_lease"), + writerFenceRef: taskToPrRefFor("writer_fence"), + providerProfileRef: taskToPrRefFor("provider_profile"), + providerRouteRef: taskToPrRefFor("provider_route") +}).strict(); +var TaskToPrRepositoryBindingSchema = exports_external2.object({ + repoRef: taskToPrRefFor("repo"), + worktreeRef: taskToPrRefFor("worktree"), + branchRef: taskToPrRefFor("branch"), + baseHead: TaskToPrGitObjectIdSchema, + branchHead: TaskToPrGitObjectIdSchema +}).strict(); +var TaskToPrEventCursorSchema = exports_external2.object({ + streamRef: taskToPrRefFor("event_stream"), + replayCursorRef: taskToPrRefFor("replay_cursor"), + sequence: exports_external2.number().int().safe().nonnegative(), + prefixDigest: LowerSha256DigestSchema +}).strict(); +var TaskToPrHandoffSchema = exports_external2.object({ + ref: taskToPrRefFor("handoff"), + previousAttemptRef: taskToPrRefFor("attempt"), + nextAttemptRef: taskToPrRefFor("attempt"), + previousWriterGenerationRef: taskToPrRefFor("writer_generation"), + nextWriterGenerationRef: taskToPrRefFor("writer_generation"), + stoppedWorkRunRef: taskToPrRefFor("work_run"), + stopEvidenceRef: TaskToPrEvidenceRefSchema, + leaseRevocationEvidenceRef: TaskToPrEvidenceRefSchema }).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); + requireFreshTaskToPrRef(value.previousAttemptRef, value.nextAttemptRef, ctx, ["nextAttemptRef"], "Handoff attempt rotation"); + requireFreshTaskToPrRef(value.previousWriterGenerationRef, value.nextWriterGenerationRef, ctx, ["nextWriterGenerationRef"], "Handoff writer-generation rotation"); + requireDistinctTaskToPrEvidenceRefs(value.stopEvidenceRef, value.leaseRevocationEvidenceRef, ctx, ["leaseRevocationEvidenceRef"]); +}); +var TaskToPrReviewBindingSchema = exports_external2.object({ + ref: taskToPrRefFor("review"), + pullRequestRef: taskToPrRefFor("pull_request"), + base: TaskToPrGitObjectIdSchema, + head: TaskToPrGitObjectIdSchema, + reviewerRef: taskToPrRefFor("reviewer"), + reviewRunRef: taskToPrRefFor("review_run"), + proofBundleRef: taskToPrRefFor("proof_bundle"), + verdict: exports_external2.enum(["approved", "changes_requested", "blocked"]), + reviewedAt: TimestampSchema +}).strict(); +var TaskToPrExactHeadBindingSchema = exports_external2.object({ + pullRequestRef: taskToPrRefFor("pull_request"), + remoteBranchRef: taskToPrRefFor("branch"), + expectedBase: TaskToPrGitObjectIdSchema, + providerPullRequestBase: TaskToPrGitObjectIdSchema, + localHead: TaskToPrGitObjectIdSchema, + remoteHead: TaskToPrGitObjectIdSchema, + providerPullRequestHead: TaskToPrGitObjectIdSchema, + equalityProofRef: taskToPrRefFor("proof_bundle"), + ciProofBundleRefs: exports_external2.array(taskToPrRefFor("proof_bundle")).min(1), + verifiedAt: TimestampSchema +}).strict().superRefine((value, ctx) => { + if (!sameGitObjectId(value.expectedBase, value.providerPullRequestBase)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Expected and provider-observed pull-request bases must be exactly equal", + path: ["providerPullRequestBase"] + }); } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); + if (!sameGitObjectId(value.localHead, value.remoteHead) || !sameGitObjectId(value.localHead, value.providerPullRequestHead)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Local, remote, and provider pull-request heads must be exactly equal", + path: ["providerPullRequestHead"] + }); } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } + const proofKeys = value.ciProofBundleRefs.map(taskToPrCanonicalRefKey); + if (new Set(proofKeys).size !== proofKeys.length) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "CI proof bundle refs must have unique canonical identities", + path: ["ciProofBundleRefs"] + }); } - if (value.status === "approval_required" && value.obligations.length === 0) { + const proofDigests = value.ciProofBundleRefs.map((ref) => ref.digest); + if (new Set(proofDigests).size !== proofDigests.length) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] + code: exports_external2.ZodIssueCode.custom, + message: "CI proof bundle refs must have unique canonical digests", + path: ["ciProofBundleRefs"] + }); + } + if (value.ciProofBundleRefs.some((ref) => sameTaskToPrCanonicalRefId(ref, value.equalityProofRef))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Head-equality and CI proof refs must have distinct canonical identities", + path: ["ciProofBundleRefs"] + }); + } + if (value.ciProofBundleRefs.some((ref) => ref.digest === value.equalityProofRef.digest)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Head-equality and CI proof refs must have distinct canonical digests", + path: ["ciProofBundleRefs"] }); } }); -var CapabilityCardSchema4 = contractBaseSchema4(SCHEMA_IDS4.capabilityCard).extend({ - kind: exports_external5.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external5.string().min(1), - version: exports_external5.string().min(1).optional(), - status: exports_external5.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external5.array(exports_external5.string().min(1)).default([]), - limitations: exports_external5.array(exports_external5.string().min(1)).default([]), - riskLevel: exports_external5.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema4.optional(), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict(); -var ProviderModeSchema4 = exports_external5.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema4 = exports_external5.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema4 = exports_external5.object({ - refName: NonEmptyStringSchema4, - requiredForModes: exports_external5.array(ProviderModeSchema4).min(1), - allowedSecretInputs: exports_external5.array(exports_external5.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema4, - revocationCheck: exports_external5.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema4 = exports_external5.object({ - operation: NonEmptyStringSchema4, - supportedModes: exports_external5.array(ProviderModeSchema4).min(1), - sideEffectClass: ProviderSideEffectClassSchema4, - requiresApproval: exports_external5.boolean().default(false), - requiresIdempotencyKey: exports_external5.boolean().default(false), - requiresSandboxEvidence: exports_external5.boolean().default(false), - requiresRollbackOrRevocation: exports_external5.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema4.optional(), - noSideEffectSmoke: NonEmptyStringSchema4.optional(), - reconciliation: NonEmptyStringSchema4.optional() +var TaskToPrRepairStateSchema = exports_external2.object({ + ref: taskToPrRefFor("repair_cycle"), + cycle: exports_external2.number().int().min(0).max(2), + cap: exports_external2.literal(2), + exhausted: exports_external2.boolean(), + latestRepairRef: taskToPrRefFor("repair_cycle").optional() }).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } + if (value.exhausted !== (value.cycle === value.cap)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Repair exhaustion must equal the cumulative cycle cap", + path: ["exhausted"] + }); + } + if (value.cycle === 0 && value.latestRepairRef) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Cycle zero cannot reference a repair", + path: ["latestRepairRef"] + }); + } + if (value.cycle > 0 && !value.latestRepairRef) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Non-zero repair state requires the latest immutable repair ref", + path: ["latestRepairRef"] + }); + } + if (value.latestRepairRef && sameTaskToPrCanonicalRefId(value.ref, value.latestRepairRef)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Repair-state and latest-repair refs must be distinct canonical records", + path: ["latestRepairRef"] + }); + } + if (value.latestRepairRef && value.ref.digest === value.latestRepairRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Repair-state and latest-repair refs must have distinct canonical digests", + path: ["latestRepairRef"] + }); } }); -var ProviderCapabilityCardSchema4 = exports_external5.object({ - providerId: NonEmptyStringSchema4, - appId: NonEmptyStringSchema4, - adapterId: NonEmptyStringSchema4, - ownerPackage: NonEmptyStringSchema4, - modes: exports_external5.array(ProviderModeSchema4).min(1), - defaultMode: ProviderModeSchema4, - credentialRequirements: exports_external5.array(CredentialRequirementSchema4).default([]), - operations: exports_external5.array(ProviderOperationCardSchema4).min(1), - rateLimitPosture: NonEmptyStringSchema4, - costPosture: NonEmptyStringSchema4.optional(), - auditEvents: exports_external5.array(NonEmptyStringSchema4).default([]), - redactionRules: exports_external5.array(NonEmptyStringSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) +var TaskToPrMergeGuardSchema = exports_external2.object({ + ref: taskToPrRefFor("merge_guard"), + pullRequestRef: taskToPrRefFor("pull_request"), + expectedBase: TaskToPrGitObjectIdSchema, + expectedHead: TaskToPrGitObjectIdSchema, + reviewRefs: exports_external2.array(taskToPrRefFor("review")).min(1), + proofBundleRefs: exports_external2.array(taskToPrRefFor("proof_bundle")).min(1), + operatorRef: taskToPrRefFor("merge_operator"), + operatorRunRef: taskToPrRefFor("merge_operator_run"), + providerGuardReceiptRef: taskToPrRefFor("merge_guard_receipt"), + mechanism: exports_external2.enum(["compare_and_swap", "queue_expected_head"]), + decision: exports_external2.enum(["eligible", "denied", "consumed", "revoked"]), + evaluatedAt: TimestampSchema }).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { + const uniqueReviews = new Set(value.reviewRefs.map((ref) => ref.id)); + if (uniqueReviews.size !== value.reviewRefs.length) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] + code: exports_external2.ZodIssueCode.custom, + message: "Merge guard review refs must be unique", + path: ["reviewRefs"] }); } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode2 of operationModes) { - if (!value.modes.includes(mode2)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: `operation mode ${mode2} is not declared in provider modes`, - path: ["operations"] - }); - } + const uniqueProofs = new Set(value.proofBundleRefs.map(taskToPrCanonicalRefKey)); + if (uniqueProofs.size !== value.proofBundleRefs.length) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge guard proof refs must have unique canonical identities", + path: ["proofBundleRefs"] + }); } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { + const uniqueProofDigests = new Set(value.proofBundleRefs.map((ref) => ref.digest)); + if (uniqueProofDigests.size !== value.proofBundleRefs.length) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge guard proof refs must have unique canonical digests", + path: ["proofBundleRefs"] + }); + } +}); +var TaskToPrMergeOutcomeSchema = exports_external2.object({ + ref: taskToPrRefFor("merge_outcome"), + guardRef: taskToPrRefFor("merge_guard"), + pullRequestRef: taskToPrRefFor("pull_request"), + expectedBase: TaskToPrGitObjectIdSchema, + observedBase: TaskToPrGitObjectIdSchema, + expectedHead: TaskToPrGitObjectIdSchema, + observedHead: TaskToPrGitObjectIdSchema, + status: exports_external2.enum(["merged", "closed_unmerged", "refused", "head_drift", "base_drift"]), + mergeCommitRef: taskToPrRefFor("commit").optional(), + finishedAt: TimestampSchema, + evidenceRefs: exports_external2.array(TaskToPrEvidenceRefSchema).min(1) +}).strict().superRefine((value, ctx) => { + const baseMatches = sameGitObjectId(value.expectedBase, value.observedBase); + const headMatches = sameGitObjectId(value.expectedHead, value.observedHead); + if (value.status === "merged") { + if (!baseMatches || !headMatches) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] + code: exports_external2.ZodIssueCode.custom, + message: "Merged outcomes require observed base and head to equal the guarded values", + path: [!baseMatches ? "observedBase" : "observedHead"] }); } - if (value.auditEvents.length === 0) { + if (!value.mergeCommitRef) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] + code: exports_external2.ZodIssueCode.custom, + message: "Merged outcomes require an immutable merge commit ref", + path: ["mergeCommitRef"] }); } + } else if (value.mergeCommitRef) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Unmerged outcomes cannot claim a merge commit", + path: ["mergeCommitRef"] + }); + } + if (value.status === "head_drift" && headMatches) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Head-drift outcomes require distinct expected and observed heads", + path: ["observedHead"] + }); + } + if (value.status === "head_drift" && !baseMatches) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Head-drift outcomes cannot also carry an unclassified base drift", + path: ["observedBase"] + }); + } + if (value.status === "base_drift" && baseMatches) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Base-drift outcomes require distinct expected and observed bases", + path: ["observedBase"] + }); + } + if (value.status === "base_drift" && !headMatches) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Base-drift outcomes cannot also carry an unclassified head drift", + path: ["observedHead"] + }); + } + if (!headMatches && value.status !== "head_drift") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Only a head_drift outcome may record an observed head that differs from the expected head", + path: ["observedHead"] + }); + } + if (!baseMatches && value.status !== "base_drift") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Only a base_drift outcome may record an observed base that differs from the expected base", + path: ["observedBase"] + }); } }); -var ProviderLiveModeTargetSchema4 = exports_external5.object({ - appId: NonEmptyStringSchema4, - repo: NonEmptyStringSchema4, - priority: exports_external5.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external5.array(NonEmptyStringSchema4).min(1), - firstOperations: exports_external5.array(NonEmptyStringSchema4).min(1), - blockedUntil: exports_external5.array(NonEmptyStringSchema4).default([]) +var TaskToPrMergeStateSchema = exports_external2.object({ + guard: TaskToPrMergeGuardSchema, + outcome: TaskToPrMergeOutcomeSchema.optional() }).strict(); -var ProviderLiveModeStandardSchema4 = contractBaseSchema4(SCHEMA_IDS4.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema4, - version: NonEmptyStringSchema4, - modes: exports_external5.array(ProviderModeSchema4).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode2) => modes.includes(mode2)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external5.array(NonEmptyStringSchema4).min(1), - liveMutationGate: exports_external5.object({ - requiredMode: exports_external5.literal("live_mutating"), - requiredChecks: exports_external5.array(NonEmptyStringSchema4).min(1), - forbiddenBypassSignals: exports_external5.array(NonEmptyStringSchema4).min(1), - disabledLiveSmoke: NonEmptyStringSchema4 - }).strict(), - noSideEffectSmoke: exports_external5.object({ - requiredForModes: exports_external5.array(ProviderModeSchema4).min(1), - commandEvidence: exports_external5.array(NonEmptyStringSchema4).min(1), - secretOutputScan: exports_external5.boolean().default(true) - }).strict(), - credentialPolicy: exports_external5.object({ - acceptedInputs: exports_external5.array(exports_external5.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external5.literal(false), - missingCredentialBehavior: exports_external5.literal("fail_closed"), - revocationCheckRequired: exports_external5.boolean().default(true) - }).strict(), - operationCards: exports_external5.array(ProviderCapabilityCardSchema4).min(1), - firstAdoptionTargets: exports_external5.array(ProviderLiveModeTargetSchema4).min(1), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) +var TaskToPrRecoverySchema = exports_external2.object({ + ref: taskToPrRefFor("recovery"), + priorAttemptRef: taskToPrRefFor("attempt"), + priorWriterGenerationRef: taskToPrRefFor("writer_generation"), + priorWorkRunRef: taskToPrRefFor("work_run"), + successorAttemptNonce: TaskToPrAttemptNonceSchema, + successorWriterGenerationRef: taskToPrRefFor("writer_generation"), + preservedStateRefs: exports_external2.array(TaskToPrRefSchema).min(1), + stopEvidenceRef: TaskToPrEvidenceRefSchema, + leaseRevocationEvidenceRef: TaskToPrEvidenceRefSchema }).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } + requireFreshTaskToPrRef(value.priorWriterGenerationRef, value.successorWriterGenerationRef, ctx, ["successorWriterGenerationRef"], "Recovery writer-generation rotation"); + requireDistinctTaskToPrEvidenceRefs(value.stopEvidenceRef, value.leaseRevocationEvidenceRef, ctx, ["leaseRevocationEvidenceRef"]); }); -var ContextPackItemSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - title: exports_external5.string().min(1).optional(), - summary: exports_external5.string().min(1), - text: exports_external5.string().optional(), - tokens: exports_external5.number().int().nonnegative().optional(), - source: EvidencePointerSchema4, - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]) -}).strict(); -var ContextPackSchema4 = contractBaseSchema4(SCHEMA_IDS4.contextPack).extend({ - objective: exports_external5.string().min(1), - budget: exports_external5.object({ - maxTokens: exports_external5.number().int().positive().optional(), - maxBytes: exports_external5.number().int().positive().optional() - }).strict().optional(), - items: exports_external5.array(ContextPackItemSchema4).default([]), - citations: exports_external5.array(EvidencePointerSchema4).default([]), - freshness: exports_external5.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external5.array(exports_external5.string().min(1)).default([]), - redactions: exports_external5.array(exports_external5.string().min(1)).default([]), - conflicts: exports_external5.array(exports_external5.string().min(1)).default([]), - uncertainty: exports_external5.string().min(1).optional() +var TaskToPrCancellationSchema = exports_external2.object({ + ref: taskToPrRefFor("cancellation"), + cancelledAttemptRef: taskToPrRefFor("attempt"), + preservedStateRefs: exports_external2.array(TaskToPrRefSchema).min(1), + evidenceRefs: exports_external2.array(TaskToPrEvidenceRefSchema).min(1) }).strict(); -var RelativeProjectPathSchema4 = NonEmptyStringSchema4.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema4 = exports_external5.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema4 = exports_external5.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema4 = exports_external5.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema4 = exports_external5.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema4 = contractBaseSchema4(SCHEMA_IDS4.integrationRef).extend({ - kind: ProjectIntegrationKindSchema4, - name: exports_external5.string().min(1), - projectId: ProjectSlugSchema4.optional(), - sourcePackage: NonEmptyStringSchema4.optional(), - externalId: NonEmptyStringSchema4.optional(), - uri: UriSchema4.optional(), - enabled: exports_external5.boolean().default(true), - readOnly: exports_external5.boolean().default(true), - capabilities: exports_external5.array(exports_external5.string().min(1)).default([]), - freshness: exports_external5.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema4.optional(), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - config: MetadataSchema4.optional() +var TaskToPrCleanupEligibilitySchema = exports_external2.object({ + ref: taskToPrRefFor("cleanup_eligibility"), + status: exports_external2.enum(["not_ready", "preserved", "blocked", "eligible"]), + targetWorktreeRef: taskToPrRefFor("worktree"), + eventCursorRef: taskToPrRefFor("replay_cursor"), + terminalDispositionRef: taskToPrRefFor("terminal_disposition"), + writerLeaseRef: taskToPrRefFor("writer_lease"), + leaseRevocationEvidenceRef: TaskToPrEvidenceRefSchema, + consumedEventEvidenceRef: TaskToPrEvidenceRefSchema, + evaluatedAt: TimestampSchema, + evidenceRefs: exports_external2.array(TaskToPrEvidenceRefSchema).min(1) }).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { + if (value.leaseRevocationEvidenceRef.id === value.consumedEventEvidenceRef.id || value.leaseRevocationEvidenceRef.digest === value.consumedEventEvidenceRef.digest) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup lease-revocation and consumed-event facts require distinct evidence identities and digests", + path: ["consumedEventEvidenceRef"] }); } }); -var ProjectLayoutSchema4 = exports_external5.object({ - schemaRoot: RelativeProjectPathSchema4.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema4.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema4.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema4.default("documents"), - reportsDir: RelativeProjectPathSchema4.default("reports"), - evidenceDir: RelativeProjectPathSchema4.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema4.default(".hasna/project/private") +var TaskToPrCleanupOutcomeSchema = exports_external2.object({ + ref: taskToPrRefFor("cleanup_outcome"), + eligibilityRef: taskToPrRefFor("cleanup_eligibility"), + targetWorktreeRef: taskToPrRefFor("worktree"), + status: exports_external2.enum(["preserved", "deleted", "failed", "skipped"]), + finishedAt: TimestampSchema, + evidenceRefs: exports_external2.array(TaskToPrEvidenceRefSchema).min(1) }).strict(); -var ProjectManifestSchema4 = contractBaseSchema4(SCHEMA_IDS4.projectManifest).extend({ - projectId: ProjectSlugSchema4, - slug: ProjectSlugSchema4, - name: exports_external5.string().min(1), - summary: exports_external5.string().min(1).optional(), - status: ProjectStatusSchema4.default("active"), - classification: ProjectClassificationSchema4.default("private"), - owner: ActorPointerSchema4.optional(), - layout: ProjectLayoutSchema4.default({}), - integrations: exports_external5.array(IntegrationRefSchema4).default([]), - renderManifests: exports_external5.array(ResourcePointerSchema4).default([]), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - tags: TagsSchema4 +var TaskToPrCleanupStateSchema = exports_external2.object({ + eligibility: TaskToPrCleanupEligibilitySchema, + outcome: TaskToPrCleanupOutcomeSchema.optional() }).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { + if (value.outcome && !sameTaskToPrRef(value.outcome.eligibilityRef, value.eligibility.ref)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup outcomes must bind the exact eligibility decision", + path: ["outcome", "eligibilityRef"] }); } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); + if (value.outcome && !sameTaskToPrRef(value.outcome.targetWorktreeRef, value.eligibility.targetWorktreeRef)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup eligibility and outcome must bind the same target worktree", + path: ["outcome", "targetWorktreeRef"] + }); + } + if (value.outcome?.status === "deleted" && value.eligibility.status !== "eligible") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Deletion requires an eligible cleanup decision", + path: ["outcome", "status"] + }); + } +}); +var TaskToPrRollbackSchema = exports_external2.object({ + plan: exports_external2.object({ + ref: taskToPrRefFor("rollback_plan"), + targetRef: exports_external2.union([taskToPrRefFor("commit"), taskToPrRefFor("branch")]), + createdAt: TimestampSchema + }).strict(), + outcome: exports_external2.object({ + ref: taskToPrRefFor("rollback_outcome"), + planRef: taskToPrRefFor("rollback_plan"), + targetRef: exports_external2.union([taskToPrRefFor("commit"), taskToPrRefFor("branch")]), + status: exports_external2.enum(["not_run", "succeeded", "failed", "cancelled"]), + finishedAt: TimestampSchema, + evidenceRefs: exports_external2.array(TaskToPrEvidenceRefSchema).min(1) + }).strict().optional() +}).strict().superRefine((value, ctx) => { + if (value.outcome && !sameTaskToPrRef(value.outcome.planRef, value.plan.ref)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Rollback outcomes must bind the exact rollback plan", + path: ["outcome", "planRef"] + }); + } + if (value.outcome && !sameTaskToPrRef(value.outcome.targetRef, value.plan.targetRef)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Rollback outcomes must bind the exact rollback target", + path: ["outcome", "targetRef"] + }); + } + if (value.outcome && Date.parse(value.outcome.finishedAt) < Date.parse(value.plan.createdAt)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Rollback outcomes cannot finish before their plan was created", + path: ["outcome", "finishedAt"] + }); + } +}); +var TaskToPrProvenanceEntrySchema = exports_external2.discriminatedUnion("category", [ + exports_external2.object({ + category: exports_external2.literal("projection_id"), + projectionId: TaskToPrProjectionIdSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("work_run"), + ref: taskToPrRefFor("work_run") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("attempt"), + ref: taskToPrRefFor("attempt") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("admission"), + ref: taskToPrRefFor("admission") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("worker_actor"), + ref: taskToPrRefFor("worker_actor") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("worker_assignment"), + ref: taskToPrRefFor("worker") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("attempt_nonce"), + nonce: TaskToPrAttemptNonceSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("runtime"), + ref: taskToPrRefFor("runtime") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("writer_generation"), + ref: taskToPrRefFor("writer_generation") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("writer_lease"), + ref: taskToPrRefFor("writer_lease") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("writer_fence"), + ref: taskToPrRefFor("writer_fence") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("provider_profile"), + ref: taskToPrRefFor("provider_profile") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("provider_route"), + ref: taskToPrRefFor("provider_route") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("replay_cursor"), + ref: taskToPrRefFor("replay_cursor") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("replay_prefix"), + sequence: exports_external2.number().int().safe().nonnegative(), + prefixDigest: LowerSha256DigestSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("repair_state"), + ref: taskToPrRefFor("repair_cycle") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("latest_repair"), + ref: taskToPrRefFor("repair_cycle") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("handoff"), + ref: taskToPrRefFor("handoff") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("recovery"), + ref: taskToPrRefFor("recovery") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("merge_guard"), + ref: taskToPrRefFor("merge_guard") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("cleanup_eligibility"), + ref: taskToPrRefFor("cleanup_eligibility") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("rollback_plan"), + ref: taskToPrRefFor("rollback_plan") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("terminal_disposition"), + ref: taskToPrRefFor("terminal_disposition") + }).strict(), + exports_external2.object({ + category: exports_external2.literal("equality_proof"), + ref: taskToPrRefFor("proof_bundle"), + base: TaskToPrGitObjectIdSchema, + head: TaskToPrGitObjectIdSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("ci_proof"), + ref: taskToPrRefFor("proof_bundle"), + base: TaskToPrGitObjectIdSchema, + head: TaskToPrGitObjectIdSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("review_proof"), + ref: taskToPrRefFor("proof_bundle"), + base: TaskToPrGitObjectIdSchema, + head: TaskToPrGitObjectIdSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("review_record"), + ref: taskToPrRefFor("review"), + base: TaskToPrGitObjectIdSchema, + head: TaskToPrGitObjectIdSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("review_run"), + ref: taskToPrRefFor("review_run"), + base: TaskToPrGitObjectIdSchema, + head: TaskToPrGitObjectIdSchema + }).strict(), + exports_external2.object({ + category: exports_external2.literal("provider_guard_receipt"), + ref: taskToPrRefFor("merge_guard_receipt"), + base: TaskToPrGitObjectIdSchema, + head: TaskToPrGitObjectIdSchema + }).strict() +]); +function taskToPrActiveProvenanceEntries(projection) { + return [ + { + category: "projection_id", + projectionId: projection.id + }, + { + category: "work_run", + ref: projection.workRunRef + }, + { + category: "attempt", + ref: projection.attempt.ref + }, + { + category: "admission", + ref: projection.attempt.admissionRef + }, + { + category: "worker_actor", + ref: projection.attempt.workerActorRef + }, + { + category: "worker_assignment", + ref: projection.attempt.workerRef + }, + { + category: "attempt_nonce", + nonce: projection.attempt.nonce + }, + { + category: "runtime", + ref: projection.attempt.runtimeRef + }, + { + category: "writer_generation", + ref: projection.attempt.writerGenerationRef + }, + { + category: "writer_lease", + ref: projection.attempt.writerLeaseRef + }, + { + category: "writer_fence", + ref: projection.attempt.writerFenceRef + }, + { + category: "provider_profile", + ref: projection.attempt.providerProfileRef + }, + { + category: "provider_route", + ref: projection.attempt.providerRouteRef + }, + { + category: "replay_cursor", + ref: projection.events.replayCursorRef + }, + { + category: "replay_prefix", + sequence: projection.events.sequence, + prefixDigest: projection.events.prefixDigest + }, + { + category: "repair_state", + ref: projection.repair.ref + }, + ...projection.repair.latestRepairRef ? [ + { + category: "latest_repair", + ref: projection.repair.latestRepairRef + } + ] : [], + ...projection.handoff ? [{ category: "handoff", ref: projection.handoff.ref }] : [], + ...projection.recovery ? [{ category: "recovery", ref: projection.recovery.ref }] : [], + ...projection.exactHead ? [ + { + category: "equality_proof", + ref: projection.exactHead.equalityProofRef, + base: projection.exactHead.expectedBase, + head: projection.exactHead.localHead + }, + ...projection.exactHead.ciProofBundleRefs.map((ref) => ({ + category: "ci_proof", + ref, + base: projection.exactHead.expectedBase, + head: projection.exactHead.localHead + })) + ] : [], + ...projection.reviews.flatMap((review) => [ + { + category: "review_proof", + ref: review.proofBundleRef, + base: review.base, + head: review.head + }, + { + category: "review_record", + ref: review.ref, + base: review.base, + head: review.head + }, + { + category: "review_run", + ref: review.reviewRunRef, + base: review.base, + head: review.head + } + ]), + ...projection.merge ? [ + { + category: "merge_guard", + ref: projection.merge.guard.ref + }, + { + category: "provider_guard_receipt", + ref: projection.merge.guard.providerGuardReceiptRef, + base: projection.merge.guard.expectedBase, + head: projection.merge.guard.expectedHead + } + ] : [], + ...projection.cleanup ? [ + { + category: "cleanup_eligibility", + ref: projection.cleanup.eligibility.ref + } + ] : [], + ...projection.rollback ? [ + { + category: "rollback_plan", + ref: projection.rollback.plan.ref + } + ] : [], + ...projection.terminalDispositionRef ? [ + { + category: "terminal_disposition", + ref: projection.terminalDispositionRef + } + ] : [] + ]; +} +function sameTaskToPrProvenanceEntry(left, right) { + if (left.category !== right.category) { + return false; + } + if (left.category === "projection_id" && right.category === "projection_id") { + return left.projectionId === right.projectionId; + } + if (left.category === "attempt_nonce" && right.category === "attempt_nonce") { + return left.nonce === right.nonce; + } + if (left.category === "replay_prefix" && right.category === "replay_prefix") { + return left.sequence === right.sequence && left.prefixDigest === right.prefixDigest; + } + if (!("ref" in left) || !("ref" in right)) { + return false; + } + return sameTaskToPrRef(left.ref, right.ref) && (("head" in left) && ("head" in right) && ("base" in left) && ("base" in right) && sameGitObjectId(left.base, right.base) && sameGitObjectId(left.head, right.head) || !("head" in left) && !("head" in right) && !("base" in left) && !("base" in right)); +} +var TASK_TO_PR_V1_ADAPTER_EXTENSION_SCHEMA_PREFIX = "hasna.task_to_pr_adapter_extension."; +var TaskToPrAdapterExtensionSchema = exports_external2.object({ + mode: exports_external2.enum(["local", "cloud"]), + schema: SchemaIdSchema, + ref: taskToPrRefFor("adapter_extension"), + digest: LowerSha256DigestSchema +}).strict().superRefine((value, ctx) => { + if (!value.schema.startsWith(TASK_TO_PR_V1_ADAPTER_EXTENSION_SCHEMA_PREFIX)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Adapter extension schema ids must use the permanently reserved task-to-PR adapter-extension namespace", + path: ["schema"] + }); + } +}); +var TaskToPrProjectionStateSchema = exports_external2.enum([ + "admitted", + "running", + "handed_off", + "reviewing", + "repairing", + "merge_ready", + "merged", + "closed_unmerged", + "failed", + "blocked", + "cancelled", + "recovering", + "cleanup_complete", + "rolled_back" +]); +var TaskToPrStatesWithoutReviewAuthority = new Set([ + "admitted", + "running", + "handed_off" +]); +var TaskToPrTerminalStates = new Set([ + "merged", + "closed_unmerged", + "failed", + "blocked", + "cancelled", + "cleanup_complete", + "rolled_back" +]); +var TASK_TO_PR_STATE_MERGE_MATRIX = { + admitted: new Set(["absent", "denied:none", "revoked:none"]), + running: new Set(["absent", "denied:none", "revoked:none"]), + handed_off: new Set(["absent", "denied:none", "revoked:none"]), + reviewing: new Set(["absent", "denied:none", "revoked:none"]), + repairing: new Set(["absent", "denied:none", "revoked:none"]), + merge_ready: new Set(["eligible:none"]), + merged: new Set(["consumed:merged"]), + closed_unmerged: new Set([ + "consumed:closed_unmerged", + "consumed:refused", + "consumed:head_drift", + "consumed:base_drift" + ]), + failed: new Set(["absent", "revoked:none"]), + blocked: new Set(["absent", "revoked:none"]), + cancelled: new Set(["absent", "revoked:none"]), + recovering: new Set(["absent", "denied:none", "revoked:none"]), + cleanup_complete: new Set([ + "absent", + "revoked:none", + "consumed:merged", + "consumed:closed_unmerged", + "consumed:refused", + "consumed:head_drift", + "consumed:base_drift" + ]), + rolled_back: new Set(["consumed:merged"]) +}; +var TaskToPrProjectionSchema = exports_external2.object({ + schema: exports_external2.literal(SCHEMA_IDS.taskToPrProjection), + id: TaskToPrProjectionIdSchema, + createdAt: TimestampSchema, + canonicalizationVersion: exports_external2.union([exports_external2.literal(1), exports_external2.literal(2)]), + identityDigest: LowerSha256DigestSchema, + frozenScopeDigest: LowerSha256DigestSchema, + state: TaskToPrProjectionStateSchema, + workRunRef: taskToPrRefFor("work_run"), + rootRequestRef: taskToPrRefFor("root_request"), + prGroupRef: taskToPrRefFor("pr_group"), + leafTaskRef: taskToPrRefFor("leaf_task"), + attempt: TaskToPrAttemptSchema, + repository: TaskToPrRepositoryBindingSchema, + events: TaskToPrEventCursorSchema, + openLoopsInvocationRef: taskToPrRefFor("openloops_invocation").optional(), + pullRequestRef: taskToPrRefFor("pull_request").optional(), + exactHead: TaskToPrExactHeadBindingSchema.optional(), + handoff: TaskToPrHandoffSchema.optional(), + reviews: exports_external2.array(TaskToPrReviewBindingSchema).default([]), + repair: TaskToPrRepairStateSchema, + merge: TaskToPrMergeStateSchema.optional(), + recovery: TaskToPrRecoverySchema.optional(), + cancellation: TaskToPrCancellationSchema.optional(), + cleanup: TaskToPrCleanupStateSchema.optional(), + rollback: TaskToPrRollbackSchema.optional(), + terminalDispositionRef: taskToPrRefFor("terminal_disposition").optional(), + provenanceLedger: exports_external2.array(TaskToPrProvenanceEntrySchema), + adapterExtensions: exports_external2.array(TaskToPrAdapterExtensionSchema).default([]), + evidenceRefs: exports_external2.array(TaskToPrEvidenceRefSchema).default([]) +}).strict().superRefine((value, ctx) => { + const derivedIdentityDigest = value.canonicalizationVersion === 1 ? deriveTaskToPrIdentityDigest({ + canonicalizationVersion: 1, + rootRequestRef: value.rootRequestRef, + prGroupRef: value.prGroupRef, + leafTaskRef: value.leafTaskRef, + repoRef: value.repository.repoRef, + baseHead: value.repository.baseHead, + frozenScopeDigest: value.frozenScopeDigest + }) : deriveTaskToPrIdentityDigest({ + canonicalizationVersion: 2, + rootRequestRef: value.rootRequestRef, + prGroupRef: value.prGroupRef, + leafTaskRef: value.leafTaskRef, + repoRef: value.repository.repoRef, + worktreeRef: value.repository.worktreeRef, + branchRef: value.repository.branchRef, + baseHead: value.repository.baseHead, + frozenScopeDigest: value.frozenScopeDigest + }); + if (value.identityDigest !== derivedIdentityDigest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "identityDigest must equal the selected v1 compatibility or v2 branch/worktree-bound canonical identity digest", + path: ["identityDigest"] + }); + } + const provenanceIds = new Set; + const provenanceDigests = new Set; + const provenanceProjectionIds = new Set; + const provenanceAttemptNonces = new Set; + const provenanceReplayPrefixes = new Set; + const provenanceReplaySequences = new Set; + for (const [index, entry] of value.provenanceLedger.entries()) { + if ("ref" in entry) { + if (provenanceIds.has(entry.ref.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Provenance entries cannot reuse a canonical owner id across categories or generations", + path: ["provenanceLedger", index, "ref", "id"] + }); + } + provenanceIds.add(entry.ref.id); + if (provenanceDigests.has(entry.ref.digest)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Provenance entries cannot reuse a canonical digest across categories or generations", + path: ["provenanceLedger", index, "ref", "digest"] + }); + } + provenanceDigests.add(entry.ref.digest); + continue; } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); + if (entry.category === "projection_id") { + if (provenanceProjectionIds.has(entry.projectionId)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Projection identity provenance tombstones must be globally unique", + path: ["provenanceLedger", index, "projectionId"] + }); + } + provenanceProjectionIds.add(entry.projectionId); + continue; } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); + if (entry.category === "attempt_nonce") { + if (provenanceAttemptNonces.has(entry.nonce)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Attempt nonce provenance tombstones must be globally unique", + path: ["provenanceLedger", index, "nonce"] + }); + } + provenanceAttemptNonces.add(entry.nonce); + continue; } - if (renderManifestIds.has(renderManifest.id)) { + if (provenanceReplayPrefixes.has(entry.prefixDigest)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] + code: exports_external2.ZodIssueCode.custom, + message: "Replay prefix provenance tombstones must be globally unique", + path: ["provenanceLedger", index, "prefixDigest"] }); } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema4 = exports_external5.enum(["local", "package", "provider", "url"]); -var RenderImportSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - kind: RenderImportKindSchema4, - specifier: exports_external5.string().min(1), - path: RelativeProjectPathSchema4.optional(), - packageName: exports_external5.string().min(1).optional(), - uri: UriSchema4.optional(), - provider: ProjectIntegrationKindSchema4.optional(), - schemaId: SchemaIdSchema4.optional(), - integrity: HashStringSchema4.optional(), - resourceRef: ResourcePointerSchema4.optional(), - optional: exports_external5.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema4 = exports_external5.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - title: exports_external5.string().min(1), - kind: RenderViewKindSchema4, - default: exports_external5.boolean().default(false), - entry: RelativeProjectPathSchema4.optional(), - imports: exports_external5.array(RenderImportSchema4).default([]), - panelRefs: exports_external5.array(ResourcePointerSchema4).default([]), - dataRefs: exports_external5.array(ResourcePointerSchema4).default([]), - layout: MetadataSchema4.optional() -}).strict(); -var RenderManifestSchema4 = contractBaseSchema4(SCHEMA_IDS4.renderManifest).extend({ - projectId: ProjectSlugSchema4, - name: exports_external5.string().min(1), - version: exports_external5.string().min(1), - manifestPath: RelativeProjectPathSchema4.default(".hasna/project/dashboard.render.json"), - renderer: exports_external5.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external5.array(RenderViewSchema4).min(1), - imports: exports_external5.array(RenderImportSchema4).default([]), - theme: MetadataSchema4.optional(), - compatibility: exports_external5.object({ - minProjectsVersion: exports_external5.string().min(1).optional(), - minContractsVersion: exports_external5.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { + provenanceReplayPrefixes.add(entry.prefixDigest); + if (provenanceReplaySequences.has(entry.sequence)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] + code: exports_external2.ZodIssueCode.custom, + message: "Replay prefix provenance entries must bind globally unique replay sequences", + path: ["provenanceLedger", index, "sequence"] }); } - importIds.add(importRef.id); + provenanceReplaySequences.add(entry.sequence); } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { + for (const activeEntry of taskToPrActiveProvenanceEntries(value)) { + if (!value.provenanceLedger.some((entry) => sameTaskToPrProvenanceEntry(entry, activeEntry))) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] + code: exports_external2.ZodIssueCode.custom, + message: `The active ${activeEntry.category} identity must be represented exactly in the monotonic provenance ledger`, + path: ["provenanceLedger"] }); } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { + } + const requiredCanonicalPreservationRefs = [ + value.rootRequestRef, + value.prGroupRef, + value.leafTaskRef, + value.repository.repoRef, + value.repository.worktreeRef, + value.repository.branchRef, + value.events.streamRef, + ...value.pullRequestRef ? [value.pullRequestRef] : [] + ]; + const requirePreservedRefs = (preservedStateRefs, requiredRefs, path, label) => { + const requiredRoles = new Set(requiredRefs.map((requiredRef) => requiredRef.role)); + const seenRoles = new Set; + for (const [index, preservedRef] of preservedStateRefs.entries()) { + if (!requiredRoles.has(preservedRef.role)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] + code: exports_external2.ZodIssueCode.custom, + message: `${label} cannot preserve an unrecognized ${preservedRef.role} role`, + path: [...path, index] }); } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { + if (seenRoles.has(preservedRef.role)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] + code: exports_external2.ZodIssueCode.custom, + message: `${label} must preserve exactly one canonical ref per role`, + path: [...path, index] }); } + seenRoles.add(preservedRef.role); } - } -}); -var ProjectPanelStateSchema4 = exports_external5.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema4 = exports_external5.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - label: exports_external5.string().min(1), - value: exports_external5.union([exports_external5.string(), exports_external5.number(), exports_external5.boolean()]), - unit: exports_external5.string().min(1).optional(), - status: exports_external5.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]) -}).strict(); -var ProjectPanelItemSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - title: exports_external5.string().min(1), - summary: exports_external5.string().min(1).optional(), - status: exports_external5.string().min(1).optional(), - priority: exports_external5.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema4.optional(), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - metadata: MetadataSchema4.optional() -}).strict(); -var ProjectRenderFragmentSchema4 = exports_external5.object({ - renderer: exports_external5.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external5.string().min(1).optional(), - entry: RelativeProjectPathSchema4.optional(), - imports: exports_external5.array(RenderImportSchema4).default([]), - spec: MetadataSchema4.default({}) -}).strict(); -var ProjectPanelSchema4 = contractBaseSchema4(SCHEMA_IDS4.projectPanel).extend({ - projectId: ProjectSlugSchema4, - provider: exports_external5.object({ - kind: ProjectIntegrationKindSchema4, - id: exports_external5.string().min(1), - name: exports_external5.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema4.optional(), - externalId: NonEmptyStringSchema4.optional() - }).strict(), - kind: ProjectPanelKindSchema4, - title: exports_external5.string().min(1), - summary: exports_external5.string().min(1).optional(), - state: ProjectPanelStateSchema4.default("ready"), - stateReason: exports_external5.string().min(1).optional(), - generatedAt: TimestampSchema4, - freshness: exports_external5.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external5.array(ProjectPanelMetricSchema4).default([]), - items: exports_external5.array(ProjectPanelItemSchema4).default([]), - actions: exports_external5.array(ResourcePointerSchema4).default([]), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - renderFragment: ProjectRenderFragmentSchema4.optional(), - warnings: exports_external5.array(exports_external5.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { + if (preservedStateRefs.length !== requiredRefs.length) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] + code: exports_external2.ZodIssueCode.custom, + message: `${label} preservation refs must exactly equal the required canonical role set`, + path }); } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); + for (const requiredRef of requiredRefs) { + if (!preservedStateRefs.some((preservedRef) => sameTaskToPrRef(preservedRef, requiredRef))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `${label} must preserve ${requiredRef.role}`, + path + }); + } } - } -}); -var ProjectSnapshotSchema4 = contractBaseSchema4(SCHEMA_IDS4.projectSnapshot).extend({ - projectId: ProjectSlugSchema4, - generatedAt: TimestampSchema4, - status: ContractStatusSchema4.default("unknown"), - manifestRef: ResourcePointerSchema4, - renderManifestRef: ResourcePointerSchema4.optional(), - panels: exports_external5.array(ProjectPanelSchema4).default([]), - contextPacks: exports_external5.array(ContextPackSchema4).default([]), - proofBundleRefs: exports_external5.array(ResourcePointerSchema4).default([]), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - warnings: exports_external5.array(exports_external5.string().min(1)).default([]), - freshness: exports_external5.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { + }; + if (value.handoff && !sameTaskToPrRef(value.handoff.nextWriterGenerationRef, value.attempt.writerGenerationRef)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] + code: exports_external2.ZodIssueCode.custom, + message: "Handoff next generation must be the current attempt writer generation", + path: ["handoff", "nextWriterGenerationRef"] }); } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { + if (value.handoff && !sameTaskToPrRef(value.handoff.nextAttemptRef, value.attempt.ref)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] + code: exports_external2.ZodIssueCode.custom, + message: "Handoff next attempt must be the current attempt", + path: ["handoff", "nextAttemptRef"] }); } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } + if (value.handoff) { + requireFreshTaskToPrRef(value.handoff.stoppedWorkRunRef, value.workRunRef, ctx, ["handoff", "stoppedWorkRunRef"], "Handoff WorkRun rotation"); } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { + if (value.recovery) { + if (value.recovery.successorAttemptNonce !== value.attempt.nonce) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] + code: exports_external2.ZodIssueCode.custom, + message: "Recovery successor nonce must equal the current attempt nonce", + path: ["recovery", "successorAttemptNonce"] }); } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { + if (!sameTaskToPrRef(value.recovery.successorWriterGenerationRef, value.attempt.writerGenerationRef)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] + code: exports_external2.ZodIssueCode.custom, + message: "Recovery successor generation must equal the current writer generation", + path: ["recovery", "successorWriterGenerationRef"] }); } - contextPackIds.add(contextPack.id); + requireFreshTaskToPrRef(value.recovery.priorAttemptRef, value.attempt.ref, ctx, ["recovery", "priorAttemptRef"], "Recovery attempt rotation"); + requireFreshTaskToPrRef(value.recovery.priorWorkRunRef, value.workRunRef, ctx, ["recovery", "priorWorkRunRef"], "Recovery WorkRun rotation"); + requirePreservedRefs(value.recovery.preservedStateRefs, [value.recovery.priorWorkRunRef, ...requiredCanonicalPreservationRefs], ["recovery", "preservedStateRefs"], "Recovery"); } -}); -var ValidationCheckSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - kind: exports_external5.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external5.boolean().default(true), - command: exports_external5.string().min(1).optional(), - expected: exports_external5.string().min(1).optional(), - timeoutMs: exports_external5.number().int().positive().optional(), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { + if (value.cancellation && !sameTaskToPrRef(value.cancellation.cancelledAttemptRef, value.attempt.ref)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] + code: exports_external2.ZodIssueCode.custom, + message: "Cancellation must bind the current attempt", + path: ["cancellation", "cancelledAttemptRef"] }); } -}); -var ValidationPlanSchema4 = contractBaseSchema4(SCHEMA_IDS4.validationPlan).extend({ - objective: exports_external5.string().min(1), - subject: ResourcePointerSchema4.optional(), - checks: exports_external5.array(ValidationCheckSchema4).min(1), - verifier: ActorPointerSchema4.optional(), - requiredEvidenceKinds: exports_external5.array(EvidenceKindSchema4).default([]) -}).strict(); -var ScaffoldTypeSchema4 = exports_external5.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema4 = exports_external5.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema4 = exports_external5.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema4 = exports_external5.object({ - key: exports_external5.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external5.string().min(1), - required: exports_external5.boolean().default(false), - ["secret"]: exports_external5.boolean().default(false), - group: exports_external5.string().min(1).optional(), - default: exports_external5.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); + if (value.cancellation) { + requirePreservedRefs(value.cancellation.preservedStateRefs, [value.workRunRef, value.attempt.ref, ...requiredCanonicalPreservationRefs], ["cancellation", "preservedStateRefs"], "Cancellation"); } -}); -var ScaffoldScriptSchema4 = exports_external5.object({ - name: exports_external5.string().min(1), - command: exports_external5.string().min(1), - description: exports_external5.string().min(1).optional(), - required: exports_external5.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema4 = exports_external5.object({ - packageManager: exports_external5.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external5.array(exports_external5.string().min(1)).default([]), - requiredFiles: exports_external5.array(exports_external5.string().min(1)).default([]), - requiredDirectories: exports_external5.array(exports_external5.string().min(1)).default([]), - optionalDirectories: exports_external5.array(exports_external5.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema4 = contractBaseSchema4(SCHEMA_IDS4.scaffoldManifest).extend({ - name: exports_external5.string().min(1), - version: exports_external5.string().min(1), - summary: exports_external5.string().min(1), - type: ScaffoldTypeSchema4, - status: ScaffoldStatusSchema4.default("draft"), - capabilities: exports_external5.array(ScaffoldCapabilitySchema4).default([]), - techStack: exports_external5.array(exports_external5.string().min(1)).default([]), - tags: TagsSchema4, - source: ResourcePointerSchema4.optional(), - output: ScaffoldOutputShapeSchema4, - env: exports_external5.array(ScaffoldEnvVarSchema4).default([]), - scripts: exports_external5.array(ScaffoldScriptSchema4).default([]), - validationChecks: exports_external5.array(ValidationCheckSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { + if (value.cancellation && value.recovery) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] + code: exports_external2.ZodIssueCode.custom, + message: "A projection cannot be both the cancellation and recovery snapshot", + path: ["recovery"] }); } - if (value.status === "active" && value.validationChecks.length === 0) { + if (value.handoff && value.recovery) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] + code: exports_external2.ZodIssueCode.custom, + message: "A projection cannot be both the handoff and recovery snapshot", + path: ["recovery"] }); } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { + if (value.cleanup && !sameTaskToPrRef(value.cleanup.eligibility.eventCursorRef, value.events.replayCursorRef)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup eligibility must bind the current canonical replay cursor", + path: ["cleanup", "eligibility", "eventCursorRef"] }); } -}); -var ScaffoldInstallStatusSchema4 = exports_external5.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema4 = contractBaseSchema4(SCHEMA_IDS4.scaffoldInstallRecord).extend({ - scaffoldId: exports_external5.string().min(1), - scaffoldVersion: exports_external5.string().min(1).optional(), - manifestRef: ResourcePointerSchema4.optional(), - target: ResourcePointerSchema4, - status: ScaffoldInstallStatusSchema4, - installedAt: TimestampSchema4.optional(), - installer: ActorPointerSchema4.optional(), - packageManager: exports_external5.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema4.optional(), - generatedFiles: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - proofBundleRefs: exports_external5.array(ResourcePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { + if (value.cleanup && (!value.terminalDispositionRef || !sameTaskToPrRef(value.cleanup.eligibility.terminalDispositionRef, value.terminalDispositionRef))) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup eligibility must bind the exact durable terminal owner fact", + path: ["cleanup", "eligibility", "terminalDispositionRef"] }); } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { + if (value.cleanup && !sameTaskToPrRef(value.cleanup.eligibility.writerLeaseRef, value.attempt.writerLeaseRef)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup eligibility must bind the exact writer lease being revoked", + path: ["cleanup", "eligibility", "writerLeaseRef"] }); } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { + if (value.cleanup && !sameTaskToPrRef(value.cleanup.eligibility.targetWorktreeRef, value.repository.worktreeRef)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup eligibility must bind the canonical worktree", + path: ["cleanup", "eligibility", "targetWorktreeRef"] }); } -}); -var AppIdSchema4 = exports_external5.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema4 = exports_external5.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema4 = exports_external5.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema4 = exports_external5.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema4 = NonEmptyStringSchema4.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema4 = exports_external5.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema4 = exports_external5.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema4 = exports_external5.object({ - transport: exports_external5.enum(["http", "stdio"]).default("http"), - bin: exports_external5.string().min(1).optional(), - url: UriSchema4.optional() -}).strict(); -var AppHttpSurfaceSchema4 = exports_external5.object({ - healthPath: exports_external5.string().min(1).default("/health"), - port: exports_external5.number().int().positive().optional(), - baseUrl: UriSchema4.optional() -}).strict(); -var AppSurfacesSchema4 = exports_external5.object({ - bins: exports_external5.array(exports_external5.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema4.optional(), - http: AppHttpSurfaceSchema4.optional() -}).strict(); -var AppSchema4 = contractBaseSchema4(SCHEMA_IDS4.app).extend({ - appId: AppIdSchema4, - npmName: NpmPackageNameSchema4, - repoFolder: AppIdSchema4, - githubUrl: GithubUrlSchema4, - projectSlug: ProjectSlugSchema4, - surfaces: AppSurfacesSchema4.default({}), - lifecycle: AppLifecycleSchema4, - releaseChannel: ReleaseChannelSchema4.default("stable"), - summary: exports_external5.string().min(1).optional(), - tags: TagsSchema4 -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { + if (value.pullRequestRef) { + if (value.exactHead && !sameTaskToPrRef(value.exactHead.pullRequestRef, value.pullRequestRef)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] + code: exports_external2.ZodIssueCode.custom, + message: "Exact-head proof must bind the canonical pull request ref", + path: ["exactHead", "pullRequestRef"] }); } - seenBins.add(bin); - } -}); -var PublishPathSchema4 = exports_external5.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema4 = contractBaseSchema4(SCHEMA_IDS4.release).extend({ - appId: AppIdSchema4, - package: NpmPackageNameSchema4, - version: SemverSchema4, - gitSha: GitShaSchema4, - publishedAt: TimestampSchema4, - publishPath: PublishPathSchema4, - changelogRef: ResourcePointerSchema4.optional(), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema4 = exports_external5.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema4 = exports_external5.object({ - cliVersion: exports_external5.string().min(1).optional(), - mcpHealth: exports_external5.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema4 = contractBaseSchema4(SCHEMA_IDS4.rolloutRecord).extend({ - appId: AppIdSchema4, - package: NpmPackageNameSchema4, - version: SemverSchema4, - machine: NonEmptyStringSchema4, - action: RolloutActionSchema4, - result: ContractStatusSchema4, - verifiedBy: RolloutVerificationSchema4.optional(), - at: TimestampSchema4, - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema4 = exports_external5.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema4 = exports_external5.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema4 = exports_external5.object({ - channel: AnnouncementChannelKindSchema4, - status: AnnouncementDeliveryStatusSchema4, - deliveredAt: TimestampSchema4.optional(), - detail: exports_external5.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { + for (const [reviewIndex, review] of value.reviews.entries()) { + if (!sameTaskToPrRef(review.pullRequestRef, value.pullRequestRef)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Every review must bind the canonical pull request ref", + path: ["reviews", reviewIndex, "pullRequestRef"] + }); + } + } + if (value.merge && !sameTaskToPrRef(value.merge.guard.pullRequestRef, value.pullRequestRef)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge guard must bind the canonical pull request ref", + path: ["merge", "guard", "pullRequestRef"] + }); + } + if (value.merge?.outcome && !sameTaskToPrRef(value.merge.outcome.pullRequestRef, value.pullRequestRef)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge outcome must bind the canonical pull request ref", + path: ["merge", "outcome", "pullRequestRef"] + }); + } + } else if (value.exactHead || value.reviews.length > 0 || value.merge) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] + code: exports_external2.ZodIssueCode.custom, + message: "Review and merge state require a canonical pull request ref", + path: ["pullRequestRef"] }); } -}); -var AnnouncementSchema4 = contractBaseSchema4(SCHEMA_IDS4.announcement).extend({ - campaignId: NonEmptyStringSchema4, - appId: AppIdSchema4.optional(), - releaseRef: ResourcePointerSchema4.optional(), - channels: exports_external5.array(AnnouncementChannelSchema4).min(1), - audienceRef: ResourcePointerSchema4, - sentAt: TimestampSchema4 -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { + if (value.exactHead && !sameGitObjectId(value.exactHead.localHead, value.repository.branchHead)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] + code: exports_external2.ZodIssueCode.custom, + message: "Exact local head must equal the canonical branch head", + path: ["exactHead", "localHead"] }); } - if (value.audienceRef.kind !== "audience") { + if (value.exactHead && !sameGitObjectId(value.exactHead.expectedBase, value.repository.baseHead)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] + code: exports_external2.ZodIssueCode.custom, + message: "Exact-head expected base must equal the canonical repository base", + path: ["exactHead", "expectedBase"] }); } -}); -var AudiencePredicateKindSchema4 = exports_external5.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema4 = exports_external5.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema4 = exports_external5.union([exports_external5.string(), exports_external5.number(), exports_external5.boolean()]); -var AudiencePredicateSchema4 = exports_external5.object({ - kind: AudiencePredicateKindSchema4, - key: exports_external5.string().min(1).optional(), - op: AudiencePredicateOpSchema4.default("eq"), - value: AudiencePredicateValueSchema4.optional(), - values: exports_external5.array(AudiencePredicateValueSchema4).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { + if (value.exactHead && !sameTaskToPrRef(value.exactHead.remoteBranchRef, value.repository.branchRef)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] + code: exports_external2.ZodIssueCode.custom, + message: "Exact-head remote branch ref must equal the canonical repository branch ref", + path: ["exactHead", "remoteBranchRef"] }); } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { + if (value.exactHead && Date.parse(value.exactHead.verifiedAt) < Date.parse(value.createdAt)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] + code: exports_external2.ZodIssueCode.custom, + message: "Exact-head verification cannot precede the projection timestamp", + path: ["exactHead", "verifiedAt"] }); } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { + if (value.reviews.length > 0 && !value.exactHead) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] + code: exports_external2.ZodIssueCode.custom, + message: "Reviews require local/remote/provider exact-head proof", + path: ["exactHead"] }); } -}); -var AudienceDefinitionSchema4 = exports_external5.object({ - match: exports_external5.enum(["all", "any"]).default("all"), - predicates: exports_external5.array(AudiencePredicateSchema4).min(1) -}).strict(); -var ConsentPolicySchema4 = exports_external5.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema4 = contractBaseSchema4(SCHEMA_IDS4.audience).extend({ - audienceId: AppIdSchema4, - name: NonEmptyStringSchema4, - definition: AudienceDefinitionSchema4, - consentPolicy: ConsentPolicySchema4, - suppressionSyncedAt: OptionalTimestampSchema4 -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES4 = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema4 = exports_external5.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - provider: AppCloudProviderSchema4, - kind: exports_external5.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external5.string().min(1), - region: exports_external5.string().min(1).optional(), - accountId: exports_external5.string().min(1).optional(), - uri: UriSchema4.optional(), - machineScoped: exports_external5.boolean().default(false) -}).strict(); -var AppCloudManifestSchema4 = contractBaseSchema4(SCHEMA_IDS4.appCloudManifest).extend({ - packageName: exports_external5.string().min(1), - packageVersion: exports_external5.string().min(1).optional(), - appId: exports_external5.string().min(1), - repository: ResourcePointerSchema4.optional(), - storageMode: exports_external5.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external5.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external5.array(AppCloudResourceSchema4).default([]), - localCache: exports_external5.object({ - path: exports_external5.string().min(1).optional(), - pullMode: exports_external5.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external5.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external5.array(exports_external5.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES4]), - dependencies: exports_external5.array(exports_external5.string().min(1)).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES4, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); + if (value.exactHead) { + const proofObligations = [ + { ref: value.exactHead.equalityProofRef, path: ["exactHead", "equalityProofRef"] }, + ...value.exactHead.ciProofBundleRefs.map((ref, index) => ({ + ref, + path: ["exactHead", "ciProofBundleRefs", index] + })), + ...value.reviews.map((review, index) => ({ + ref: review.proofBundleRef, + path: ["reviews", index, "proofBundleRef"] + })) + ]; + const proofObligationKeys = new Set; + const proofObligationDigests = new Set; + for (const obligation of proofObligations) { + const key = taskToPrCanonicalRefKey(obligation.ref); + if (proofObligationKeys.has(key)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Exact-head equality, CI, and review proof obligations require globally unique canonical identities", + path: obligation.path + }); + } + proofObligationKeys.add(key); + if (proofObligationDigests.has(obligation.ref.digest)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Exact-head equality, CI, and review proof obligations require globally unique canonical digests", + path: obligation.path + }); + } + proofObligationDigests.add(obligation.ref.digest); + } } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES4) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { + const reviewKeys = new Set; + const reviewDigests = new Set; + const reviewerKeys = new Set; + const reviewerDigests = new Set; + const reviewRunKeys = new Set; + const reviewRunDigests = new Set; + const reviewProofKeys = new Set; + const reviewProofDigests = new Set; + for (const [reviewIndex, review] of value.reviews.entries()) { + if (!sameGitObjectId(review.base, value.repository.baseHead)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] + code: exports_external2.ZodIssueCode.custom, + message: "Review base must equal the exact canonical pull-request base", + path: ["reviews", reviewIndex, "base"] }); } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { + if (!sameGitObjectId(review.head, value.repository.branchHead)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] + code: exports_external2.ZodIssueCode.custom, + message: "Review head must equal the exact canonical branch head", + path: ["reviews", reviewIndex, "head"] }); } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { + for (const [key, seen, path] of [ + [review.ref.id, reviewKeys, "ref"], + [review.reviewerRef.id, reviewerKeys, "reviewerRef"], + [review.reviewRunRef.id, reviewRunKeys, "reviewRunRef"] + ]) { + if (seen.has(key)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Review, reviewer, and review-run refs must each be unique", + path: ["reviews", reviewIndex, path] + }); + } + seen.add(key); + } + if (reviewDigests.has(review.ref.digest)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] + code: exports_external2.ZodIssueCode.custom, + message: "Review refs must resolve to distinct canonical record digests", + path: ["reviews", reviewIndex, "ref"] }); } - if (!value.localCache) { + reviewDigests.add(review.ref.digest); + if (reviewerDigests.has(review.reviewerRef.digest)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] + code: exports_external2.ZodIssueCode.custom, + message: "Reviewer refs must resolve to distinct canonical actor digests", + path: ["reviews", reviewIndex, "reviewerRef"] }); } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { + reviewerDigests.add(review.reviewerRef.digest); + if (reviewRunDigests.has(review.reviewRunRef.digest)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] + code: exports_external2.ZodIssueCode.custom, + message: "Review-run refs must resolve to distinct canonical run digests", + path: ["reviews", reviewIndex, "reviewRunRef"] }); } - if (value.cloudResources.length > 0) { + reviewRunDigests.add(review.reviewRunRef.digest); + const reviewProofKey = taskToPrCanonicalRefKey(review.proofBundleRef); + if (reviewProofKeys.has(reviewProofKey)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] + code: exports_external2.ZodIssueCode.custom, + message: "Review proof bundles must have unique canonical identities", + path: ["reviews", reviewIndex, "proofBundleRef"] + }); + } + reviewProofKeys.add(reviewProofKey); + if (reviewProofDigests.has(review.proofBundleRef.digest)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Review proof bundles must have unique canonical digests", + path: ["reviews", reviewIndex, "proofBundleRef"] + }); + } + reviewProofDigests.add(review.proofBundleRef.digest); + if (review.reviewerRef.digest === value.attempt.workerRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Worker and reviewer identities must resolve to distinct canonical digests", + path: ["reviews", reviewIndex, "reviewerRef"] + }); + } + if (review.reviewRunRef.digest === value.attempt.runtimeRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Worker runtime and review run must resolve to distinct canonical digests", + path: ["reviews", reviewIndex, "reviewRunRef"] + }); + } + if (value.exactHead && Date.parse(review.reviewedAt) < Date.parse(value.exactHead.verifiedAt)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Reviews cannot precede exact-head verification", + path: ["reviews", reviewIndex, "reviewedAt"] }); } } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); + if (value.merge) { + if (!value.exactHead) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge state requires local/remote/provider exact-head proof", + path: ["exactHead"] + }); + } + if (!sameGitObjectId(value.merge.guard.expectedBase, value.repository.baseHead)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge guard expected base must equal the exact canonical pull-request base", + path: ["merge", "guard", "expectedBase"] + }); + } + if (!sameGitObjectId(value.merge.guard.expectedHead, value.repository.branchHead)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge guard expected head must equal the exact canonical branch head", + path: ["merge", "guard", "expectedHead"] + }); + } + if (value.exactHead && Date.parse(value.merge.guard.evaluatedAt) < Date.parse(value.exactHead.verifiedAt)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge guards cannot precede exact-head verification", + path: ["merge", "guard", "evaluatedAt"] + }); + } + if (value.reviews.some((review) => Date.parse(value.merge.guard.evaluatedAt) < Date.parse(review.reviewedAt))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge guards cannot precede their bound reviews", + path: ["merge", "guard", "evaluatedAt"] + }); + } + if (value.merge.guard.operatorRef.digest === value.attempt.workerRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Worker and merge operator identities must resolve to distinct canonical digests", + path: ["merge", "guard", "operatorRef"] + }); + } + if (value.merge.guard.operatorRunRef.digest === value.attempt.runtimeRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Worker runtime and merge-operator run must resolve to distinct canonical digests", + path: ["merge", "guard", "operatorRunRef"] + }); + } + for (const [reviewIndex, review] of value.reviews.entries()) { + if (value.merge.guard.operatorRef.digest === review.reviewerRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Reviewer and merge operator identities must resolve to distinct canonical digests", + path: ["reviews", reviewIndex, "reviewerRef"] + }); + } + if (value.merge.guard.operatorRunRef.digest === review.reviewRunRef.digest) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Review and merge-operator runs must resolve to distinct canonical digests", + path: ["reviews", reviewIndex, "reviewRunRef"] + }); + } + } + if (value.merge.guard.decision === "eligible" || value.merge.guard.decision === "consumed") { + if (value.reviews.length === 0 || value.reviews.some((review) => review.verdict !== "approved")) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Eligible merge guards require at least one review and all reviews approved", + path: ["merge", "guard", "decision"] + }); + } + if (value.merge.guard.reviewRefs.length !== value.reviews.length || value.merge.guard.reviewRefs.some((reviewRef) => !value.reviews.some((review) => sameTaskToPrRef(reviewRef, review.ref)))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Eligible merge guard review refs must exactly equal the projected approved review refs as a canonical set", + path: ["merge", "guard", "reviewRefs"] + }); + } + for (const review of value.reviews) { + if (!value.merge.guard.proofBundleRefs.some((proofRef) => sameTaskToPrRef(proofRef, review.proofBundleRef))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Eligible merge guards must bind every exact review proof bundle", + path: ["merge", "guard", "proofBundleRefs"] + }); + } + } + if (value.exactHead && !value.merge.guard.proofBundleRefs.some((proofRef) => sameTaskToPrRef(proofRef, value.exactHead.equalityProofRef))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Eligible merge guards must bind the exact-head equality proof", + path: ["merge", "guard", "proofBundleRefs"] + }); + } + if (value.exactHead && value.exactHead.ciProofBundleRefs.some((ciProofRef) => !value.merge.guard.proofBundleRefs.some((proofRef) => sameTaskToPrRef(proofRef, ciProofRef)))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Eligible merge guards must bind every exact-head CI proof", + path: ["merge", "guard", "proofBundleRefs"] + }); + } + } } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { + if (value.merge?.outcome) { + if (!sameTaskToPrRef(value.merge.outcome.guardRef, value.merge.guard.ref)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] + code: exports_external2.ZodIssueCode.custom, + message: "Merge outcome must bind the exact immutable merge guard", + path: ["merge", "outcome", "guardRef"] }); } - }); -}); -var NoCloudCheckKindSchema4 = exports_external5.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema4 = exports_external5.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - kind: NoCloudCheckKindSchema4, - severity: NoCloudFindingSeveritySchema4, - path: exports_external5.string().min(1).optional(), - packageName: exports_external5.string().min(1).optional(), - pattern: exports_external5.string().min(1), - message: exports_external5.string().min(1), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict(); -var NoCloudCheckResultSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - kind: NoCloudCheckKindSchema4, - status: ContractStatusSchema4, - target: exports_external5.string().min(1), - command: exports_external5.string().min(1).optional(), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - findings: exports_external5.array(NoCloudFindingSchema4).default([]) -}).strict(); -var NoCloudEvidencePackSchema4 = contractBaseSchema4(SCHEMA_IDS4.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema4, - packageName: exports_external5.string().min(1).optional(), - packageVersion: exports_external5.string().min(1).optional(), - generatedBy: ActorPointerSchema4.optional(), - scanMode: exports_external5.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema4, - verdict: exports_external5.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema4.optional(), - checks: exports_external5.array(NoCloudCheckResultSchema4).min(1), - findings: exports_external5.array(NoCloudFindingSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check2) => check2.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); + if (!sameGitObjectId(value.merge.outcome.expectedHead, value.merge.guard.expectedHead)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge outcome expected head must equal the guarded expected head", + path: ["merge", "outcome", "expectedHead"] + }); } - if (value.checks.some((check2) => check2.status !== "succeeded")) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); + if (!sameGitObjectId(value.merge.outcome.expectedBase, value.merge.guard.expectedBase)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge outcome expected base must equal the guarded expected base", + path: ["merge", "outcome", "expectedBase"] + }); } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check2) => check2.status === "failed")) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check2, index) => { - const checkBlockingFindings = check2.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check2.status === "succeeded" && checkBlockingFindings.length > 0) { + if (value.merge.guard.decision !== "consumed") { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] + code: exports_external2.ZodIssueCode.custom, + message: "Every merge outcome requires an explicitly consumed merge guard", + path: ["merge", "guard", "decision"] }); } - }); -}); -var ProofCheckResultSchema4 = exports_external5.object({ - checkId: exports_external5.string().min(1), - status: ContractStatusSchema4, - summary: exports_external5.string().min(1).optional(), - startedAt: OptionalTimestampSchema4, - finishedAt: OptionalTimestampSchema4, - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) -}).strict(); -var ProofBundleSchema4 = contractBaseSchema4(SCHEMA_IDS4.proofBundle).extend({ - subject: ResourcePointerSchema4, - validationPlanRef: ResourcePointerSchema4.optional(), - status: ContractStatusSchema4, - verdict: exports_external5.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external5.array(ProofCheckResultSchema4).default([]), - verifier: ActorPointerSchema4.optional(), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - residualRisks: exports_external5.array(exports_external5.string().min(1)).default([]), - freshness: exports_external5.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { + if (Date.parse(value.merge.outcome.finishedAt) < Date.parse(value.merge.guard.evaluatedAt)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] + code: exports_external2.ZodIssueCode.custom, + message: "Merge outcomes cannot precede guard evaluation", + path: ["merge", "outcome", "finishedAt"] }); } - if (value.checks.length === 0) { + } + if (value.cleanup) { + const cleanupFloor = value.merge?.outcome?.finishedAt ?? value.createdAt; + if (Date.parse(value.cleanup.eligibility.evaluatedAt) < Date.parse(cleanupFloor)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup eligibility cannot precede the terminal merge outcome or projection", + path: ["cleanup", "eligibility", "evaluatedAt"] }); } - value.checks.forEach((check2, index) => { - if (check2.status !== "succeeded") { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check2) => check2.evidenceRefs.length > 0); - if (!hasEvidence) { + if (value.cleanup.outcome && Date.parse(value.cleanup.outcome.finishedAt) < Date.parse(value.cleanup.eligibility.evaluatedAt)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup outcomes cannot precede cleanup eligibility", + path: ["cleanup", "outcome", "finishedAt"] }); } - if (!value.verifier) { + } + if (value.rollback?.outcome && value.merge?.outcome && Date.parse(value.rollback.outcome.finishedAt) < Date.parse(value.merge.outcome.finishedAt)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Rollback outcomes cannot precede the merge outcome they remediate", + path: ["rollback", "outcome", "finishedAt"] + }); + } + if (value.rollback) { + const rollbackFloor = value.merge?.outcome?.finishedAt ?? value.createdAt; + if (Date.parse(value.rollback.plan.createdAt) < Date.parse(rollbackFloor)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] + code: exports_external2.ZodIssueCode.custom, + message: "Rollback plans cannot precede the terminal merge outcome or projection", + path: ["rollback", "plan", "createdAt"] }); } } - if (value.verdict === "not_run" && value.checks.length > 0) { + if (value.state === "handed_off" && !value.handoff) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Handed-off projections require a handoff ref", path: ["handoff"] }); + } + if (TaskToPrStatesWithoutReviewAuthority.has(value.state) && value.reviews.length > 0) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] + code: exports_external2.ZodIssueCode.custom, + message: `${value.state} projections cannot carry review bindings before review authority is active`, + path: ["reviews"] }); } - if (value.verdict === "failed" && !value.checks.some((check2) => check2.status === "failed") && value.evidenceRefs.length === 0) { + if ((TaskToPrStatesWithoutReviewAuthority.has(value.state) || value.state === "recovering") && (value.merge?.guard.reviewRefs.length ?? 0) > 0) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] + code: exports_external2.ZodIssueCode.custom, + message: `${value.state} projections cannot hide review bindings in a merge guard before review authority is active`, + path: ["merge", "guard", "reviewRefs"] }); } -}); -var WorkRunSchema4 = contractBaseSchema4(SCHEMA_IDS4.workRun).extend({ - objective: exports_external5.string().min(1), - status: ContractStatusSchema4, - actor: ActorPointerSchema4, - traceId: exports_external5.string().min(1).optional(), - startedAt: OptionalTimestampSchema4, - finishedAt: OptionalTimestampSchema4, - constraints: exports_external5.array(exports_external5.string().min(1)).default([]), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - decisions: exports_external5.array(DecisionEnvelopeSchema4).default([]), - costEstimates: exports_external5.array(CostEstimateSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - validationPlanRefs: exports_external5.array(ResourcePointerSchema4).default([]), - proofBundleRefs: exports_external5.array(ResourcePointerSchema4).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { + const mergeMatrixKey = value.merge ? `${value.merge.guard.decision}:${value.merge.outcome?.status ?? "none"}` : "absent"; + if (!TASK_TO_PR_STATE_MERGE_MATRIX[value.state].has(mergeMatrixKey)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] + code: exports_external2.ZodIssueCode.custom, + message: `State ${value.state} is incompatible with merge authority ${mergeMatrixKey}`, + path: ["merge"] }); } - if (TerminalStatuses4.has(value.status) && !value.finishedAt) { + if (TaskToPrTerminalStates.has(value.state) && !value.terminalDispositionRef) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] + code: exports_external2.ZodIssueCode.custom, + message: `${value.state} projections require a durable Todos terminal-disposition owner ref`, + path: ["terminalDispositionRef"] }); } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { + if (!TaskToPrTerminalStates.has(value.state) && value.terminalDispositionRef) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] + code: exports_external2.ZodIssueCode.custom, + message: `${value.state} projections cannot carry a terminal-disposition owner ref`, + path: ["terminalDispositionRef"] }); } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { + if (value.state === "reviewing" && value.reviews.length === 0) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Reviewing projections require review refs", path: ["reviews"] }); + } + if (value.state === "cancelled" && !value.cancellation) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Cancelled projections require preservation state", path: ["cancellation"] }); + } + if (value.cancellation && value.merge?.outcome) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", + code: exports_external2.ZodIssueCode.custom, + message: "Cancellation cannot coexist with a terminal merge outcome", + path: ["cancellation"] + }); + } + if (value.state === "recovering" && !value.recovery) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Recovering projections require recovery state", path: ["recovery"] }); + } + if (value.state === "repairing" && value.repair.cycle === 0) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Repairing projections require a non-zero repair cycle", path: ["repair", "cycle"] }); + } + if (value.merge && (value.merge.guard.decision === "eligible" || value.merge.guard.decision === "consumed") && !sameTaskToPrRef(value.attempt.admissionWriterGenerationRef, value.attempt.writerGenerationRef)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Merge eligibility requires admission from the current writer generation", + path: ["attempt", "admissionWriterGenerationRef"] + }); + } + if (value.state === "merge_ready" && value.merge?.guard.decision !== "eligible") { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Merge-ready projections require an eligible guard", path: ["merge"] }); + } + if (value.state === "merged" && value.merge?.outcome?.status !== "merged") { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Merged projections require a merged immutable outcome", path: ["merge"] }); + } + if (value.state === "closed_unmerged" && !value.merge?.outcome?.status.match(/^(closed_unmerged|refused|head_drift|base_drift)$/)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Closed-unmerged projections require a non-merged terminal outcome", + path: ["merge"] + }); + } + if (value.state === "cleanup_complete" && (!value.cleanup?.outcome || !["deleted", "preserved", "skipped"].includes(value.cleanup.outcome.status))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Cleanup-complete projections require an immutable cleanup outcome", + path: ["cleanup"] + }); + } + if (value.state === "rolled_back" && value.rollback?.outcome?.status !== "succeeded") { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Rolled-back projections require a successful rollback outcome", + path: ["rollback"] + }); + } + if ((value.state === "failed" || value.state === "blocked") && value.evidenceRefs.length === 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Failed and blocked projections require redacted evidence refs", path: ["evidenceRefs"] }); } + if (["admitted", "running", "handed_off", "reviewing", "repairing", "merge_ready", "recovering"].includes(value.state) && (value.merge?.outcome || value.cancellation || value.cleanup?.outcome || value.rollback?.outcome)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Non-terminal projections cannot carry terminal owner outcomes", + path: ["state"] + }); + } + const extensionKeys = new Set; + for (const [index, extension] of value.adapterExtensions.entries()) { + const key = `${extension.mode}:${extension.schema}`; + if (extensionKeys.has(key)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "Adapter extensions must be unique per local/cloud mode and schema", + path: ["adapterExtensions", index] + }); + } + extensionKeys.add(key); + } }); -var TrajectoryEventSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - at: TimestampSchema4, - kind: exports_external5.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external5.string().min(1), - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]), - costEstimate: CostEstimateSchema4.optional() +var TrajectoryEventSchema = exports_external2.object({ + id: exports_external2.string().min(1), + at: TimestampSchema, + kind: exports_external2.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), + summary: exports_external2.string().min(1), + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]), + costEstimate: CostEstimateSchema.optional() }).strict(); -var AgentTrajectorySchema4 = contractBaseSchema4(SCHEMA_IDS4.agentTrajectory).extend({ - actor: ActorPointerSchema4, - workRunRef: ResourcePointerSchema4.optional(), - events: exports_external5.array(TrajectoryEventSchema4).default([]), - outcome: exports_external5.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema4.optional() +var AgentTrajectorySchema = contractBaseSchema(SCHEMA_IDS.agentTrajectory).extend({ + actor: ActorPointerSchema, + workRunRef: ResourcePointerSchema.optional(), + events: exports_external2.array(TrajectoryEventSchema).default([]), + outcome: exports_external2.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), + proofBundleRef: ResourcePointerSchema.optional() }).strict(); -var SERVICE_CONTRACT_VERSION4 = "v1"; -var RepoClassSchema4 = exports_external5.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES4 = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema4 = exports_external5.enum(DEPLOYMENT_MODES4); -var ServiceSurfaceStatusSchema4 = exports_external5.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema4 = exports_external5.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema4 = exports_external5.object({ - method: exports_external5.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external5.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external5.boolean().default(false), - description: exports_external5.string().min(1).optional() +var SERVICE_CONTRACT_VERSION = "v1"; +var RepoClassSchema = exports_external2.enum(["library", "cli-with-store", "service", "saas"]); +var HOSTING_MODES = ["user-hosted", "hasna-saas"]; +var HostingModeSchema = exports_external2.enum(HOSTING_MODES); +var SERVICE_SURFACE_KINDS = ["api", "sdk", "mcp", "cli"]; +var ServiceSurfaceKindSchema = exports_external2.enum(SERVICE_SURFACE_KINDS); +var ServiceSurfaceStatusSchema = exports_external2.enum(["supported", "deferred", "unsupported"]); +var ServiceAuthModeSchema = exports_external2.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); +var ServiceEndpointSchema = exports_external2.object({ + method: exports_external2.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), + path: exports_external2.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), + public: exports_external2.boolean().default(false), + description: exports_external2.string().min(1).optional() }).strict(); -var DeploymentReadinessGateSchema4 = exports_external5.object({ - id: exports_external5.string().min(1), - kind: exports_external5.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external5.boolean().default(true), - command: exports_external5.string().min(1).optional(), - evidenceRef: EvidencePointerSchema4.optional(), - status: exports_external5.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external5.string().min(1).optional() +var DeploymentReadinessGateSchema = exports_external2.object({ + id: exports_external2.string().min(1), + kind: exports_external2.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), + required: exports_external2.boolean().default(true), + command: exports_external2.string().min(1).optional(), + evidenceRef: EvidencePointerSchema.optional(), + status: exports_external2.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), + summary: exports_external2.string().min(1).optional() }).strict().superRefine((value, ctx) => { if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "Terminal readiness gates require command, evidenceRef, or summary", path: ["status"] }); } }); -var ServiceSurfaceSchema4 = exports_external5.object({ - name: exports_external5.string().min(1), - status: ServiceSurfaceStatusSchema4, - bin: exports_external5.string().min(1).optional(), - mcpBin: exports_external5.string().min(1).optional(), - authMode: ServiceAuthModeSchema4, - deploymentModes: exports_external5.array(DeploymentModeSchema4).min(1), - health: ServiceEndpointSchema4.optional(), - readiness: ServiceEndpointSchema4.optional(), - version: ServiceEndpointSchema4.optional(), - apiBasePath: exports_external5.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external5.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external5.string().min(1).optional(), - readinessGates: exports_external5.array(DeploymentReadinessGateSchema4).default([]) +var ServiceSurfaceSchema = exports_external2.object({ + name: exports_external2.string().min(1), + kind: ServiceSurfaceKindSchema.optional(), + status: ServiceSurfaceStatusSchema, + bin: exports_external2.string().min(1).optional(), + mcpBin: exports_external2.string().min(1).optional(), + authMode: ServiceAuthModeSchema, + health: ServiceEndpointSchema.optional(), + readiness: ServiceEndpointSchema.optional(), + version: ServiceEndpointSchema.optional(), + apiBasePath: exports_external2.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), + openApiPath: exports_external2.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), + exportSubpath: exports_external2.string().regex(/^\.(?:\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*)?$/, "SDK export subpaths must be package export keys such as . or ./sdk").optional(), + generatedFrom: exports_external2.string().regex(/^\/[A-Za-z0-9_./:-]*$/, "SDK generatedFrom must reference an absolute OpenAPI path").optional(), + clientClassName: exports_external2.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).optional(), + deferReason: exports_external2.string().min(1).optional(), + readinessGates: exports_external2.array(DeploymentReadinessGateSchema).default([]) }).strict().superRefine((value, ctx) => { if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); + if (!value.kind || value.kind === "api") { + if (!value.bin) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported API surfaces require a serve bin", path: ["bin"] }); + } + if (!value.health) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported API surfaces require a health endpoint", path: ["health"] }); + } + if (!value.readiness) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported API surfaces require a readiness endpoint", path: ["readiness"] }); + } + if (!value.version) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported API surfaces require a version endpoint", path: ["version"] }); + } + } + if (value.kind === "cli" && !value.bin) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported CLI surfaces require a bin", path: ["bin"] }); } - if (!value.health) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); + if (value.kind === "mcp" && !value.mcpBin) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported MCP surfaces require an mcpBin", path: ["mcpBin"] }); } - if (!value.version) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); + if (value.kind === "sdk" && !value.exportSubpath) { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported SDK surfaces require an exportSubpath", path: ["exportSubpath"] }); } } if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "Deferred or unsupported service surfaces require a deferReason", path: ["deferReason"] }); } if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); + } + if (value.health && value.health.method !== "GET") { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Health endpoint must use GET", path: ["health", "method"] }); } if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); + } + if (value.readiness && value.readiness.method !== "GET") { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Readiness endpoint must use GET", path: ["readiness", "method"] }); } if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); + } + if (value.version && value.version.method !== "GET") { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Version endpoint must use GET", path: ["version", "method"] }); } }); -var STORAGE_MODES4 = ["local", "cloud"]; -var StorageModeSchema4 = exports_external5.enum(STORAGE_MODES4); -var AppNameSchema4 = exports_external5.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES4 = [ +var STORAGE_MODES = ["sqlite", "postgres"]; +var StorageModeSchema = exports_external2.enum(STORAGE_MODES); +var STORAGE_ENGINES = ["sqlite", "postgres"]; +var StorageEngineSchema = exports_external2.enum(STORAGE_ENGINES); +var WAIVABLE_STORAGE_ENGINES = ["postgres"]; +var SurfaceConformanceWaiverSchema = exports_external2.object({ + kind: ServiceSurfaceKindSchema, + reason: exports_external2.string().trim().min(1) +}).strict(); +var STORAGE_WAIVER_REASON_MAX_LENGTH = 500; +var STORAGE_WAIVER_REVIEWER_MAX_LENGTH = 200; +var WaiverTextSchema = (maxLength) => exports_external2.string().trim().min(1).max(maxLength).regex(/^[^\u0000-\u001f\u007f]+$/, "Waiver text must not contain control characters"); +var ASSET_INVENTORY_KINDS = ["domain", "host", "ip", "email"]; +var AssetInventoryWaiverSchema = exports_external2.object({ + kind: exports_external2.enum(ASSET_INVENTORY_KINDS), + reason: WaiverTextSchema(STORAGE_WAIVER_REASON_MAX_LENGTH), + reviewedBy: WaiverTextSchema(STORAGE_WAIVER_REVIEWER_MAX_LENGTH), + expiresAt: TimestampSchema +}).strict(); +var StorageEngineWaiverSchema = exports_external2.object({ + engine: exports_external2.enum(WAIVABLE_STORAGE_ENGINES), + reason: WaiverTextSchema(STORAGE_WAIVER_REASON_MAX_LENGTH), + reviewedBy: WaiverTextSchema(STORAGE_WAIVER_REVIEWER_MAX_LENGTH).optional(), + expiresAt: TimestampSchema.optional() +}).strict(); +function storageWaiverIneligibilityReason(input) { + if (input.class !== "cli-with-store") { + return `storage waivers are not permitted for class ${input.class}`; + } + if (input.bins.includes(`${input.name}-serve`)) { + return `storage waivers are not permitted for a service-capable cli-with-store repo shipping ${input.name}-serve`; + } + if (input.storageMode === "postgres") { + return "storage waivers are not permitted while storage.mode is postgres, which reads and writes PostgreSQL directly"; + } + if (input.hosting.includes("hasna-saas")) { + return "storage waivers are not permitted for a repo declaring the hasna-saas product story"; + } + return null; +} +var ServiceContractMetadataSchema = exports_external2.object({ + conformance: exports_external2.object({ + waivedSurfaces: exports_external2.array(SurfaceConformanceWaiverSchema).default([]), + waiverProfile: exports_external2.literal("non-node-monorepo").optional(), + waivedStorageEngines: exports_external2.array(StorageEngineWaiverSchema).default([]), + waivedAssetInventories: exports_external2.array(AssetInventoryWaiverSchema).default([]) + }).catchall(exports_external2.unknown()).optional(), + release: exports_external2.object({ + artifactScan: exports_external2.object({ + script: exports_external2.string().trim().min(1) + }).strict().optional() + }).catchall(exports_external2.unknown()).optional() +}).catchall(exports_external2.unknown()); +var AppNameSchema = exports_external2.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); +var ALLOWED_BIN_SUFFIXES = [ "", "-cli", "-mcp", @@ -56768,43 +41170,190 @@ var ALLOWED_BIN_SUFFIXES4 = [ "-migrate", "-doctor" ]; -function allowedBinsForName4(name) { - return ALLOWED_BIN_SUFFIXES4.map((suffix) => `${name}${suffix}`); +function allowedBinsForName(name) { + return ALLOWED_BIN_SUFFIXES.map((suffix) => `${name}${suffix}`); } -function databaseUrlSecretRefFor4(name) { +function databaseUrlSecretRefFor(name) { return `hasna/oss/${name}/database-url`; } -var StorageContractSchema4 = exports_external5.object({ - mode: StorageModeSchema4, - envPrefix: exports_external5.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external5.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external5.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external5.string().min(1).optional() +var StorageContractSchema = exports_external2.object({ + mode: StorageModeSchema, + engines: exports_external2.array(StorageEngineSchema).min(1).optional(), + envPrefix: exports_external2.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), + aliasEnvPrefix: exports_external2.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), + databaseUrlSecretRef: exports_external2.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), + sqlitePath: exports_external2.string().min(1).endsWith(".db", "storage.sqlitePath must end in .db").optional(), + pgTestGate: exports_external2.object({ + envVar: exports_external2.string().regex(/^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$/), + command: exports_external2.string().trim().min(1) + }).strict().optional() +}).strict().superRefine((value, ctx) => { + if (value.engines && new Set(value.engines).size !== value.engines.length) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "storage.engines must not contain duplicates", + path: ["engines"] + }); + } + if (value.engines?.includes("postgres") && !value.envPrefix) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "storage.engines containing postgres requires envPrefix for the HASNA_<NAME>_DATABASE_URL contract", + path: ["envPrefix"] + }); + } +}); +var OwnerOnlyFileModeSchema = exports_external2.enum(["0600"]); +var OwnerOnlyDirectoryModeSchema = exports_external2.enum(["0700"]); +var LocalStoreRootSchema = exports_external2.enum([".hasna", ".codewith"]); +var SecureLocalStoreArtifactClassSchema = exports_external2.enum([ + "directory", + "file", + "sqlite_db", + "sqlite_wal", + "sqlite_shm", + "backup", + "export", + "report", + "tmp", + "log", + "session", + "snapshot" +]); +var SecureLocalStorePathPatternSchema = RelativeProjectPathSchema.refine((value) => !value.startsWith("~"), "Local store path patterns must be relative to their declared root"); +var SecureLocalStoreActiveRecordExclusionSchema = exports_external2.object({ + id: exports_external2.string().min(1), + source: exports_external2.enum(["sqlite", "manifest", "index", "runtime", "package_adapter"]), + table: exports_external2.string().min(1).optional(), + column: exports_external2.string().min(1).optional(), + description: exports_external2.string().min(1), + required: exports_external2.boolean().default(true) +}).strict(); +var SecureLocalStoreSqliteMaintenanceSchema = exports_external2.object({ + safeWhen: exports_external2.enum(["exclusive_access", "offline_only", "never"]), + operations: exports_external2.array(exports_external2.enum(["wal_checkpoint_truncate", "incremental_vacuum", "optimize", "vacuum"])).default([]) +}).strict().superRefine((value, ctx) => { + if (value.safeWhen === "never" && value.operations.length > 0) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "sqliteMaintenance.safeWhen=never cannot declare operations", + path: ["operations"] + }); + } +}); +var SecureLocalStoreRetentionAdapterSchema = exports_external2.object({ + id: exports_external2.string().min(1), + description: exports_external2.string().min(1), + ttlDays: exports_external2.number().int().nonnegative().optional(), + artifactClasses: exports_external2.array(SecureLocalStoreArtifactClassSchema).min(1), + allowlistGlobs: exports_external2.array(SecureLocalStorePathPatternSchema).min(1), + activeRecordExclusions: exports_external2.array(SecureLocalStoreActiveRecordExclusionSchema).default([]), + sqliteMaintenance: SecureLocalStoreSqliteMaintenanceSchema.optional() }).strict(); -var ServiceContractManifestSchema4 = exports_external5.object({ - $schema: exports_external5.string().min(1).optional(), - schema: exports_external5.literal(SCHEMA_IDS4.serviceContract), - name: AppNameSchema4, - class: RepoClassSchema4, - contractVersion: exports_external5.literal(SERVICE_CONTRACT_VERSION4), - kitVersion: exports_external5.string().min(1), - description: exports_external5.string().min(1).optional(), - bins: exports_external5.array(exports_external5.string().min(1)).default([]), - storage: StorageContractSchema4.optional(), - deploymentModes: exports_external5.array(DeploymentModeSchema4).default(["local"]), - serviceSurfaces: exports_external5.array(ServiceSurfaceSchema4).default([]), - metadata: MetadataSchema4.optional() +var SecureLocalStoreDefinitionSchema = exports_external2.object({ + storeId: exports_external2.string().regex(/^[a-z][a-z0-9-]*$/), + packageName: exports_external2.string().min(1), + displayName: exports_external2.string().min(1), + root: LocalStoreRootSchema, + relativePath: SecureLocalStorePathPatternSchema, + directoryMode: OwnerOnlyDirectoryModeSchema.default("0700"), + fileMode: OwnerOnlyFileModeSchema.default("0600"), + sqliteDatabaseGlobs: exports_external2.array(SecureLocalStorePathPatternSchema).default([]), + sensitiveFileGlobs: exports_external2.array(SecureLocalStorePathPatternSchema).default([]), + backupGlobs: exports_external2.array(SecureLocalStorePathPatternSchema).default([]), + exportGlobs: exports_external2.array(SecureLocalStorePathPatternSchema).default([]), + retentionAdapters: exports_external2.array(SecureLocalStoreRetentionAdapterSchema).default([]), + notes: exports_external2.array(exports_external2.string().min(1)).default([]) +}).strict().superRefine((value, ctx) => { + if (value.relativePath.includes("*")) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "store relativePath must be a concrete directory; use glob fields for files", + path: ["relativePath"] + }); + } + const adapterIds = new Set; + for (const [index, adapter] of value.retentionAdapters.entries()) { + if (adapterIds.has(adapter.id)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "retention adapter ids must be unique within a store", + path: ["retentionAdapters", index, "id"] + }); + } + adapterIds.add(adapter.id); + } +}); +var SecureLocalStorePolicySchema = contractBaseSchema(SCHEMA_IDS.secureLocalStorePolicy).extend({ + version: exports_external2.string().min(1), + scope: exports_external2.array(LocalStoreRootSchema).min(1), + defaults: exports_external2.object({ + directoryMode: OwnerOnlyDirectoryModeSchema.default("0700"), + fileMode: OwnerOnlyFileModeSchema.default("0600"), + dryRunDefault: exports_external2.literal(true), + requireExplicitApply: exports_external2.literal(true), + includeSqliteSidecars: exports_external2.literal(true), + redactedEvidenceOnly: exports_external2.literal(true) + }).strict(), + stores: exports_external2.array(SecureLocalStoreDefinitionSchema).min(1), + lifecycle: exports_external2.object({ + retentionDryRunDefault: exports_external2.literal(true), + requireActiveRecordExclusionProof: exports_external2.literal(true), + requireArtifactAllowlist: exports_external2.literal(true), + sqliteMaintenanceRequiresExclusiveAccess: exports_external2.literal(true) + }).strict(), + warnings: exports_external2.array(exports_external2.string().min(1)).default([]) +}).strict().superRefine((value, ctx) => { + const stores = new Set; + for (const [index, store] of value.stores.entries()) { + if (stores.has(store.storeId)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "store ids must be unique", + path: ["stores", index, "storeId"] + }); + } + stores.add(store.storeId); + if (!value.scope.includes(store.root)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "store root must be listed in policy scope", + path: ["stores", index, "root"] + }); + } + } +}); +var ServiceContractManifestSchema = exports_external2.object({ + $schema: exports_external2.string().min(1).optional(), + schema: exports_external2.literal(SCHEMA_IDS.serviceContract), + name: AppNameSchema, + class: RepoClassSchema, + contractVersion: exports_external2.literal(SERVICE_CONTRACT_VERSION), + kitVersion: exports_external2.string().min(1), + description: exports_external2.string().min(1).optional(), + bins: exports_external2.array(exports_external2.string().min(1)).default([]), + storage: StorageContractSchema.optional(), + hosting: exports_external2.array(HostingModeSchema).min(1).default(["user-hosted"]), + serviceSurfaces: exports_external2.array(ServiceSurfaceSchema).default([]), + metadata: ServiceContractMetadataSchema.optional() }).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName4(value.name)); + if (new Set(value.hosting).size !== value.hosting.length) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "hosting must not contain duplicates", + path: ["hosting"] + }); + } + const allowed = new Set(allowedBinsForName(value.name)); const seenBins = new Set; for (const [index, bin] of value.bins.entries()) { if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); } seenBins.add(bin); if (!allowed.has(bin)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, path: ["bins", index] }); @@ -56815,33 +41364,26 @@ var ServiceContractManifestSchema4 = exports_external5.object({ const upper = value.name.toUpperCase().replace(/-/g, "_"); if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `storage.envPrefix must be HASNA_${upper}_`, path: ["storage", "envPrefix"] }); } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor4(value.name)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor4(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { + if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor(value.name)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", + code: exports_external2.ZodIssueCode.custom, + message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor(value.name)}`, path: ["storage", "databaseUrlSecretRef"] }); } } if (value.class === "library") { if (value.storage) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); } if (hasBin("-serve") || hasBin("-mcp")) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "library repos must not ship a -serve or -mcp bin", path: ["bins"] }); @@ -56849,28 +41391,57 @@ var ServiceContractManifestSchema4 = exports_external5.object({ } if (value.class === "cli-with-store") { if (!value.storage) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", - path: ["storage", "sqlitePath"] - }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); + } else { + if (value.storage.mode === "sqlite" && !value.storage.sqlitePath) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "sqlite cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", + path: ["storage", "sqlitePath"] + }); + } + if (value.storage.engines) { + const declaredEngines = new Set(value.storage.engines); + const declaredWaivers = value.metadata?.conformance?.waivedStorageEngines ?? []; + const ineligible = storageWaiverIneligibilityReason({ + class: value.class, + name: value.name, + bins: value.bins, + hosting: value.hosting, + storageMode: value.storage.mode + }); + const waivedEngines = new Set(ineligible ? [] : declaredWaivers.map((waiver) => waiver.engine)); + const missingEngines = STORAGE_ENGINES.filter((engine) => !declaredEngines.has(engine) && !waivedEngines.has(engine)); + if (missingEngines.length > 0) { + const refusal = ineligible && declaredWaivers.length > 0 ? `; declared waiver ignored: ${ineligible}` : ""; + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `cli-with-store storage.engines must declare both sqlite and postgres unless the engine carries a metadata.conformance.waivedStorageEngines waiver; missing: ${missingEngines.join(", ")}${refusal}`, + path: ["storage", "engines"] + }); + } + } } if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); } } if (value.class === "service") { if (!value.storage) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); + } else if (value.storage.engines && (!value.storage.engines.includes("sqlite") || !value.storage.engines.includes("postgres"))) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "service storage.engines must declare both sqlite and postgres", + path: ["storage", "engines"] + }); } if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); } if (value.serviceSurfaces.length === 0) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "service repos must declare at least one service surface", path: ["serviceSurfaces"] }); @@ -56878,91 +41449,115 @@ var ServiceContractManifestSchema4 = exports_external5.object({ } if (value.class === "saas") { if (!value.storage) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); + } else { + if (value.storage.mode !== "postgres") { + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must use the postgres storage backend", path: ["storage", "mode"] }); + } + if (!value.storage.envPrefix) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: "saas storage requires envPrefix for the public DATABASE_URL contract", + path: ["storage", "envPrefix"] + }); + } } if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); } if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external5.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); + ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); } } for (const [index, surface] of value.serviceSurfaces.entries()) { if (surface.bin && !seenBins.has(surface.bin)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `Service surface bin "${surface.bin}" must be declared in bins`, path: ["serviceSurfaces", index, "bin"] }); } if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, path: ["serviceSurfaces", index, "mcpBin"] }); } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } + } + const waivedKinds = value.metadata?.conformance?.waivedSurfaces ?? []; + const seenWaivers = new Set; + for (const [index, waiver] of waivedKinds.entries()) { + if (seenWaivers.has(waiver.kind)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `Duplicate conformance waiver for ${waiver.kind}`, + path: ["metadata", "conformance", "waivedSurfaces", index, "kind"] + }); + } + seenWaivers.add(waiver.kind); + } + const waivedStorageEngines = value.metadata?.conformance?.waivedStorageEngines ?? []; + const seenStorageWaivers = new Set; + for (const [index, waiver] of waivedStorageEngines.entries()) { + if (seenStorageWaivers.has(waiver.engine)) { + ctx.addIssue({ + code: exports_external2.ZodIssueCode.custom, + message: `Duplicate storage-engine waiver for ${waiver.engine}`, + path: ["metadata", "conformance", "waivedStorageEngines", index, "engine"] + }); } + seenStorageWaivers.add(waiver.engine); } }); -var HealthResponseSchema4 = exports_external5.object({ - status: exports_external5.enum(["ok", "degraded", "unavailable"]), - version: exports_external5.string().min(1), - mode: StorageModeSchema4 +var HealthResponseSchema = exports_external2.object({ + status: exports_external2.enum(["ok", "degraded", "unavailable"]), + version: exports_external2.string().min(1), + mode: StorageModeSchema }).strict(); -var ReadyResponseSchema4 = exports_external5.object({ - ready: exports_external5.boolean(), - reason: exports_external5.string().min(1).optional() +var ReadyResponseSchema = exports_external2.object({ + ready: exports_external2.boolean(), + reason: exports_external2.string().min(1).optional() }).strict(); -var VersionResponseSchema4 = exports_external5.object({ - version: exports_external5.string().min(1) +var VersionResponseSchema = exports_external2.object({ + version: exports_external2.string().min(1) }).strict(); -var CommsSeveritySchema4 = exports_external5.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema4 = exports_external5.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); -var COMMS_SEVERITY_TAGS4 = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema4 = exports_external5.enum(COMMS_SEVERITY_TAGS4); -var CommsScopeSchema4 = exports_external5.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema4 = contractBaseSchema4(SCHEMA_IDS4.commsEventEnvelope).extend({ - type: CommsEventTypeSchema4, - severity: CommsSeveritySchema4, - scope: CommsScopeSchema4, - summary: exports_external5.string().min(1).optional(), - source: ActorPointerSchema4.optional(), - affected_packages: exports_external5.array(NonEmptyStringSchema4).default([]), - affected_machines: exports_external5.array(NonEmptyStringSchema4).default([]), - action_required: exports_external5.boolean().default(false), - ack_by: TimestampSchema4.optional(), - dedupe_key: NonEmptyStringSchema4, - resourceRefs: exports_external5.array(ResourcePointerSchema4).default([]), - evidenceRefs: exports_external5.array(EvidencePointerSchema4).default([]) +var CommsSeveritySchema = exports_external2.enum(["info", "notice", "breaking", "critical"]); +var CommsEventTypeSchema = exports_external2.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); +var COMMS_SEVERITY_TAGS = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; +var CommsSeverityTagSchema = exports_external2.enum(COMMS_SEVERITY_TAGS); +var CommsScopeSchema = exports_external2.enum(["fleet", "package", "machine"]); +var CommsEventEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.commsEventEnvelope).extend({ + type: CommsEventTypeSchema, + severity: CommsSeveritySchema, + scope: CommsScopeSchema, + summary: exports_external2.string().min(1).optional(), + source: ActorPointerSchema.optional(), + affected_packages: exports_external2.array(NonEmptyStringSchema).default([]), + affected_machines: exports_external2.array(NonEmptyStringSchema).default([]), + action_required: exports_external2.boolean().default(false), + ack_by: TimestampSchema.optional(), + dedupe_key: NonEmptyStringSchema, + resourceRefs: exports_external2.array(ResourcePointerSchema).default([]), + evidenceRefs: exports_external2.array(EvidencePointerSchema).default([]) }).strict().superRefine((value, ctx) => { if (value.scope === "package" && value.affected_packages.length === 0) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "Package-scoped comms events require affected_packages", path: ["affected_packages"] }); } if (value.scope === "machine" && value.affected_machines.length === 0) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "Machine-scoped comms events require affected_machines", path: ["affected_machines"] }); } if (value.ack_by && !value.action_required) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "Comms events with an ack_by deadline require action_required", path: ["action_required"] }); @@ -56970,55 +41565,55 @@ var CommsEventEnvelopeSchema4 = contractBaseSchema4(SCHEMA_IDS4.commsEventEnvelo if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { if (value.severity !== "critical") { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `${value.type} events are always critical`, path: ["severity"] }); } if (value.scope !== "fleet") { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `${value.type} events are always fleet-scoped`, path: ["scope"] }); } if (!value.action_required) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `${value.type} events require action_required`, path: ["action_required"] }); } } }); -var CommsChannelClassSchema4 = exports_external5.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema4 = exports_external5.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema4 = NonEmptyStringSchema4.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); -var CommsChannelMetadataSchema4 = contractBaseSchema4(SCHEMA_IDS4.commsChannelMetadata).extend({ - class: CommsChannelClassSchema4, - noise: CommsChannelNoiseSchema4.optional(), - owner: NonEmptyStringSchema4.optional(), - until: CommsUntilHorizonSchema4.optional(), - successor: NonEmptyStringSchema4.optional() +var CommsChannelClassSchema = exports_external2.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); +var CommsChannelNoiseSchema = exports_external2.enum(["quiet", "work", "firehose"]); +var CommsUntilHorizonSchema = NonEmptyStringSchema.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); +var CommsChannelMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsChannelMetadata).extend({ + class: CommsChannelClassSchema, + noise: CommsChannelNoiseSchema.optional(), + owner: NonEmptyStringSchema.optional(), + until: CommsUntilHorizonSchema.optional(), + successor: NonEmptyStringSchema.optional() }).strict().superRefine((value, ctx) => { if (value.class === "initiative") { if (!value.owner) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "Initiative channels require an owner", path: ["owner"] }); } if (!value.until) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: "Initiative channels require an until horizon (date or gate id)", path: ["until"] }); } } }); -var COMMS_SEVERITY_TAG_INFO4 = { +var COMMS_SEVERITY_TAG_INFO = { FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, @@ -57026,66 +41621,68 @@ var COMMS_SEVERITY_TAG_INFO4 = { POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } }; -var CommsMessageMetadataSchema4 = contractBaseSchema4(SCHEMA_IDS4.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema4, - envelope: CommsEventEnvelopeSchema4 +var CommsMessageMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsMessageMetadata).extend({ + tag: CommsSeverityTagSchema, + envelope: CommsEventEnvelopeSchema }).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO4[value.tag]; + const info = COMMS_SEVERITY_TAG_INFO[value.tag]; if (!info.allowedSeverities.includes(value.envelope.severity)) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, path: ["envelope", "severity"] }); } if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `[${value.tag}] posts require event type ${info.requiredEventType}`, path: ["envelope", "type"] }); } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO4)) { + for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO)) { if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { ctx.addIssue({ - code: exports_external5.ZodIssueCode.custom, + code: exports_external2.ZodIssueCode.custom, message: `${value.envelope.type} events must use the [${tag}] tag`, path: ["tag"] }); } } }); -var ContractSchemaRegistry4 = { - [SCHEMA_IDS4.actorRef]: ActorRefSchema4, - [SCHEMA_IDS4.resourceRef]: ResourceRefSchema4, - [SCHEMA_IDS4.evidenceRef]: EvidenceRefSchema4, - [SCHEMA_IDS4.workRun]: WorkRunSchema4, - [SCHEMA_IDS4.decisionEnvelope]: DecisionEnvelopeSchema4, - [SCHEMA_IDS4.costEstimate]: CostEstimateSchema4, - [SCHEMA_IDS4.capabilityCard]: CapabilityCardSchema4, - [SCHEMA_IDS4.providerLiveModeStandard]: ProviderLiveModeStandardSchema4, - [SCHEMA_IDS4.contextPack]: ContextPackSchema4, - [SCHEMA_IDS4.integrationRef]: IntegrationRefSchema4, - [SCHEMA_IDS4.projectManifest]: ProjectManifestSchema4, - [SCHEMA_IDS4.projectPanel]: ProjectPanelSchema4, - [SCHEMA_IDS4.projectSnapshot]: ProjectSnapshotSchema4, - [SCHEMA_IDS4.renderManifest]: RenderManifestSchema4, - [SCHEMA_IDS4.agentTrajectory]: AgentTrajectorySchema4, - [SCHEMA_IDS4.validationPlan]: ValidationPlanSchema4, - [SCHEMA_IDS4.proofBundle]: ProofBundleSchema4, - [SCHEMA_IDS4.scaffoldManifest]: ScaffoldManifestSchema4, - [SCHEMA_IDS4.scaffoldInstallRecord]: ScaffoldInstallRecordSchema4, - [SCHEMA_IDS4.appCloudManifest]: AppCloudManifestSchema4, - [SCHEMA_IDS4.noCloudEvidencePack]: NoCloudEvidencePackSchema4, - [SCHEMA_IDS4.serviceContract]: ServiceContractManifestSchema4, - [SCHEMA_IDS4.commsEventEnvelope]: CommsEventEnvelopeSchema4, - [SCHEMA_IDS4.commsChannelMetadata]: CommsChannelMetadataSchema4, - [SCHEMA_IDS4.commsMessageMetadata]: CommsMessageMetadataSchema4, - [SCHEMA_IDS4.app]: AppSchema4, - [SCHEMA_IDS4.release]: ReleaseSchema4, - [SCHEMA_IDS4.rolloutRecord]: RolloutRecordSchema4, - [SCHEMA_IDS4.announcement]: AnnouncementSchema4, - [SCHEMA_IDS4.audience]: AudienceSchema4 +var ContractSchemaRegistry = { + [SCHEMA_IDS.actorRef]: ActorRefSchema, + [SCHEMA_IDS.resourceRef]: ResourceRefSchema, + [SCHEMA_IDS.evidenceRef]: EvidenceRefSchema, + [SCHEMA_IDS.workRun]: WorkRunSchema, + [SCHEMA_IDS.taskToPrProjection]: TaskToPrProjectionSchema, + [SCHEMA_IDS.decisionEnvelope]: DecisionEnvelopeSchema, + [SCHEMA_IDS.costEstimate]: CostEstimateSchema, + [SCHEMA_IDS.capabilityCard]: CapabilityCardSchema, + [SCHEMA_IDS.providerLiveModeStandard]: ProviderLiveModeStandardSchema, + [SCHEMA_IDS.contextPack]: ContextPackSchema, + [SCHEMA_IDS.integrationRef]: IntegrationRefSchema, + [SCHEMA_IDS.projectManifest]: ProjectManifestSchema, + [SCHEMA_IDS.projectPanel]: ProjectPanelSchema, + [SCHEMA_IDS.projectSnapshot]: ProjectSnapshotSchema, + [SCHEMA_IDS.renderManifest]: RenderManifestSchema, + [SCHEMA_IDS.agentTrajectory]: AgentTrajectorySchema, + [SCHEMA_IDS.validationPlan]: ValidationPlanSchema, + [SCHEMA_IDS.proofBundle]: ProofBundleSchema, + [SCHEMA_IDS.scaffoldManifest]: ScaffoldManifestSchema, + [SCHEMA_IDS.scaffoldInstallRecord]: ScaffoldInstallRecordSchema, + [SCHEMA_IDS.appCloudManifest]: AppCloudManifestSchema, + [SCHEMA_IDS.noCloudEvidencePack]: NoCloudEvidencePackSchema, + [SCHEMA_IDS.secureLocalStorePolicy]: SecureLocalStorePolicySchema, + [SCHEMA_IDS.serviceContract]: ServiceContractManifestSchema, + [SCHEMA_IDS.commsEventEnvelope]: CommsEventEnvelopeSchema, + [SCHEMA_IDS.commsChannelMetadata]: CommsChannelMetadataSchema, + [SCHEMA_IDS.commsMessageMetadata]: CommsMessageMetadataSchema, + [SCHEMA_IDS.app]: AppSchema, + [SCHEMA_IDS.release]: ReleaseSchema, + [SCHEMA_IDS.rolloutRecord]: RolloutRecordSchema, + [SCHEMA_IDS.announcement]: AnnouncementSchema, + [SCHEMA_IDS.audience]: AudienceSchema }; class ContractValidationError extends Error { @@ -57099,47 +41696,116 @@ class ContractValidationError extends Error { } } function parseContract(schemaId, value) { - const schema = ContractSchemaRegistry4[schemaId]; + const schema = ContractSchemaRegistry[schemaId]; const parsed = schema.safeParse(value); if (!parsed.success) { throw new ContractValidationError(schemaId, parsed.error.issues); } return parsed.data; } +var MAX_ARCHIVE_MEMBER_BYTES = 5 * 1024 * 1024; +var MAX_SCANNED_MEMBER_BYTES = 512 * 1024 * 1024; +var INERT_CALLEES = new Set([ + "expect", + "not", + "toBe", + "toEqual", + "toStrictEqual", + "toContain", + "toContainEqual", + "toMatch", + "toMatchObject", + "toHaveProperty", + "toBeUndefined", + "toBeDefined", + "describe", + "it", + "test", + "includes", + "indexOf", + "lastIndexOf", + "startsWith", + "endsWith", + "has", + "match", + "search", + "split", + "concat", + "existsSync", + "statSync", + "lstatSync", + "readFileSync", + "readdirSync", + "join", + "basename", + "dirname", + "extname", + "relative", + "normalize", + "push", + "add", + "filter", + "some", + "every", + "find", + "map", + "RegExp", + "raw" +]); +var LOAD_CALLEE = String.raw`(?:^|[^\w$])(?:_*(?:import|require)|createRequire|Module\s*\.\s*_load)`; var SKIP_DIRS = new Set([".git", "node_modules", ".cache", ".next", ".turbo", "coverage", "docs", "examples", "tests"]); var LOCKFILES = new Set(["bun.lock", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"]); var SOURCE_DIRS = new Set(["src", "bin", "cli", "mcp", "server", "lib", "scripts", "config", "infra", "hooks", ".github", "dist"]); var MAX_TEXT_BYTES = 5 * 1024 * 1024; -var CONTRACTS_DECLARATION_PATHS = new Set([ - "src/no-cloud.ts", - "src/schemas.ts", - "dist/no-cloud.js", - "dist/schemas.js", - "dist/validators.js", - "dist/index.js", - "dist/mode.js", - "dist/service-contract.js", - "dist/conformance.js", - "dist/client/transport.js", - "dist/client/storage.js", - "dist/cli/index.js", - "dist/no-cloud.d.ts", - "dist/schemas.d.ts", - "dist/mode.d.ts", - "dist/service-contract.d.ts", - "dist/conformance.d.ts" -]); +var RUNTIME_PATTERNS = [ + { pattern: "@hasna/cloud", kind: "module", message: "Shared @hasna/cloud runtime reference is forbidden" }, + { pattern: "open-cloud", kind: "module", message: "Shared open-cloud runtime reference is forbidden" }, + { pattern: "cloud-mcp", kind: "module", message: "Legacy cloud-mcp runtime surface is forbidden" }, + { pattern: "registerCloudTools", kind: "symbol", message: "Legacy registerCloudTools runtime surface is forbidden" }, + { pattern: "registerCloudCommands", kind: "symbol", message: "Legacy registerCloudCommands runtime surface is forbidden" }, + { pattern: ".hasna/cloud", kind: "config", checkKind: "runtime_config", message: "Legacy .hasna/cloud runtime config is forbidden" }, + { pattern: "HASNA_CLOUD_", kind: "config", message: "Shared HASNA_CLOUD_* runtime config is forbidden" }, + { pattern: "HASNA_RDS_PASSWORD", kind: "config", message: "Legacy shared RDS credential config is forbidden" } +]; +var PATH_CONFIG_PATTERNS = RUNTIME_PATTERNS.filter((entry) => ("checkKind" in entry)); +var MODULE_PATTERNS = RUNTIME_PATTERNS.filter((entry) => entry.kind === "module"); +var FORBIDDEN_LOCKFILE_PACKAGES = [ + ...new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES, ...MODULE_PATTERNS.map((entry) => entry.pattern)]) +]; +var LOCKFILE_TEXT_PATTERNS = RUNTIME_PATTERNS.filter((entry) => entry.kind === "config"); +var WAIVER_TEXT_JSON_SCHEMA_PATTERN = "^[^\\u0000-\\u001f\\u007f]*$"; var SERVICE_CONTRACT_JSON_SCHEMA = { $schema: "http://json-schema.org/draft-07/schema#", $id: "https://github.com/hasna/contracts/schema/hasna.service_contract.v1.json", title: "Hasna Service Contract v1", - description: "Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Storage runtime enum is local|cloud ONLY per Amendment A1 (PURE REMOTE).", + description: "Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Hosting story, product surfaces, and storage capabilities are separate declarations; the storage backend (sqlite | postgres) is the only runtime switch.", type: "object", additionalProperties: false, required: ["schema", "name", "class", "contractVersion", "kitVersion"], + allOf: [ + { + if: { + required: ["class"], + properties: { + class: { const: "saas" } + } + }, + then: { + required: ["storage"], + properties: { + storage: { + required: ["mode", "envPrefix"], + properties: { + mode: { const: "postgres" } + } + } + } + } + } + ], properties: { $schema: { type: "string", description: "Optional editor hint pointing at this JSON Schema." }, - schema: { const: SCHEMA_IDS4.serviceContract }, + schema: { const: SCHEMA_IDS.serviceContract }, name: { type: "string", pattern: "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", @@ -57158,34 +41824,46 @@ var SERVICE_CONTRACT_JSON_SCHEMA = { items: { type: "string", minLength: 1 }, description: "Declared bins. Allowlisted: <name>, <name>-cli, <name>-mcp, <name>-serve, <name>-worker, <name>-runner, <name>-daemon, <name>-migrate, <name>-doctor." }, - deploymentModes: { + hosting: { type: "array", - items: { enum: ["local", "self-hosted", "cloud"] }, - description: "Supported deployment modes. local = this machine, self-hosted = Hasna-owned AWS, cloud = multi-tenant SaaS for outside users." + items: { enum: ["user-hosted", "hasna-saas"] }, + minItems: 1, + uniqueItems: true, + description: "Customer-facing product stories. Public OSS cores include user-hosted; add hasna-saas only when a managed control plane exists." }, serviceSurfaces: { type: "array", items: { type: "object", additionalProperties: false, - required: ["name", "status", "authMode", "deploymentModes"], + required: ["name", "status", "authMode"], + allOf: [ + { + if: { + required: ["status"], + properties: { + status: { const: "supported" }, + kind: { const: "api" } + } + }, + then: { + required: ["bin", "health", "readiness", "version"] + } + } + ], properties: { name: { type: "string", minLength: 1 }, + kind: { enum: ["api", "sdk", "mcp", "cli"] }, status: { enum: ["supported", "deferred", "unsupported"] }, bin: { type: "string", minLength: 1 }, mcpBin: { type: "string", minLength: 1 }, authMode: { enum: ["none", "local-only", "api-key", "session", "service-token", "custom"] }, - deploymentModes: { - type: "array", - items: { enum: ["local", "self-hosted", "cloud"] }, - minItems: 1 - }, health: { type: "object", additionalProperties: false, required: ["method", "path"], properties: { - method: { enum: ["GET", "POST", "PUT", "PATCH", "DELETE"] }, + method: { const: "GET" }, path: { type: "string", pattern: "^/[A-Za-z0-9_./:*-]*$" }, public: { type: "boolean" }, description: { type: "string", minLength: 1 } @@ -57196,7 +41874,7 @@ var SERVICE_CONTRACT_JSON_SCHEMA = { additionalProperties: false, required: ["method", "path"], properties: { - method: { enum: ["GET", "POST", "PUT", "PATCH", "DELETE"] }, + method: { const: "GET" }, path: { type: "string", pattern: "^/[A-Za-z0-9_./:*-]*$" }, public: { type: "boolean" }, description: { type: "string", minLength: 1 } @@ -57207,7 +41885,7 @@ var SERVICE_CONTRACT_JSON_SCHEMA = { additionalProperties: false, required: ["method", "path"], properties: { - method: { enum: ["GET", "POST", "PUT", "PATCH", "DELETE"] }, + method: { const: "GET" }, path: { type: "string", pattern: "^/[A-Za-z0-9_./:*-]*$" }, public: { type: "boolean" }, description: { type: "string", minLength: 1 } @@ -57215,6 +41893,20 @@ var SERVICE_CONTRACT_JSON_SCHEMA = { }, apiBasePath: { type: "string", pattern: "^/v[0-9]+$" }, openApiPath: { type: "string", pattern: "^/[A-Za-z0-9_./:-]*$" }, + exportSubpath: { + type: "string", + pattern: "^\\.(?:\\/[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)*)?$", + description: "SDK package export key such as . or ./sdk." + }, + generatedFrom: { + type: "string", + pattern: "^/[A-Za-z0-9_./:-]*$", + description: "OpenAPI path used to generate the SDK." + }, + clientClassName: { + type: "string", + pattern: "^[A-Za-z_$][A-Za-z0-9_$]*$" + }, deferReason: { type: "string", minLength: 1 }, readinessGates: { type: "array", @@ -57237,7 +41929,7 @@ var SERVICE_CONTRACT_JSON_SCHEMA = { } } }, - description: "Declared HTTP/MCP service surfaces. Supported surfaces name lifecycle endpoints; unsafe or unfinished surfaces use deferred/unsupported with a reason." + description: "Declared API, SDK, MCP, and CLI product surfaces. Legacy entries without kind remain parseable; new manifests declare kind explicitly." }, storage: { type: "object", @@ -57245,8 +41937,15 @@ var SERVICE_CONTRACT_JSON_SCHEMA = { required: ["mode"], properties: { mode: { - enum: ["local", "cloud"], - description: "Runtime storage enum. local|cloud ONLY (Amendment A1: PURE REMOTE)." + enum: ["sqlite", "postgres"], + description: "Active data backend. sqlite|postgres ONLY \u2014 the single runtime switch." + }, + engines: { + type: "array", + items: { enum: ["sqlite", "postgres"] }, + minItems: 1, + uniqueItems: true, + description: "Supported storage engines; capability metadata independent of the active backend." }, envPrefix: { type: "string", @@ -57261,20 +41960,381 @@ var SERVICE_CONTRACT_JSON_SCHEMA = { databaseUrlSecretRef: { type: "string", pattern: "^hasna/oss/[a-z0-9-]+/database-url$", - description: "Secret Manager ref for the cloud database URL." + description: "Legacy/private-tier database secret ref. Public conformance rejects this field." }, sqlitePath: { type: "string", - minLength: 1, + pattern: "\\.db$", description: "Local sqlite path (~/.hasna/<name>/<name>.db)." + }, + pgTestGate: { + type: "object", + additionalProperties: false, + required: ["envVar", "command"], + properties: { + envVar: { + type: "string", + pattern: "^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$" + }, + command: { type: "string", minLength: 1 } + }, + description: "Environment-gated live PostgreSQL test command." } } }, - metadata: { type: "object" } + metadata: { + type: "object", + additionalProperties: true, + properties: { + conformance: { + type: "object", + additionalProperties: true, + properties: { + waiverProfile: { + const: "non-node-monorepo", + description: "Explicit surface-waiver eligibility for exceptional non-Node monorepos. Libraries are eligible for API/MCP waivers without this profile." + }, + waivedSurfaces: { + type: "array", + uniqueItems: true, + items: { + type: "object", + additionalProperties: false, + required: ["kind", "reason"], + properties: { + kind: { enum: ["api", "sdk", "mcp", "cli"] }, + reason: { type: "string", minLength: 1 } + } + } + }, + waivedStorageEngines: { + type: "array", + uniqueItems: true, + maxItems: WAIVABLE_STORAGE_ENGINES.length, + items: { + type: "object", + additionalProperties: false, + required: ["engine", "reason"], + properties: { + engine: { enum: [...WAIVABLE_STORAGE_ENGINES] }, + reason: { + type: "string", + minLength: 1, + maxLength: STORAGE_WAIVER_REASON_MAX_LENGTH, + allOf: [{ pattern: "\\S" }, { pattern: WAIVER_TEXT_JSON_SCHEMA_PATTERN }] + }, + reviewedBy: { + type: "string", + minLength: 1, + maxLength: STORAGE_WAIVER_REVIEWER_MAX_LENGTH, + allOf: [{ pattern: "\\S" }, { pattern: WAIVER_TEXT_JSON_SCHEMA_PATTERN }] + }, + expiresAt: { type: "string", format: "date-time" } + } + }, + description: "Explicit storage-engine exceptions, at most one per engine. Only a CLI-only cli-with-store repo (no <name>-serve bin, storage.mode sqlite, no hasna-saas story) may waive postgres; sqlite is never waivable, expiresAt is a UTC RFC 3339 timestamp, and conformance stops honouring a waiver once it has passed." + } + } + } + } + } } }; +var SECURE_LOCAL_STORE_POLICY_VERSION = "2026-07-06"; +function retentionAdapter(id, description, ttlDays, artifactClasses, allowlistGlobs, activeRecordExclusions = [], sqliteMaintenance) { + return { + id, + description, + ttlDays, + artifactClasses, + allowlistGlobs, + activeRecordExclusions: activeRecordExclusions.map((exclusion) => ({ ...exclusion, required: exclusion.required ?? true })), + sqliteMaintenance + }; +} +var DEFAULT_SECURE_LOCAL_STORE_POLICY = SecureLocalStorePolicySchema.parse({ + schema: SCHEMA_IDS.secureLocalStorePolicy, + id: "hasna-secure-local-store-defaults", + createdAt: "2026-07-06T00:00:00.000Z", + version: SECURE_LOCAL_STORE_POLICY_VERSION, + scope: [".hasna", ".codewith"], + defaults: { + directoryMode: "0700", + fileMode: "0600", + dryRunDefault: true, + requireExplicitApply: true, + includeSqliteSidecars: true, + redactedEvidenceOnly: true + }, + lifecycle: { + retentionDryRunDefault: true, + requireActiveRecordExclusionProof: true, + requireArtifactAllowlist: true, + sqliteMaintenanceRequiresExclusiveAccess: true + }, + stores: [ + { + storeId: "codewith", + packageName: "codewith", + displayName: "Codewith native state", + root: ".codewith", + relativePath: ".", + sqliteDatabaseGlobs: ["logs_*.sqlite", "state_*.sqlite", "goals_*.sqlite"], + sensitiveFileGlobs: ["sessions/**/*.jsonl", "shell_snapshots/**/*", "logs*.sqlite", "state*.sqlite", "goals*.sqlite"], + backupGlobs: ["backups/**/*"], + exportGlobs: ["exports/**/*"], + retentionAdapters: [ + retentionAdapter("codewith-session-snapshots", "Codewith sessions, shell snapshots, logs, monitor output, mailbox payloads, and scheduler state need package-owned redaction before retention applies.", 30, ["session", "snapshot", "log"], ["sessions/**/*.jsonl", "shell_snapshots/**/*", "logs/**/*"], [ + { + id: "codewith-active-session", + source: "package_adapter", + description: "Exclude currently active sessions, leased schedules, monitors, pending interactions, and active goal rows." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ], + notes: ["Includes native .codewith DBs and transcript-like artifacts; redaction-before-persistence remains package-owned."] + }, + { + storeId: "todos", + packageName: "@hasna/todos", + displayName: "Todos", + root: ".hasna", + relativePath: "todos", + sqliteDatabaseGlobs: ["todos.db"], + sensitiveFileGlobs: ["todos.db", "todos.db-wal", "todos.db-shm", "exports/**/*", "backups/**/*"], + backupGlobs: ["backups/**/*", "*.bak", "*.backup"], + exportGlobs: ["exports/**/*", "*.jsonl", "*.csv"], + retentionAdapters: [ + retentionAdapter("todos-exports-backups", "Todos backups and exports are deleted only after package redaction and active task/evidence references are excluded.", 14, ["backup", "export"], ["backups/**/*", "exports/**/*"], [ + { + id: "todos-active-evidence", + source: "sqlite", + table: "task_files", + column: "path", + description: "Exclude files still referenced by active tasks, verification evidence, task comments, or handoff records." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "conversations", + packageName: "@hasna/conversations", + displayName: "Conversations", + root: ".hasna", + relativePath: "conversations", + sqliteDatabaseGlobs: ["messages.db"], + sensitiveFileGlobs: ["messages.db", "messages.db-wal", "messages.db-shm", "exports/**/*", "attachments/**/*"], + backupGlobs: ["backups/**/*", "*.bak"], + exportGlobs: ["exports/**/*", "*.json", "*.csv"], + retentionAdapters: [ + retentionAdapter("conversations-exports-attachments", "Conversation exports and attachments require message-id redaction and active attachment reference checks before deletion.", 14, ["export", "backup"], ["exports/**/*", "backups/**/*", "attachments/**/*"], [ + { + id: "conversations-active-attachments", + source: "sqlite", + table: "messages", + column: "attachments", + description: "Exclude attachments still referenced by retained messages or audited redaction records." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "mementos", + packageName: "@hasna/mementos", + displayName: "Mementos", + root: ".hasna", + relativePath: "mementos", + sqliteDatabaseGlobs: ["mementos.db"], + sensitiveFileGlobs: ["mementos.db", "mementos.db-wal", "mementos.db-shm", "exports/**/*", "backups/**/*"], + backupGlobs: ["backups/**/*", "*.bak"], + exportGlobs: ["exports/**/*"], + retentionAdapters: [ + retentionAdapter("mementos-audit-search-history", "Mementos retention must preserve active memory versions while compacting audit/search surfaces through package-owned adapters.", 30, ["backup", "export", "log"], ["backups/**/*", "exports/**/*", "audit/**/*"], [ + { + id: "mementos-active-memory-versions", + source: "sqlite", + table: "memory_versions", + column: "memory_id", + description: "Exclude current memory versions and audit entries required for provenance." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "knowledge", + packageName: "@hasna/knowledge", + displayName: "Knowledge", + root: ".hasna", + relativePath: "knowledge", + sqliteDatabaseGlobs: ["knowledge.db"], + sensitiveFileGlobs: ["knowledge.db", "knowledge.db-wal", "knowledge.db-shm", "db.json", "migration-exports/**/*", "*.bak"], + backupGlobs: ["*.bak", "backups/**/*", "*.pre-cloud-*"], + exportGlobs: ["migration-exports/**/*", "exports/**/*", "*.jsonl"], + retentionAdapters: [ + retentionAdapter("knowledge-migrations-exports", "Knowledge migration exports and pre-cloud backups require replacement, encryption, or redaction before retention deletion.", 14, ["backup", "export"], ["migration-exports/**/*", "exports/**/*", "*.bak", "*.pre-cloud-*"], [ + { + id: "knowledge-current-catalog", + source: "manifest", + description: "Exclude files referenced by the active catalog or migration ledger." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "projects", + packageName: "@hasna/projects", + displayName: "Projects", + root: ".hasna", + relativePath: "projects", + sqliteDatabaseGlobs: ["projects.db", "data/*/project.db"], + sensitiveFileGlobs: ["projects.db", "projects.db-wal", "projects.db-shm", "data/*/project.db", "data/*/project.db-wal", "data/*/project.db-shm", "reports/**/*"], + backupGlobs: ["backups/**/*", "data/*/backups/**/*"], + exportGlobs: ["reports/**/*", "exports/**/*"], + retentionAdapters: [ + retentionAdapter("projects-reports-workspaces", "Project reports, dashboards, workspaces, and per-project DBs need active workspace/location references before cleanup.", 30, ["backup", "export", "report", "tmp"], ["backups/**/*", "reports/**/*", "workspaces/**/*", "data/*/backups/**/*"], [ + { + id: "projects-active-workspaces", + source: "sqlite", + table: "workspaces", + column: "primary_path", + description: "Exclude active workspace paths, locations, linked reports, and project store artifacts." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "browser", + packageName: "@hasna/browser", + displayName: "Browser", + root: ".hasna", + relativePath: "browser", + sqliteDatabaseGlobs: ["browser.db"], + sensitiveFileGlobs: ["browser.db", "browser.db-wal", "browser.db-shm", "profiles/**/cookies.json", "states/**/*.json", "auth/**/*"], + backupGlobs: ["backups/**/*"], + exportGlobs: ["exports/**/*", "traces/**/*", "har/**/*"], + retentionAdapters: [ + retentionAdapter("browser-auth-traces", "Browser state, trace, HAR, and auth artifacts require session invalidation or redaction before deletion.", 7, ["backup", "export", "session", "snapshot"], ["profiles/**/*", "states/**/*", "traces/**/*", "har/**/*", "exports/**/*"], [ + { + id: "browser-active-profiles", + source: "sqlite", + table: "sessions", + column: "profile_path", + description: "Exclude profiles, cookies, and storage state used by active browser sessions." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "terminal", + packageName: "@hasna/terminal", + displayName: "Terminal", + root: ".hasna", + relativePath: "terminal", + sqliteDatabaseGlobs: ["sessions.db"], + sensitiveFileGlobs: ["sessions.db", "sessions.db-wal", "sessions.db-shm", "exports/**/*"], + backupGlobs: ["backups/**/*"], + exportGlobs: ["exports/**/*"], + retentionAdapters: [ + retentionAdapter("terminal-sessions", "Terminal sessions and interactions need active session exclusion plus command-output redaction before retention.", 30, ["backup", "export", "session", "log"], ["backups/**/*", "exports/**/*", "sessions/**/*"], [ + { + id: "terminal-active-sessions", + source: "sqlite", + table: "sessions", + column: "id", + description: "Exclude active terminal session records and any linked interaction artifacts." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "logs", + packageName: "@hasna/logs", + displayName: "Logs", + root: ".hasna", + relativePath: "logs", + sqliteDatabaseGlobs: ["logs.db"], + sensitiveFileGlobs: ["logs.db", "logs.db-wal", "logs.db-shm", "exports/**/*"], + backupGlobs: ["backups/**/*"], + exportGlobs: ["exports/**/*"], + retentionAdapters: [ + retentionAdapter("logs-retention", "Logs require redaction before compaction and must preserve active incident/evidence references.", 14, ["backup", "export", "log"], ["backups/**/*", "exports/**/*", "*.log", "logs/**/*"], [ + { + id: "logs-active-evidence", + source: "sqlite", + table: "logs", + column: "id", + description: "Exclude log rows or files linked to active incidents, tasks, or proof bundles." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + }, + { + storeId: "loops", + packageName: "@hasna/loops", + displayName: "OpenLoops", + root: ".hasna", + relativePath: "loops", + sqliteDatabaseGlobs: ["loops.db", "state.db", "*.sqlite"], + sensitiveFileGlobs: ["*.db", "*.sqlite", "*.db-wal", "*.db-shm", "reports/**/*", "tmp/**/*", "runs/**/*"], + backupGlobs: ["backups/**/*", "tmp/**/*"], + exportGlobs: ["reports/**/*", "runs/**/*", "exports/**/*"], + retentionAdapters: [ + retentionAdapter("loops-reports-tmp", "Loop reports, tmp files, workflow artifacts, and command output need run-state checks and redaction before retention deletion.", 14, ["backup", "export", "report", "tmp", "log"], ["reports/**/*", "tmp/**/*", "runs/**/*", "exports/**/*"], [ + { + id: "loops-active-runs", + source: "sqlite", + table: "loop_runs", + column: "id", + description: "Exclude active, leased, recently failed, or evidence-linked loop and workflow run artifacts." + } + ], { safeWhen: "exclusive_access", operations: ["wal_checkpoint_truncate", "optimize"] }) + ] + } + ], + warnings: [ + "This package publishes declarations only; each owning package implements and verifies its own local-store lifecycle.", + "Retention and redaction evidence remain package-owned and must preserve active-record exclusions.", + "SQLite maintenance is descriptive policy metadata only and is never executed by @hasna/contracts." + ] +}); +var MAX_TENANT_ID_LENGTH2 = 64; +var TENANT_ID_PATTERN2 = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_TENANT_ID_LENGTH2 - 1}}$`); +var UUID_HEX2 = "[0-9a-fA-F]"; +var UUID_PATTERN2 = new RegExp(`^\\{?(?:${UUID_HEX2}{8}-${UUID_HEX2}{4}-${UUID_HEX2}{4}-${UUID_HEX2}{4}-${UUID_HEX2}{12}|${UUID_HEX2}{32})\\}?$`); +var API_KEY_TOKEN_PATTERN2 = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/; var DEFAULT_API_KEY_TTL_SECONDS2 = 90 * 24 * 60 * 60; +var SKIP_DIRS2 = new Set([ + ".git", + "node_modules", + "dist", + "build", + "out", + "bin", + "coverage", + ".next", + ".turbo", + ".cache", + "tests", + "test", + "__tests__", + "examples", + "docs", + "scripts" +]); +var INBOUND_SURFACE_DIRS = new Set(["server", "http", "api", "mcp"]); +var HASNA_API_KEY_TOKEN_PATTERN = new RegExp(API_KEY_TOKEN_PATTERN2.source.replace(/^\^/, "\\b").replace(/\$$/, "\\b")); +var MAX_FLEET_TOKEN_TTL_SECONDS2 = 24 * 60 * 60; +var MAX_CREDENTIAL_FILE_BYTES3 = 64 * 1024; +var INSPECT_CUSTOM3 = Symbol.for("nodejs.util.inspect.custom"); +var DEPRECATION_REGISTRY3 = Symbol.for("hasna:contracts:credentialDeprecationNotices"); var IDEMPOTENT_METHODS3 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); +var AUTHORITY_OVERRIDE_HEADERS3 = new Set([ + "host", + ":authority", + "forwarded", + "x-forwarded-host", + "x-original-host" +]); // src/project-panel.ts var SOURCE_PACKAGE = "@hasna/knowledge"; @@ -57306,7 +42366,7 @@ function toTimestamp(value) { return Number.isNaN(parsed.valueOf()) ? undefined : parsed.toISOString(); } function hasUriScheme(value) { - return UriSchema4.safeParse(value).success; + return UriSchema.safeParse(value).success; } function resource(kind, id, name, uri, tags = []) { return { @@ -57462,7 +42522,7 @@ async function createKnowledgeProjectPanel(projectRef, options = {}) { const state = totalKnowledge === 0 ? "empty" : freshness === "stale" ? "stale" : "ready"; const items = inventoryItems(inventory, limit); const draft = { - schema: SCHEMA_IDS4.projectPanel, + schema: SCHEMA_IDS.projectPanel, id: `knowledge_panel_${projectId}`, createdAt: generatedAt, projectId, @@ -57516,7 +42576,7 @@ async function createKnowledgeProjectPanel(projectRef, options = {}) { latest_activity_at: latest } }; - return parseContract(SCHEMA_IDS4.projectPanel, draft); + return parseContract(SCHEMA_IDS.projectPanel, draft); } function formatKnowledgeProjectPanel(panel) { const lines = [ diff --git a/dist/item-store.d.ts b/dist/item-store.d.ts index ea7ca5d..b409409 100644 --- a/dist/item-store.d.ts +++ b/dist/item-store.d.ts @@ -83,7 +83,7 @@ export interface ResolveItemStoreOptions { } /** * Resolve the single item Store for this invocation. Returns the ApiItemStore - * only when the mode is explicitly cloud, otherwise the LocalItemStore. An + * only when the mode is explicitly postgres, otherwise the LocalItemStore. An * explicit `--store` override always yields the local transport so the flip * stays fully reversible. */ diff --git a/dist/knowledge-mode.d.ts b/dist/knowledge-mode.d.ts index 8d1441e..94b553c 100644 --- a/dist/knowledge-mode.d.ts +++ b/dist/knowledge-mode.d.ts @@ -8,18 +8,18 @@ export declare const KNOWLEDGE_APP_SLUG = "knowledge"; * transport underneath us. */ export declare const KNOWLEDGE_MODE_ENV_KEYS: readonly string[]; -/** Pointer keys: where the cloud is. Never a mode selector. */ +/** Pointer keys: where the server is. Never a mode selector. */ export declare const KNOWLEDGE_API_URL_ENV_KEYS: readonly string[]; /** Pointer keys: how to authenticate. Never a mode selector, never logged. */ export declare const KNOWLEDGE_API_KEY_ENV_KEYS: readonly string[]; -/** `local` = on-box store. `cloud` = the app's HTTP `/v1` API. */ +/** `sqlite` = on-box store. `postgres` = server data reached by clients over HTTP. */ export type KnowledgeMode = StorageMode; export interface KnowledgeModeSource { /** `env` when a mode var selected it, `default` when nothing did. */ kind: 'env' | 'default'; /** The env key that selected the mode, or null for the default. */ name: string | null; - /** The mode var's own value (`local` / `cloud` / a deprecated alias). Never a pointer value. */ + /** The mode var's own value (`sqlite` / `postgres` / `postgresql`). Never a pointer value. */ value: string | null; } export interface KnowledgeModeResolution { @@ -45,8 +45,8 @@ export interface KnowledgeModeResolution { * * Precedence: the first mode key that carries a value wins and RETURNS — the * pointer keys are not even read on that path, which is what makes an explicit - * `KNOWLEDGE_MODE=local` authoritative on a machine whose shell exports a URL - * and a key. With no mode key set the answer is `local`, the safe default, + * `KNOWLEDGE_MODE=sqlite` authoritative on a machine whose shell exports a URL + * and a key. With no mode key set the answer is `sqlite`, the safe default, * regardless of what pointers exist. * * Throws only on an unusable mode value (never on pointer state) so a typo in @@ -55,28 +55,12 @@ export interface KnowledgeModeResolution { */ export declare function resolveKnowledgeModeSelection(env?: NodeJS.ProcessEnv): KnowledgeModeResolution; /** - * Server-side tokens, in probe order. The order is load-bearing, and it is - * NEWEST-GENERATION FIRST, THEN CANONICAL BEFORE DEPRECATED: - * - * postgres the current canonical server token - * cloud the previous canonical server token - * self_hosted a DEPRECATED alias of `cloud`, last resort only - * - * Both halves matter. Newest-first is what stops a transitional contracts - * release — one that still honours the old words — from pinning us to the old - * generation. Canonical-before-deprecated is what stops us pinning - * `self_hosted` on the enum where `cloud` is the real answer: both are accepted - * there, but only one is the token this package already injects, and switching - * to the alias would be a live behaviour change dressed up as a refactor. - * - * (Sibling repos list `self_hosted` ahead of `cloud` for exactly the same - * reason inverted — `self_hosted` is the literal THEY replace. The rule is - * "derive what this repo already injects on the installed generation", not - * "copy the other repo's array".) + * Server-side tokens, in probe order. Kept as a small derivation seam so a + * future contracts enum change fails loudly instead of guessing a backend. */ -export declare const SERVER_MODE_CANDIDATES: readonly ['postgres', 'cloud', 'self_hosted']; -/** On-box tokens, same rule: newest generation first. */ -export declare const LOCAL_MODE_CANDIDATES: readonly ['sqlite', 'local']; +export declare const SERVER_MODE_CANDIDATES: readonly ['postgres']; +/** On-box tokens. */ +export declare const LOCAL_MODE_CANDIDATES: readonly ['sqlite']; /** Accepts a mode token or throws. Injectable so both enum generations are testable. */ export type ModeNormalizer = (value: string) => unknown; /** The live-contracts token meaning "the app server". */ @@ -84,56 +68,19 @@ export declare function serverStorageMode(normalize?: ModeNormalizer): string; /** The live-contracts token meaning "the on-box store". */ export declare function localStorageMode(normalize?: ModeNormalizer): string; /** - * Translate OUR semantic mode into the token the INSTALLED @hasna/contracts - * accepts. - * - * THIS FUNCTION IS A TRANSLATION, NOT A PASS-THROUGH, AND THAT IS THE WHOLE - * POINT — do not "simplify" it back. This module holds two independent - * validators, and they are allowed to disagree: - * - * - {@link normalizeVendoredMode}, from the vendored `src/generated/storage-kit`, - * validates what an OPERATOR typed. Its vocabulary is `local | cloud` and - * that is the vocabulary in the docs, the `knowledge mode` report, and the - * env vars people set. {@link KnowledgeMode} is that type. - * - the LIVE `@hasna/contracts` validates the token we hand its resolver. - * After the placement axis was removed it accepts ONLY `sqlite | postgres` - * and THROWS on `local`/`cloud`. - * - * Post-removal those two sets are DISJOINT, which reads at first like an - * impossible constraint: the token that satisfies the type is the token the - * resolver rejects. It is not impossible, because they never had to be the same - * value. {@link KnowledgeMode} types the INTERNAL semantic mode; what reaches - * the resolver is an ENV STRING, and `NodeJS.ProcessEnv` values are - * `string | undefined` — nothing ever forced the stamped token to satisfy the - * vendored type. The two vocabularies meet in exactly one place, here, so - * translating here keeps the vendored kit, the operator vocabulary, and the - * explicit-only no-inference guarantee all untouched. Re-vendoring the kit is - * NOT required to make this forward-compatible. - * - * The tokens are DERIVED by probing the installed `normalizeStorageMode` rather - * than hardcoded, because a literal is a bet on which contracts generation a - * given machine has, and the bet loses on one side or the other. `normalize` is - * injectable because only one generation can be installed at a time, so - * forward-compatibility would otherwise be an assertion rather than a test. - * - * BOUNDARY: the returned token is for the contracts resolver ONLY. Do not feed - * a pinned env back into {@link resolveKnowledgeModeSelection} — that validates - * with the VENDORED normalizer, which will reject the live token once the two - * enums diverge. + * Validate and return the installed-contracts token for a semantic backend. */ export declare function contractsStorageModeFor(mode: KnowledgeMode, normalize?: ModeNormalizer): string; /** * The env to hand @hasna/contracts, with the mode we resolved stamped on top. * * Load-bearing in BOTH directions. Stamping the server token keeps the - * transport from refusing a mode we deliberately chose; stamping the local + * transport from refusing a mode we deliberately chose; stamping the sqlite * token is what stops `resolveClientTransport` from re-deriving the server out * of the ambient pointer vars we just decided to ignore. Handing it the raw * environment instead would put the backend choice back in a second layer. * - * The stamped VALUE is the live-contracts token, not our `KnowledgeMode` — see - * {@link contractsStorageModeFor} for why those are deliberately different - * things. + * The stamped VALUE is the live-contracts token. */ export declare function pinnedTransportEnv(env: NodeJS.ProcessEnv, mode: KnowledgeMode): NodeJS.ProcessEnv; /** @@ -150,7 +97,7 @@ export declare class HalfConfiguredKnowledgeClientError extends Error { * Gate a store-touching command on an UNAMBIGUOUS environment. * * Deliberately separate from {@link resolveKnowledgeModeSelection}, which stays - * total and non-throwing. The resolver has to keep answering `local` in exactly + * total and non-throwing. The resolver has to keep answering `sqlite` in exactly * the environment this rejects, because `knowledge mode` — the command whose * whole job is explaining the situation — resolves through it. A guard fused * into the resolver would kill the diagnostic along with the defect. @@ -160,15 +107,15 @@ export declare class HalfConfiguredKnowledgeClientError extends Error { * fire on machines that could never have routed anywhere, and a check that * cries wolf is a check somebody turns off. * - * `storePathOverridden` (an explicit `--store <path>`) is an explicit local - * choice and passes for the same reason `MODE=local` does: the operator said + * `storePathOverridden` (an explicit `--store <path>`) is an explicit sqlite + * choice and passes for the same reason `MODE=sqlite` does: the operator said * which store they meant. */ export declare function assertKnowledgeModeSelected(env?: NodeJS.ProcessEnv, options?: { storePathOverridden?: boolean; }): KnowledgeModeResolution; export interface KnowledgeModeReport extends KnowledgeModeResolution { - /** `local` -> the on-box store; `api` -> the HTTP `/v1` transport. */ + /** `sqlite` -> the on-box store; `api` -> the HTTP `/v1` transport. */ store_transport: 'local' | 'api'; /** Whether an API key is available at all. Presence only — never the value. */ api_key_present: boolean; diff --git a/dist/sdk.d.ts b/dist/sdk.d.ts index 5631256..1e5cb1e 100644 --- a/dist/sdk.d.ts +++ b/dist/sdk.d.ts @@ -3,9 +3,10 @@ import type { KnowledgeItem } from './store.js'; import type { ItemStore, ItemCreateInput, ItemPatch, ItemListResult } from './item-store.js'; /** * The unified knowledge-item Store surface, mirrored on the SDK so app code - * routes item CRUD through the SAME Store as the CLI and MCP in all three modes - * (local db.json, self_hosted, cloud). No SDK item method touches sqlite or the - * raw HTTP client — the mode is resolved from the environment by the Store. + * routes item CRUD through the SAME Store as the CLI and MCP: sqlite uses the + * local db.json store, postgres uses the HTTP API transport. No SDK item method + * touches sqlite or the raw HTTP client directly — the mode is resolved from + * the environment by the Store. */ export interface KnowledgeItemsSdk { /** The resolved Store for this scope (`kind: 'local' | 'api'`). */ @@ -96,9 +97,9 @@ export interface KnowledgeClient { */ readonly items: KnowledgeItemsSdk; /** - * Inventory of the knowledge corpus. Routes to the shared cloud item corpus in - * api mode (self_hosted/cloud) and the local sqlite/JSON catalog otherwise, so - * the SDK never diverges from the CLI/MCP. Always async. + * Inventory of the knowledge corpus. Routes to the shared API item corpus in + * postgres mode and the local sqlite/JSON catalog otherwise, so the SDK never + * diverges from the CLI/MCP. Always async. */ readonly inventory: (options?: KnowledgeInventoryOptions) => ReturnType<KnowledgeService['resolveInventory']>; readonly db: { diff --git a/dist/serve.js b/dist/serve.js index 7b973c9..24e58fd 100644 --- a/dist/serve.js +++ b/dist/serve.js @@ -21,9 +21,48 @@ import { readFileSync as readFileSync4 } from "fs"; // node_modules/@hasna/contracts/dist/auth/index.js import { createHash, createHmac, randomBytes, timingSafeEqual } from "crypto"; +var MAX_TENANT_ID_LENGTH = 64; +var TENANT_ID_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_TENANT_ID_LENGTH - 1}}$`); +var UUID_HEX = "[0-9a-fA-F]"; +var UUID_PATTERN = new RegExp(`^\\{?(?:${UUID_HEX}{8}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{12}|${UUID_HEX}{32})\\}?$`); +function isValidTenantId(value) { + return typeof value === "string" && TENANT_ID_PATTERN.test(value); +} +function isUuidTenantId(value) { + return typeof value === "string" && UUID_PATTERN.test(value); +} +function canonicalizeTenantId(value) { + if (!isUuidTenantId(value)) + return value; + const hex = value.replace(/[{}-]/g, "").toLowerCase(); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +function normalizeTenantId(value) { + const trimmed = typeof value === "string" ? value.trim() : ""; + const canonical = canonicalizeTenantId(trimmed); + if (!isValidTenantId(canonical)) { + throw new Error(`Invalid tenant id '${value}'. Expected 1-${MAX_TENANT_ID_LENGTH} characters matching ${TENANT_ID_PATTERN} (a UUID, ULID, slug, or prefixed id).`); + } + return canonical; +} +function tenantIdsEqual(left, right) { + const canonical = (value) => { + if (typeof value !== "string") + return null; + const folded = canonicalizeTenantId(value.trim()); + return isValidTenantId(folded) ? folded : null; + }; + const a = canonical(left); + const b = canonical(right); + return a !== null && b !== null && a === b; +} +function ownTenantId(source) { + return Object.hasOwn(source, "tid") ? source.tid : undefined; +} var API_KEY_TOKEN_VERSION = 1; var API_KEY_NAMESPACE = "hasna"; -var TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/; +var API_KEY_TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/; +var TOKEN_PATTERN = API_KEY_TOKEN_PATTERN; var DEFAULT_API_KEY_TTL_SECONDS = 90 * 24 * 60 * 60; function toBuffer(secret) { return typeof secret === "string" ? Buffer.from(secret, "utf8") : secret; @@ -52,6 +91,10 @@ function parseApiKey(token) { if (typeof claims !== "object" || claims === null || typeof claims.kid !== "string" || typeof claims.app !== "string" || !Array.isArray(claims.scopes)) { return null; } + const claimedTid = ownTenantId(claims); + if (claimedTid !== undefined && !isValidTenantId(claimedTid)) { + return null; + } return { app, body, sig, claims }; } function verifyApiKeyToken(token, options) { @@ -87,6 +130,28 @@ function verifyApiKeyToken(token, options) { if (claims.exp !== null && typeof claims.exp === "number" && now - leeway >= claims.exp) { return { ok: false, reason: "expired", message: "Token has expired." }; } + const verifiedTid = ownTenantId(claims); + const tid = verifiedTid === undefined ? null : canonicalizeTenantId(verifiedTid); + const tenantRequired = Boolean(options.requireTenant) || options.expectedTid !== undefined; + if (tenantRequired && tid === null) { + return { + ok: false, + reason: "tenant_required", + message: "Token carries no tenant id ('tid') and this service requires one.", + kid: claims.kid, + tid: null + }; + } + if (options.expectedTid !== undefined && !tenantIdsEqual(tid, options.expectedTid)) { + const expectationIsWellFormed = typeof options.expectedTid === "string" && isValidTenantId(options.expectedTid.trim()); + return { + ok: false, + reason: "tenant_mismatch", + message: expectationIsWellFormed ? "Token is for a different tenant than the one this service accepts." : "Token tenant cannot be checked: the expected tenant id is not a valid tenant id.", + kid: claims.kid, + tid + }; + } if (options.requiredScopes && options.requiredScopes.length > 0) { const granted = claims.scopes; const satisfies = (required) => granted.some((g) => { @@ -108,7 +173,7 @@ function verifyApiKeyToken(token, options) { } } } - return { ok: true, claims, kid: claims.kid, app }; + return { ok: true, claims, kid: claims.kid, app, tid }; } var DEFAULT_API_KEYS_TABLE = "api_keys"; function createTableSql(table) { @@ -134,6 +199,11 @@ function apiKeyMigrations(table = DEFAULT_API_KEYS_TABLE) { id: `hasna_auth_0002_${table}_indexes`, sql: `CREATE INDEX IF NOT EXISTS ${table}_app_idx ON ${table} (app); CREATE INDEX IF NOT EXISTS ${table}_token_hash_idx ON ${table} (token_hash);` + }, + { + id: `hasna_auth_0003_${table}_tenant`, + sql: `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS tid TEXT; + CREATE INDEX IF NOT EXISTS ${table}_tid_idx ON ${table} (tid);` } ]; } @@ -158,10 +228,12 @@ function parseScopes(value) { return []; } function rowToRecord(row) { + const tid = ownTenantId(row); return { kid: String(row.kid), app: String(row.app), agent: row.agent === null || row.agent === undefined ? null : String(row.agent), + tid: tid === null || tid === undefined ? null : String(tid), scopes: parseScopes(row.scopes), tokenHash: String(row.token_hash), issuedAt: toIso(row.issued_at) ?? new Date(0).toISOString(), @@ -192,12 +264,14 @@ class ApiKeyStore { } } async insert(input) { + const tid = ownTenantId(input); await this.client.execute(`INSERT INTO ${this.table} - (kid, app, agent, scopes, token_hash, issued_at, expires_at, created_by) - VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)`, [ + (kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, created_by) + VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9)`, [ input.kid, input.app, input.agent ?? null, + tid === undefined || tid === null ? null : normalizeTenantId(tid), JSON.stringify(input.scopes), input.tokenHash, input.issuedAt.toISOString(), @@ -211,6 +285,7 @@ class ApiKeyStore { kid: minted.kid, app: claims.app, agent: claims.agent ?? null, + tid: ownTenantId(claims) ?? null, scopes: claims.scopes, tokenHash: minted.tokenHash, issuedAt: new Date(claims.iat * 1000), @@ -268,11 +343,16 @@ class ApiKeyStore { params.push(options.app); clauses.push(`app = $${params.length}`); } + const tid = ownTenantId(options); + if (tid !== undefined) { + params.push(normalizeTenantId(tid)); + clauses.push(`tid = $${params.length}`); + } if (!options.includeRevoked) { clauses.push("revoked_at IS NULL"); } const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""; - const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`); + const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`, params); return rows.map(rowToRecord); } async revokedKids() { @@ -315,6 +395,9 @@ function verifyApiKey(options) { if (!options.signingSecret) { throw new Error("verifyApiKey requires a 'signingSecret'. Set it from HASNA_<APP>_API_SIGNING_KEY."); } + if (options.expectedTid !== undefined && !isValidTenantId(options.expectedTid)) { + throw new Error(`verifyApiKey received an invalid 'expectedTid': '${options.expectedTid}'.`); + } const headerName = options.headerName ?? "x-api-key"; const scheme = options.scheme ?? "Bearer"; const clock = options.nowMs ?? (() => Date.now()); @@ -330,6 +413,17 @@ function verifyApiKey(options) { const path = context.path ?? null; const requiredScopes = [...options.requiredScopes ?? [], ...context.requiredScopes ?? []]; const at = new Date(clock()).toISOString(); + const perCallTid = Object.hasOwn(context, "expectedTid") ? context.expectedTid : undefined; + const expectedTid = perCallTid !== undefined ? perCallTid : options.expectedTid; + if (perCallTid !== undefined && options.expectedTid !== undefined && !tenantIdsEqual(perCallTid, options.expectedTid)) { + await emit({ outcome: "deny", app: options.app, kid: null, tid: null, reason: "tenant_mismatch", scopesRequired: requiredScopes, method, path, status: 403, at }); + return { + ok: false, + status: 403, + reason: "tenant_mismatch", + message: "This route addresses a tenant other than the one this service is pinned to." + }; + } const token = extractToken(headers, headerName, scheme); if (!token) { const decision = { @@ -338,7 +432,7 @@ function verifyApiKey(options) { reason: "missing_token", message: `Missing API key. Send it as '${headerName}: <key>' or 'Authorization: ${scheme} <key>'.` }; - await emit({ outcome: "deny", app: options.app, kid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at }); + await emit({ outcome: "deny", app: options.app, kid: null, tid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at }); return decision; } const verified = verifyApiKeyToken(token, { @@ -346,17 +440,19 @@ function verifyApiKey(options) { expectedApp: options.app, nowMs: clock(), ...options.leewaySeconds !== undefined ? { leewaySeconds: options.leewaySeconds } : {}, + ...options.requireTenant !== undefined ? { requireTenant: options.requireTenant } : {}, + ...expectedTid !== undefined ? { expectedTid } : {}, requiredScopes }); if (!verified.ok) { - const status = verified.reason === "insufficient_scope" ? 403 : 401; - await emit({ outcome: "deny", app: options.app, kid: null, reason: verified.reason, scopesRequired: requiredScopes, method, path, status, at }); + const status = verified.reason === "insufficient_scope" || verified.reason === "tenant_mismatch" || verified.reason === "tenant_required" ? 403 : 401; + await emit({ outcome: "deny", app: options.app, kid: verified.kid ?? null, tid: ownTenantId(verified) ?? null, reason: verified.reason, scopesRequired: requiredScopes, method, path, status, at }); return { ok: false, status, reason: verified.reason, message: verified.message }; } if (options.isRevoked) { const revoked = await options.isRevoked(verified.kid); if (revoked) { - await emit({ outcome: "deny", app: options.app, kid: verified.kid, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at }); + await emit({ outcome: "deny", app: options.app, kid: verified.kid, tid: verified.tid, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at }); return { ok: false, status: 401, reason: "revoked", message: "API key has been revoked." }; } } @@ -365,30 +461,24 @@ function verifyApiKey(options) { app: verified.app, scopes: verified.claims.scopes, agent: verified.claims.agent ?? null, + tid: verified.tid, claims: verified.claims }; - await emit({ outcome: "allow", app: options.app, kid: verified.kid, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at }); + await emit({ outcome: "allow", app: options.app, kid: verified.kid, tid: verified.tid, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at }); return { ok: true, status: 200, principal }; } return { authenticate, app: options.app }; } +var MAX_FLEET_TOKEN_TTL_SECONDS = 24 * 60 * 60; // src/generated/storage-kit/mode.ts -var DEPRECATED_STORAGE_MODE_ALIASES = [ - "remote", - "hybrid", - "self_hosted" -]; function normalizeStorageMode(value) { const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); } function envToken(name) { return name.toUpperCase().replace(/-/g, "_"); @@ -416,21 +506,17 @@ function resolveStorageMode(name, env = process.env) { const modeHit = firstEnv(env, modeKeys); if (!modeHit) { return { - mode: "local", - source: "default", - deprecatedAlias: null, + mode: databaseUrlPresent ? "postgres" : "sqlite", + source: databaseUrlPresent ? databaseUrlSource : "default", databaseUrlPresent, databaseUrlSource, warning: null }; } - const { mode, deprecatedAlias } = normalizeStorageMode(modeHit.value); + const { mode } = normalizeStorageMode(modeHit.value); const warnings = []; - if (deprecatedAlias) { - warnings.push(`Deprecated storage mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Set ${modeKeys[0]}=cloud instead.`); - } - if (mode === "cloud" && !databaseUrlPresent) { - warnings.push(`cloud mode needs ${databaseUrlKeys[0]} (PURE REMOTE: reads and writes go to cloud Postgres).`); + if (mode === "postgres" && !databaseUrlPresent) { + warnings.push(`postgres storage needs ${databaseUrlKeys[0]} (reads and writes go to PostgreSQL).`); } if (modeHit.key !== modeKeys[0]) { warnings.push(`Using alias env ${modeHit.key}; the canonical key is ${modeKeys[0]}.`); @@ -438,7 +524,6 @@ function resolveStorageMode(name, env = process.env) { return { mode, source: modeHit.key, - deprecatedAlias, databaseUrlPresent, databaseUrlSource, warning: warnings.length > 0 ? warnings.join(" ") : null @@ -485,11 +570,11 @@ function loadCaBundle(options) { } function resolveTlsConfig(connectionString, options = {}) { const mode = sslModeFromConnectionString(connectionString); - if (mode === "disable") { + if (mode === "disable" || mode === "prefer") { return; } const ca = loadCaBundle(options); - if (mode === "prefer" || mode === "require") { + if (mode === "require") { return ca ? { rejectUnauthorized: false, ca } : { rejectUnauthorized: false }; } if (!ca) { @@ -571,15 +656,15 @@ function createPgPool(options) { config.application_name = options.applicationName; return new pg.Pool(config); } -function createCloudPoolFromEnv(appName, options = {}) { +function createServerPoolFromEnv(appName, options = {}) { const env = options.env ?? process.env; const resolution = resolveStorageMode(appName, env); - if (resolution.mode !== "cloud") { - throw new Error(`createCloudPoolFromEnv requires ${appName} storage mode 'cloud', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=cloud.`); + if (resolution.mode !== "postgres") { + throw new Error(`createServerPoolFromEnv requires ${appName} storage mode 'postgres', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=postgres.`); } const connectionString = resolveDatabaseUrl(appName, env); if (!connectionString) { - throw new Error(`cloud mode for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); + throw new Error(`postgres storage for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); } const pool = createPgPool({ connectionString, @@ -607,9 +692,6 @@ function checksumSql(sql) { function defineMigration(id, sql) { return Object.freeze({ id, sql: sql.trim(), checksum: checksumSql(sql) }); } -function hasTransaction(client) { - return typeof client.transaction === "function"; -} class MigrationLedger { client; @@ -674,30 +756,11 @@ class MigrationLedger { for (const item of plan) { if (item.state === "already_applied") continue; - await this.applyPendingMigration(item.migration); + await this.client.execute(item.migration.sql); + await this.client.execute(`INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, [item.migration.id, item.migration.checksum]); } return { dryRun, applied: await this.readApplied(), plan }; } - async applyPendingMigration(migration) { - const apply = async (client) => { - await client.execute(migration.sql); - await client.execute(`INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, [migration.id, migration.checksum]); - }; - if (hasTransaction(this.client)) { - await this.client.transaction(apply); - return; - } - await this.client.execute("BEGIN"); - try { - await apply(this.client); - await this.client.execute("COMMIT"); - } catch (error) { - try { - await this.client.execute("ROLLBACK"); - } catch {} - throw error; - } - } } function createMigrationLedger(client, migrations, options = {}) { return new MigrationLedger(client, migrations, options); @@ -734,12 +797,12 @@ async function checkReady(client, migrations, options = {}) { } // src/generated/storage-kit/index.ts -var KIT_VERSION = "0.4.0"; +var KIT_VERSION = "0.8.5"; // src/db/remote-storage.ts var KNOWLEDGE_APP_NAME = "knowledge"; function createKnowledgeCloudClient() { - return createCloudPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; + return createServerPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; } // src/registry-contract.ts @@ -1836,7 +1899,7 @@ function parseExpectedVersion(req, body) { } function createServeHandler(deps) { const repo = new NoteRepo(deps.client); - const mode2 = "cloud"; + const mode2 = "postgres"; const authOrThrow = async (req, requiredScopes) => { const url = new URL(req.url); const decision = await deps.verifier.authenticate(req.headers, { @@ -1987,7 +2050,7 @@ async function startKnowledgeServe(options = {}) { throw new Error("knowledge-serve requires the Bun runtime (Bun.serve unavailable)."); } const server = BunGlobal.serve({ port, hostname, fetch: handler }); - console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=cloud, version=${version})`); + console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=postgres, version=${version})`); return { port: server.port, hostname, diff --git a/dist/service.d.ts b/dist/service.d.ts index faa230b..8f07559 100644 --- a/dist/service.d.ts +++ b/dist/service.d.ts @@ -366,8 +366,8 @@ export declare class KnowledgeService { /** * The single knowledge-item Store for this scope. One interface, two * transports resolved from the environment: LocalItemStore (on-box db.json) - * in local mode, ApiItemStore (HTTP `/v1` + bearer key) in self_hosted/cloud - * mode. EVERY item read/write — CLI, MCP, and SDK — routes through this one + * in sqlite mode, ApiItemStore (HTTP `/v1` + bearer key) in postgres mode. + * EVERY item read/write — CLI, MCP, and SDK — routes through this one * surface, so no path touches sqlite or the raw HTTP client directly. */ itemStore(): ItemStore; @@ -384,8 +384,8 @@ export declare class KnowledgeService { /** Delete many items by id/short id via the unified Store; returns the count. */ deleteItems(idsOrShorts: string[]): Promise<number>; /** - * Unified inventory dispatch: the shared cloud knowledge-item corpus in api - * mode (self_hosted/cloud), the local sqlite/JSON catalog otherwise. CLI, MCP, + * Unified inventory dispatch: the shared API knowledge-item corpus in + * postgres mode, the local sqlite/JSON catalog otherwise. CLI, MCP, * and SDK all call this so no surface reads a divergent store. */ resolveInventory(options?: KnowledgeInventoryOptions): Promise<KnowledgeInventoryResult>; diff --git a/dist/storage.d.ts b/dist/storage.d.ts index 20e8a08..acf72e3 100644 --- a/dist/storage.d.ts +++ b/dist/storage.d.ts @@ -2,5 +2,5 @@ export { KNOWLEDGE_STORAGE_MODE_ENV, KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV, KNOWLE export type { StorageMode, StorageStatus, StorageStatusOptions, StorageSyncOptions, SyncMeta, SyncResult, } from './db/storage-sync.js'; export { createKnowledgeCloudClient, KNOWLEDGE_APP_NAME } from './db/remote-storage.js'; export { PG_MIGRATIONS } from './db/pg-migrations.js'; -export { KIT_VERSION, resolveStorageMode, resolveDatabaseUrl, resolveTlsConfig, normalizeStorageMode as normalizeCloudStorageMode, storageEnvKeys, MigrationLedger, createMigrationLedger, defineMigration, checksumSql, wrapExecutor, checkHealth, checkReady, } from './generated/storage-kit/index.js'; +export { KIT_VERSION, resolveStorageMode, resolveDatabaseUrl, resolveTlsConfig, normalizeStorageMode, normalizeStorageMode as normalizeCloudStorageMode, storageEnvKeys, MigrationLedger, createMigrationLedger, defineMigration, checksumSql, wrapExecutor, checkHealth, checkReady, } from './generated/storage-kit/index.js'; export type { PoolQueryClient, TypedQueryClient, PgExecutor, Migration, MigrationResult, StorageModeResolution, } from './generated/storage-kit/index.js'; diff --git a/dist/storage.js b/dist/storage.js index 9c1362d..dff18a6 100644 --- a/dist/storage.js +++ b/dist/storage.js @@ -199,18469 +199,945 @@ function writeKnowledgeConfig(path, config) { } // node_modules/@hasna/contracts/dist/client/storage.js -var __defProp2 = Object.defineProperty; -var __returnValue2 = (v) => v; -function __exportSetter2(name, newValue) { - this[name] = __returnValue2.bind(null, newValue); +import { isIP } from "net"; +import { readFileSync as readFileSync2, statSync } from "fs"; +import { join as join2 } from "path"; +function envToken(name) { + return name.toUpperCase().replace(/-/g, "_"); } -var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter2.bind(all, name) - }); -}; -var exports_external = {}; -__export2(exports_external, { - void: () => voidType, - util: () => util, - unknown: () => unknownType, - union: () => unionType, - undefined: () => undefinedType, - tuple: () => tupleType, - transformer: () => effectsType, - symbol: () => symbolType, - string: () => stringType, - strictObject: () => strictObjectType, - setErrorMap: () => setErrorMap, - set: () => setType, - record: () => recordType, - quotelessJson: () => quotelessJson, - promise: () => promiseType, - preprocess: () => preprocessType, - pipeline: () => pipelineType, - ostring: () => ostring, - optional: () => optionalType, - onumber: () => onumber, - oboolean: () => oboolean, - objectUtil: () => objectUtil, - object: () => objectType, - number: () => numberType, - nullable: () => nullableType, - null: () => nullType, - never: () => neverType, - nativeEnum: () => nativeEnumType, - nan: () => nanType, - map: () => mapType, - makeIssue: () => makeIssue, - literal: () => literalType, - lazy: () => lazyType, - late: () => late, - isValid: () => isValid, - isDirty: () => isDirty, - isAsync: () => isAsync, - isAborted: () => isAborted, - intersection: () => intersectionType, - instanceof: () => instanceOfType, - getParsedType: () => getParsedType, - getErrorMap: () => getErrorMap, - function: () => functionType, - enum: () => enumType, - effect: () => effectsType, - discriminatedUnion: () => discriminatedUnionType, - defaultErrorMap: () => en_default, - datetimeRegex: () => datetimeRegex, - date: () => dateType, - custom: () => custom, - coerce: () => coerce, - boolean: () => booleanType, - bigint: () => bigIntType, - array: () => arrayType, - any: () => anyType, - addIssueToContext: () => addIssueToContext, - ZodVoid: () => ZodVoid, - ZodUnknown: () => ZodUnknown, - ZodUnion: () => ZodUnion, - ZodUndefined: () => ZodUndefined, - ZodType: () => ZodType, - ZodTuple: () => ZodTuple, - ZodTransformer: () => ZodEffects, - ZodSymbol: () => ZodSymbol, - ZodString: () => ZodString, - ZodSet: () => ZodSet, - ZodSchema: () => ZodType, - ZodRecord: () => ZodRecord, - ZodReadonly: () => ZodReadonly, - ZodPromise: () => ZodPromise, - ZodPipeline: () => ZodPipeline, - ZodParsedType: () => ZodParsedType, - ZodOptional: () => ZodOptional, - ZodObject: () => ZodObject, - ZodNumber: () => ZodNumber, - ZodNullable: () => ZodNullable, - ZodNull: () => ZodNull, - ZodNever: () => ZodNever, - ZodNativeEnum: () => ZodNativeEnum, - ZodNaN: () => ZodNaN, - ZodMap: () => ZodMap, - ZodLiteral: () => ZodLiteral, - ZodLazy: () => ZodLazy, - ZodIssueCode: () => ZodIssueCode, - ZodIntersection: () => ZodIntersection, - ZodFunction: () => ZodFunction, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodError: () => ZodError, - ZodEnum: () => ZodEnum, - ZodEffects: () => ZodEffects, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodDefault: () => ZodDefault, - ZodDate: () => ZodDate, - ZodCatch: () => ZodCatch, - ZodBranded: () => ZodBranded, - ZodBoolean: () => ZodBoolean, - ZodBigInt: () => ZodBigInt, - ZodArray: () => ZodArray, - ZodAny: () => ZodAny, - Schema: () => ZodType, - ParseStatus: () => ParseStatus, - OK: () => OK, - NEVER: () => NEVER, - INVALID: () => INVALID, - EMPTY_PATH: () => EMPTY_PATH, - DIRTY: () => DIRTY, - BRAND: () => BRAND -}); -var util; -(function(util2) { - util2.assertEqual = (_) => {}; - function assertIs(_arg) {} - util2.assertIs = assertIs; - function assertNever(_x) { - throw new Error; - } - util2.assertNever = assertNever; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util2.joinValues = joinValues; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; +function normalizeStorageMode(value) { + const normalized = value.trim().toLowerCase().replace(/-/g, "_"); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); +} +function clientTransportEnvKeys(name) { + const envSegment = envToken(name); + return { + modeKeys: [ + `HASNA_${envSegment}_STORAGE_MODE`, + `HASNA_${envSegment}_MODE`, + `${envSegment}_STORAGE_MODE`, + `${envSegment}_MODE` + ], + apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], + apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; -var ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; +} +function credentialOverrideEnvKey(name) { + return `HASNA_${envToken(name)}_API_KEY_OVERRIDE`; +} +var CREDENTIAL_PROFILE_ENV_KEY = "HASNA_PROFILE"; -class ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; +class CredentialResolutionError extends Error { + appName; + attempted; + constructor(appName, message, attempted) { + super(message); + this.name = "CredentialResolutionError"; + this.appName = appName; + this.attempted = attempted; + } +} +var HASNA_STATE_DIR = ".hasna"; +var FLEET_CREDENTIAL_DIR = "cloud"; +var CONFIG_DIR = ".config"; +var CONFIG_NAMESPACE = "hasna"; +var MAX_CREDENTIAL_FILE_BYTES = 64 * 1024; +var SAFE_APP_SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/; +var SAFE_PROFILE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/; +var ILLEGAL_IN_HEADER_VALUE = /[^\t\x20-\x7e]/; +function homeDir(env) { + const home = env.HOME?.trim(); + return home ? home : null; +} +function credentialDiskSources(name, env) { + return profileDiskSources(name, env, null); +} +function profileDiskSources(name, env, profile) { + const home = homeDir(env); + if (!home || !SAFE_APP_SLUG.test(name)) + return []; + const stem = profile ? `${name}.${profile}` : name; + const configStem = profile ? `${name}-${profile}` : name; + return [ + join2(home, HASNA_STATE_DIR, FLEET_CREDENTIAL_DIR, `${stem}.env`), + join2(home, CONFIG_DIR, CONFIG_NAMESPACE, `${configStem}-cloud.env`) + ]; +} +function parseEnvFile(text) { + const values = new Map; + for (const rawLine of text.split(/\r?\n/)) { + const line = rawLine.trim(); + if (line.length === 0 || line.startsWith("#")) + continue; + const withoutExport = line.startsWith("export ") ? line.slice("export ".length).trim() : line; + const equals = withoutExport.indexOf("="); + if (equals <= 0) + continue; + const key = withoutExport.slice(0, equals).trim(); + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) + continue; + let value = withoutExport.slice(equals + 1).trim(); + const quote = value[0]; + if (quote === '"' || quote === "'") { + if (value.length < 2 || !value.endsWith(quote)) + continue; + value = value.slice(1, -1); } - this.name = "ZodError"; - this.issues = issues; + if (value.length === 0) + continue; + values.set(key, value); } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; + return values; +} +function readCredentialFile(path, apiKeyKeys) { + let text; + try { + const stats = statSync(path); + if (!stats.isFile() || stats.size > MAX_CREDENTIAL_FILE_BYTES) + return null; + text = readFileSync2(path, "utf8"); + } catch { + return null; } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } + const values = parseEnvFile(text); + for (const key of apiKeyKeys) { + const value = values.get(key)?.trim(); + if (value) + return value; } - toString() { - return this.message; + return null; +} +function assertUsableCredential(appName, source, value) { + if (!ILLEGAL_IN_HEADER_VALUE.test(value)) + return; + throw new CredentialResolutionError(appName, `The credential from ${source} contains characters that cannot be sent in an HTTP header ` + `(a control character or non-ASCII byte). A file written with CR-only line endings is the usual ` + `cause. Rewrite that credential file with one LF-terminated KEY=value line. ` + `The value is not shown here, and is deliberately never logged.`, [source]); +} +var INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom"); +function sealCredential(fields) { + const { apiKey, ...visible } = fields; + const sealed = { ...visible }; + Object.defineProperty(sealed, "apiKey", { + value: apiKey, + enumerable: false, + writable: false, + configurable: false + }); + Object.defineProperty(sealed, INSPECT_CUSTOM, { + value: () => ({ ...visible, apiKey: "[redacted]" }), + enumerable: false, + writable: false, + configurable: false + }); + return sealed; +} +function explicitCredential(appName, apiKey) { + const source = "explicit apiKey option"; + assertUsableCredential(appName, source, apiKey); + return sealCredential({ + apiKey, + tier: "argument", + source, + deliberate: true, + deprecated: false, + diskCandidates: [], + warning: null + }); +} +function firstEnvValue(env, keys) { + for (const key of keys) { + const value = env[key]?.trim(); + if (value) + return { key, value }; } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + return null; +} +var DEPRECATION_REGISTRY = Symbol.for("hasna:contracts:credentialDeprecationNotices"); +function deprecationNotified() { + const host = globalThis; + const existing = host[DEPRECATION_REGISTRY]; + if (existing instanceof Set) + return existing; + const created = new Set; + host[DEPRECATION_REGISTRY] = created; + return created; +} +function defaultDeprecationSink(message) { + if (typeof process !== "undefined" && process.stderr) { + process.stderr.write(`${message} +`); } - get isEmpty() { - return this.issues.length === 0; +} +function resolveCredential(name, env, options = {}) { + const { apiKeyKeys } = clientTransportEnvKeys(name); + const diskPaths = credentialDiskSources(name, env); + const explicitKey = options.apiKey?.trim(); + if (explicitKey) { + assertUsableCredential(name, "the explicit apiKey argument", explicitKey); + return sealCredential({ + apiKey: explicitKey, + tier: "argument", + source: "explicit apiKey argument", + deliberate: true, + deprecated: false, + diskCandidates: diskPaths, + warning: null + }); } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; + const overrideKeyName = credentialOverrideEnvKey(name); + const overrideRaw = env[overrideKeyName]; + if (overrideRaw !== undefined) { + const override = overrideRaw.trim(); + if (!override) { + throw new CredentialResolutionError(name, `${overrideKeyName} is set but empty. It is a deliberate override, so it is not resolved around: ` + `either give it a real key or unset it to fall back to the credential on disk.`, [overrideKeyName]); + } + assertUsableCredential(name, overrideKeyName, override); + return sealCredential({ + apiKey: override, + tier: "override", + source: overrideKeyName, + deliberate: true, + deprecated: false, + diskCandidates: diskPaths, + warning: null + }); } - get formErrors() { - return this.flatten(); + const profile = options.profile?.trim() || env[CREDENTIAL_PROFILE_ENV_KEY]?.trim(); + if (profile) { + const profileSource = options.profile?.trim() ? "explicit profile argument" : CREDENTIAL_PROFILE_ENV_KEY; + if (!SAFE_PROFILE.test(profile)) { + throw new CredentialResolutionError(name, `Profile name from ${profileSource} is not usable in a path. ` + `Use letters, digits, dot, dash, or underscore.`, [profileSource]); + } + const paths = profileDiskSources(name, env, profile); + for (const path of paths) { + const value = readCredentialFile(path, apiKeyKeys); + if (value) { + assertUsableCredential(name, path, value); + return sealCredential({ + apiKey: value, + tier: "profile", + source: path, + deliberate: true, + deprecated: false, + diskCandidates: paths, + warning: null + }); + } + } + throw new CredentialResolutionError(name, `Profile '${profile}' (from ${profileSource}) has no ${apiKeyKeys[0]} for '${name}'. ` + `Looked in: ${paths.join(", ") || "<no HOME in this environment>"}. ` + `A profile names WHICH identity to use, so it is never resolved around \u2014 ` + `create the profile's credential file or unset ${CREDENTIAL_PROFILE_ENV_KEY}.`, paths); + } + const diskHits = diskPaths.map((path) => ({ path, value: readCredentialFile(path, apiKeyKeys) })).filter((hit) => hit.value !== null); + if (diskHits.length > 0) { + const winner = diskHits[0]; + assertUsableCredential(name, winner.path, winner.value); + const divergentSources = [ + ...diskHits.slice(1).filter((hit) => hit.value !== winner.value).map((hit) => hit.path), + ...(() => { + const legacyHit = firstEnvValue(env, apiKeyKeys); + return legacyHit && legacyHit.value !== winner.value ? [legacyHit.key] : []; + })() + ]; + const warning = divergentSources.length > 0 ? `Credential sources disagree for '${name}': ${winner.path} and ` + `${divergentSources.join(", ")} hold different keys. ${winner.path} wins, because a file on ` + `disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 ` + `a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.` : null; + return sealCredential({ + apiKey: winner.value, + tier: "disk", + source: winner.path, + deliberate: false, + deprecated: false, + diskCandidates: diskPaths, + warning + }); + } + const legacy = firstEnvValue(env, apiKeyKeys); + if (legacy) { + assertUsableCredential(name, legacy.key, legacy.value); + const where = diskPaths.length > 0 ? `Put the current key in ${diskPaths[0]} \u2014 it is re-read on every call, so rotations take effect immediately.` : `This environment has no HOME, so no credential file could be consulted at all; the disk tier is ` + `unavailable here and this process will keep using the environment snapshot.`; + const message = `[${name}] DEPRECATED: the API key came from ${legacy.key} in this process's environment. ` + `Environment variables are a snapshot taken when this process started, so a shell that started ` + `before a key rotation keeps using the old key until it exits. ${where}`; + const sink = options.onDeprecation ?? defaultDeprecationSink; + const notified = deprecationNotified(); + if (!notified.has(name)) { + notified.add(name); + sink(message); + } + return sealCredential({ + apiKey: legacy.value, + tier: "legacy-env", + source: legacy.key, + deliberate: false, + deprecated: true, + diskCandidates: diskPaths, + warning: message + }); } + return null; } -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); +var FLEET_API_DOMAIN_ENV_KEY = "HASNA_FLEET_API_DOMAIN"; +var NEUTRAL_FLEET_API_DOMAIN = "your-deployment.example"; +var ASCII_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/; +var DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/; +function isValidDnsDomain(value) { + if (value.length === 0 || value.length > 253 || ASCII_CONTROL_PATTERN.test(value) || /[^\x00-\x7f]/.test(value)) { + return false; } - return { message }; -}; -var en_default = errorMap; -var overrideErrorMap = en_default; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; + return value.split(".").every((label) => label.length <= 63 && !label.startsWith("xn--") && DNS_LABEL_PATTERN.test(label)); } -var makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { +function resolveFleetApiDomain(env) { + const raw = env[FLEET_API_DOMAIN_ENV_KEY]; + if (raw === undefined) { return { - ...issueData, - path: fullPath, - message: issueData.message + domain: NEUTRAL_FLEET_API_DOMAIN, + source: "default", + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} is not set; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` }; } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + const configured = raw.trim().toLowerCase(); + if (ASCII_CONTROL_PATTERN.test(raw) || !isValidDnsDomain(configured)) { + return { + domain: NEUTRAL_FLEET_API_DOMAIN, + source: FLEET_API_DOMAIN_ENV_KEY, + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} is blank or invalid; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` + }; } return { - ...issueData, - path: fullPath, - message: errorMessage + domain: configured, + source: FLEET_API_DOMAIN_ENV_KEY, + misconfigured: false, + warning: null }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default ? undefined : en_default - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); } - -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; +function validateAppSlug(name) { + if (name.length > 63 || !DNS_LABEL_PATTERN.test(name)) { + throw new Error("App name must be one lowercase DNS label."); } + return name; } -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x) => x.status === "aborted"; -var isDirty = (x) => x.status === "dirty"; -var isValid = (x) => x.status === "valid"; -var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; +function composeCloudHostname(name, domain) { + const hostname = `${validateAppSlug(name)}.${domain}`; + if (!isValidDnsDomain(hostname)) { + throw new Error("Composed cloud hostname must be a valid DNS domain"); } + return hostname; } -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } +function resolveDefaultCloudBaseUrl(name, env) { + const appSlug = validateAppSlug(name); + const fleetDomain = resolveFleetApiDomain(env); + const configuredHostname = `${appSlug}.${fleetDomain.domain}`; + if (isValidDnsDomain(configuredHostname)) { return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } + baseUrl: `https://${configuredHostname}`, + source: fleetDomain.source, + misconfigured: fleetDomain.misconfigured, + warning: fleetDomain.warning }; } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; + const fallbackHostname = composeCloudHostname(appSlug, NEUTRAL_FLEET_API_DOMAIN); + return { + baseUrl: `https://${fallbackHostname}`, + source: fleetDomain.source, + misconfigured: true, + warning: `${FLEET_API_DOMAIN_ENV_KEY} cannot form a valid composed cloud hostname for app '${appSlug}'; using the non-resolving ${NEUTRAL_FLEET_API_DOMAIN} fallback.` }; - return { errorMap: customMap, description }; } - -class ZodType { - get description() { - return this._def.description; +function firstEnv2(env, keys, options = {}) { + for (const key of keys) { + const raw = env[key]; + const value = raw?.trim(); + if (value) + return { key, value: options.preserveRaw ? raw : value }; } - _getType(input) { - return getParsedType(input.data); + return null; +} +function rawAuthority(value) { + const match = /^[a-z][a-z0-9+.-]*:\/\//i.exec(value); + if (!match) + throw new Error("API URL must be absolute."); + const afterScheme = value.slice(match[0].length); + const boundary = afterScheme.search(/[/?#]/); + const authority = boundary === -1 ? afterScheme : afterScheme.slice(0, boundary); + if (!authority) + throw new Error("API URL must include a hostname."); + return authority; +} +function assertCanonicalPort(port) { + if (!/^[0-9]+$/.test(port) || port.length > 1 && port.startsWith("0")) { + throw new Error("API URL authority must contain a canonical port between 1 and 65535."); } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; + const numericPort = Number(port); + if (!Number.isSafeInteger(numericPort) || numericPort < 1 || numericPort > 65535) { + throw new Error("API URL authority must contain a canonical port between 1 and 65535."); } - _processInputParams(input) { - return { - status: new ParseStatus, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent +} +function canonicalAuthorityHostname(authority) { + let rawHostname; + if (authority.startsWith("[")) { + const closingBracket = authority.indexOf("]"); + if (closingBracket === -1) { + throw new Error("API URL authority must contain a canonical hostname."); + } + rawHostname = authority.slice(0, closingBracket + 1); + const portSuffix = authority.slice(closingBracket + 1); + if (portSuffix) { + if (!portSuffix.startsWith(":")) { + throw new Error("API URL authority must contain a canonical hostname and port."); } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); + assertCanonicalPort(portSuffix.slice(1)); + } + if (isIP(rawHostname.slice(1, -1)) !== 6) { + throw new Error("API URL authority must contain a canonical IPv6 literal."); + } + } else { + const firstColon = authority.indexOf(":"); + const lastColon = authority.lastIndexOf(":"); + if (firstColon !== lastColon) { + throw new Error("IPv6 API URL authorities must use brackets."); + } + if (lastColon !== -1) { + const port = authority.slice(lastColon + 1); + assertCanonicalPort(port); + rawHostname = authority.slice(0, lastColon); + } else { + rawHostname = authority; + } + const ipVersion = isIP(rawHostname); + const numericAddressParts = rawHostname.split("."); + const looksLikeNonCanonicalIpv4 = numericAddressParts.every((part) => /^(?:0x[0-9a-f]+|[0-9]+)$/i.test(part)); + if (ipVersion !== 4 && looksLikeNonCanonicalIpv4 || ipVersion !== 4 && !isValidDnsDomain(rawHostname.toLowerCase())) { + throw new Error("API URL authority must contain a canonical ASCII hostname."); } - return result; } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); + return rawHostname.toLowerCase(); +} +function isDeliberateLoopbackHttpAuthority(authority) { + return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(authority); +} +function toV1BaseUrl(apiUrl) { + if (ASCII_CONTROL_PATTERN.test(apiUrl)) { + throw new Error("API URL must not contain ASCII control characters."); } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; + const input = apiUrl.trim(); + const authority = rawAuthority(input); + if (authority.includes("@") || authority.includes("\\") || authority.includes("%") || /[^\x00-\x7f]/.test(authority)) { + throw new Error("API URL authority must be canonical ASCII without credentials."); } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); + const canonicalHostname = canonicalAuthorityHostname(authority); + const url = new URL(input); + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("API URL must use http or https."); } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); + if (url.username || url.password) { + throw new Error("API URL must not include credentials."); } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; + if (!url.hostname || url.hostname.endsWith(".")) { + throw new Error("API URL must include a canonical hostname."); } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); + if (url.hostname.toLowerCase() !== canonicalHostname) { + throw new Error("API URL authority must not rely on parser hostname normalization."); } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); + if (url.hostname.split(".").some((label) => label.toLowerCase().startsWith("xn--"))) { + throw new Error("API URL must not use IDN or punycode hostnames."); } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); + if (url.protocol === "http:" && !isDeliberateLoopbackHttpAuthority(authority)) { + throw new Error("API URL may use http only for an exact loopback authority."); } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); + if (url.search || url.hash) { + throw new Error("API URL must not include a query string or fragment."); } - superRefine(refinement) { - return this._refinement(refinement); + let path = url.pathname.replace(/\/+$/, ""); + if (path.endsWith("/v1")) + path = path.slice(0, -"/v1".length); + url.pathname = `${path}/v1`; + return url.toString().replace(/\/+$/, ""); +} +function resolveClientTransport(name, env = process.env, options = {}) { + const keys = clientTransportEnvKeys(name); + const modeHit = firstEnv2(env, keys.modeKeys); + const urlHit = firstEnv2(env, keys.apiUrlKeys, { preserveRaw: true }); + const keyHit = firstEnv2(env, keys.apiKeyKeys); + let mode = "sqlite"; + let modeSource = "default"; + const warnings = []; + let credential; + if (modeHit) { + mode = normalizeStorageMode(modeHit.value).mode; + modeSource = modeHit.key; + } else if (urlHit) { + credential = resolveCredential(name, env, options.credentials); + if (credential) { + mode = "postgres"; + modeSource = `${urlHit.key}+${credential.source}`; + } } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) + if (mode === "sqlite") { + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: Boolean(keyHit), + apiKeySource: keyHit ? keyHit.key : null, + apiKeyTier: null, + misconfigured: false, + warning: warnings.length > 0 ? warnings.join(" ") : null }; } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); + if (credential === undefined) + credential = resolveCredential(name, env, options.credentials); + if (!credential) { + const diskHint = credentialDiskSourcesForMessage(name, env); + warnings.push(`${modeSource}=postgres but no API key could be resolved for '${name}'. A client reaches server data ` + `over HTTP only; refusing to route. Using the local sqlite store. ` + `Looked for a credential file at ${diskHint}, then for ${keys.apiKeyKeys[0]} in the environment.`); + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: false, + apiKeySource: null, + apiKeyTier: null, + misconfigured: true, + warning: warnings.join(" ") + }; } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?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)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?: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])$/; -var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\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])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; + if (credential.warning) + warnings.push(credential.warning); + let defaultBaseUrl = null; + let apiUrlSource = urlHit?.key ?? (env[FLEET_API_DOMAIN_ENV_KEY] === undefined ? "default" : FLEET_API_DOMAIN_ENV_KEY); + let baseUrl; + try { + if (!urlHit) { + defaultBaseUrl = resolveDefaultCloudBaseUrl(name, env); + apiUrlSource = defaultBaseUrl.source; + } + const rawUrl = urlHit?.value ?? defaultBaseUrl.baseUrl; + baseUrl = toV1BaseUrl(rawUrl); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + warnings.push(`Invalid API URL from ${apiUrlSource}: ${message}. Using local store.`); + return { + transport: "sqlite", + mode, + modeSource, + baseUrl: null, + apiUrlSource: null, + apiKeyPresent: true, + apiKeySource: credential.source, + apiKeyTier: credential.tier, + misconfigured: true, + warning: warnings.join(" ") + }; } + if (defaultBaseUrl?.warning) + warnings.push(defaultBaseUrl.warning); + return { + transport: "http", + mode, + modeSource, + baseUrl, + apiUrlSource, + apiKeyPresent: true, + apiKeySource: credential.source, + apiKeyTier: credential.tier, + misconfigured: defaultBaseUrl?.misconfigured ?? false, + warning: warnings.length > 0 ? warnings.join(" ") : null + }; } -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; +function credentialDiskSourcesForMessage(name, env) { + const paths = credentialDiskSources(name, env); + return paths.length > 0 ? paths.join(" or ") : "<no HOME set in this environment, so no credential file was consulted>"; } -class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; +class HasnaHttpError extends Error { + status; + method; + path; + body; + credentialSource; + credentialTier; + constructor(method, path, status, body, credential) { + const guidance = credential ? `. ${credential.guidance}` : ""; + super(`Hasna cloud request failed: ${method} ${path} -> ${status}${guidance}`); + this.name = "HasnaHttpError"; + this.status = status; + this.method = method; + this.path = path; + this.body = body; + this.credentialSource = credential?.source ?? null; + this.credentialTier = credential?.tier ?? null; } } -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; +function currentCredential(name, apiKey) { + if (typeof apiKey === "function") + return apiKey(); + return explicitCredential(name, apiKey); } - -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = undefined; - const status = new ParseStatus; - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); +function authFailureGuidance(credential) { + const origin = `The API key for this request came from ${credential.source}`; + if (credential.deliberate) { + return `${origin} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: ` + `falling back here would authenticate as a different principal than the one you named, which is ` + `exactly the failure an override exists to prevent. Rotate that key, or unset the override to use ` + `the credential on disk.`; } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); + if (credential.deprecated) { + const target = credential.diskCandidates[0]; + const remedy = target ? `Write the CURRENT key to ${target} \u2014 that file is re-read on every call, so rotations take ` + `effect immediately and in every shell. Do not simply unset ${credential.source}: nothing was ` + `found on disk, so that would leave this client with no credential at all.` : `This environment has no HOME, so no credential file could be consulted; the disk tier is ` + `unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.`; + return `${origin}, a variable in this process's environment \u2014 which is a snapshot taken when the process ` + `started. A STALE SHELL is the most common cause of this error: this shell exported the key before ` + `it was rotated, and will keep sending the old one until it exits. ${remedy}`; } + return `${origin}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. ` + `The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution ` + `so this machine gets the current key.`; } -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; - -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; +var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504]; +var IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); +var AUTHORITY_OVERRIDE_HEADERS = new Set([ + "host", + ":authority", + "forwarded", + "x-forwarded-host", + "x-original-host" +]); +function assertNoAuthorityOverrideHeaders(headers, source) { + if (!headers) + return; + const forbidden = Object.keys(headers).find((name) => AUTHORITY_OVERRIDE_HEADERS.has(name.trim().toLowerCase())); + if (forbidden) { + throw new Error(`Authenticated ${source} headers must not set authority header '${forbidden}'.`); } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus; - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } +} +function appendQuery(path, query) { + if (!query) + return path; + const params = query instanceof URLSearchParams ? query : new URLSearchParams; + if (!(query instanceof URLSearchParams)) { + for (const [key, value] of Object.entries(query)) { + if (value === null || value === undefined) + continue; + if (Array.isArray(value)) { + for (const v of value) + params.append(key, String(v)); } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + params.append(key, String(value)); } } - return max; } + const qs = params.toString(); + if (!qs) + return path; + return `${path}${path.includes("?") ? "&" : "?"}${qs}`; } -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; - -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); +var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); +function createHasnaHttpTransport(options) { + const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init)); + const base = toV1BaseUrl(options.baseUrl); + const timeoutMs = options.timeoutMs ?? 30000; + const sleep = options.sleepImpl ?? defaultSleep; + const defaultRetry = options.retry; + function resolveRetry(callRetry) { + const chosen = callRetry !== undefined ? callRetry : defaultRetry; + if (chosen === false) + return null; + const r = chosen ?? {}; + return { + retries: r.retries ?? 2, + baseDelayMs: r.baseDelayMs ?? 200, + maxDelayMs: r.maxDelayMs ?? 2000, + retryStatuses: r.retryStatuses ?? [...DEFAULT_RETRY_STATUSES] + }; } -} -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; - -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) + async function once(method, rel, url, body, opts, credential) { + assertNoAuthorityOverrideHeaders(options.headers, "transport"); + assertNoAuthorityOverrideHeaders(opts.headers, "request"); + const headers = { + "x-api-key": credential.apiKey, + Authorization: `Bearer ${credential.apiKey}`, + Accept: "application/json", + ...options.headers ?? {}, + ...opts.headers ?? {} }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; - -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; - -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; - -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; - -class ZodAny extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; - -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; - -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -} -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; - -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -} -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; - -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} - -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -} -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; - -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -} -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [undefined]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -} -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; + if (opts.idempotencyKey) + headers["Idempotency-Key"] = opts.idempotencyKey; + const init = { + method, + headers, + redirect: "manual" }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; - -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest - }); - } -} -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; - -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -} - -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; - -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; - -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -} - -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; - -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} - -class ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum.create = createZodEnum; - -class ZodNativeEnum extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; - -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; - -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util.assertNever(effect); - } -} -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; - -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; - -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; - -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; - -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; - -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = Symbol("zod_brand"); - -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -} - -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: (arg) => ZodString.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), - date: (arg) => ZodDate.create({ ...arg, coerce: true }) -}; -var NEVER = INVALID; -var SCHEMA_IDS = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema = exports_external.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema = exports_external.string().datetime(); -var NonEmptyStringSchema = exports_external.string().trim().min(1); -var UriSchema = NonEmptyStringSchema.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema = exports_external.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema = exports_external.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema = exports_external.record(exports_external.unknown()); -var TagsSchema = exports_external.array(exports_external.string().min(1)).default([]); -var OptionalTimestampSchema = TimestampSchema.nullable().optional(); -var TerminalStatuses = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema = exports_external.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema(schema) { - return exports_external.object({ - schema: exports_external.literal(schema), - id: exports_external.string().min(1), - createdAt: TimestampSchema, - updatedAt: OptionalTimestampSchema, - metadata: MetadataSchema.optional() - }).strict(); -} -var ContractEnvelopeSchema = exports_external.object({ - schema: SchemaIdSchema, - id: exports_external.string().min(1), - createdAt: TimestampSchema, - updatedAt: OptionalTimestampSchema, - metadata: MetadataSchema.optional() -}).strict(); -var ActorKindSchema = exports_external.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema = contractBaseSchema(SCHEMA_IDS.actorRef).extend({ - kind: ActorKindSchema, - name: exports_external.string().min(1).optional(), - provider: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - machineId: exports_external.string().min(1).optional(), - capabilities: exports_external.array(exports_external.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema = exports_external.object({ - kind: ActorKindSchema, - id: exports_external.string().min(1), - name: exports_external.string().min(1).optional(), - provider: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - machineId: exports_external.string().min(1).optional() -}).strict(); -var ResourceKindSchema = exports_external.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema = contractBaseSchema(SCHEMA_IDS.resourceRef).extend({ - kind: ResourceKindSchema, - name: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema = exports_external.object({ - kind: ResourceKindSchema, - id: exports_external.string().min(1), - name: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema = exports_external.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema = exports_external.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema = contractBaseSchema(SCHEMA_IDS.evidenceRef).extend({ - kind: EvidenceKindSchema, - uri: UriSchema, - sha256: Sha256DigestSchema.optional(), - summary: exports_external.string().min(1).optional(), - contentType: exports_external.string().min(1).optional(), - sizeBytes: exports_external.number().int().nonnegative().optional(), - redaction: RedactionStateSchema.default("unknown"), - producer: ActorPointerSchema.optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - tags: TagsSchema -}).strict(); -var EvidencePointerSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: EvidenceKindSchema.optional(), - uri: UriSchema.optional(), - sha256: Sha256DigestSchema.optional(), - summary: exports_external.string().min(1).optional() -}).strict(); -var CostEstimateSchema = contractBaseSchema(SCHEMA_IDS.costEstimate).extend({ - currency: exports_external.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external.number().int().nonnegative(), - provider: exports_external.string().min(1).optional(), - model: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - promptTokens: exports_external.number().int().nonnegative().optional(), - completionTokens: exports_external.number().int().nonnegative().optional(), - totalTokens: exports_external.number().int().nonnegative().optional(), - basis: exports_external.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema = exports_external.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.decisionEnvelope).extend({ - decisionType: exports_external.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema, - actor: ActorPointerSchema.optional(), - traceId: exports_external.string().min(1).optional(), - inputHash: HashStringSchema.optional(), - policyBundleId: exports_external.string().min(1).optional(), - selected: exports_external.array(ResourcePointerSchema).default([]), - skipped: exports_external.array(ResourcePointerSchema).default([]), - reason: exports_external.string().min(1), - obligations: exports_external.array(exports_external.string().min(1)).default([]), - redactions: exports_external.array(exports_external.string().min(1)).default([]), - costEstimate: CostEstimateSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema = contractBaseSchema(SCHEMA_IDS.capabilityCard).extend({ - kind: exports_external.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external.string().min(1), - version: exports_external.string().min(1).optional(), - status: exports_external.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external.array(exports_external.string().min(1)).default([]), - limitations: exports_external.array(exports_external.string().min(1)).default([]), - riskLevel: exports_external.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict(); -var ProviderModeSchema = exports_external.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema = exports_external.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema = exports_external.object({ - refName: NonEmptyStringSchema, - requiredForModes: exports_external.array(ProviderModeSchema).min(1), - allowedSecretInputs: exports_external.array(exports_external.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema, - revocationCheck: exports_external.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema = exports_external.object({ - operation: NonEmptyStringSchema, - supportedModes: exports_external.array(ProviderModeSchema).min(1), - sideEffectClass: ProviderSideEffectClassSchema, - requiresApproval: exports_external.boolean().default(false), - requiresIdempotencyKey: exports_external.boolean().default(false), - requiresSandboxEvidence: exports_external.boolean().default(false), - requiresRollbackOrRevocation: exports_external.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema.optional(), - noSideEffectSmoke: NonEmptyStringSchema.optional(), - reconciliation: NonEmptyStringSchema.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema = exports_external.object({ - providerId: NonEmptyStringSchema, - appId: NonEmptyStringSchema, - adapterId: NonEmptyStringSchema, - ownerPackage: NonEmptyStringSchema, - modes: exports_external.array(ProviderModeSchema).min(1), - defaultMode: ProviderModeSchema, - credentialRequirements: exports_external.array(CredentialRequirementSchema).default([]), - operations: exports_external.array(ProviderOperationCardSchema).min(1), - rateLimitPosture: NonEmptyStringSchema, - costPosture: NonEmptyStringSchema.optional(), - auditEvents: exports_external.array(NonEmptyStringSchema).default([]), - redactionRules: exports_external.array(NonEmptyStringSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema = exports_external.object({ - appId: NonEmptyStringSchema, - repo: NonEmptyStringSchema, - priority: exports_external.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external.array(NonEmptyStringSchema).min(1), - firstOperations: exports_external.array(NonEmptyStringSchema).min(1), - blockedUntil: exports_external.array(NonEmptyStringSchema).default([]) -}).strict(); -var ProviderLiveModeStandardSchema = contractBaseSchema(SCHEMA_IDS.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema, - version: NonEmptyStringSchema, - modes: exports_external.array(ProviderModeSchema).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external.array(NonEmptyStringSchema).min(1), - liveMutationGate: exports_external.object({ - requiredMode: exports_external.literal("live_mutating"), - requiredChecks: exports_external.array(NonEmptyStringSchema).min(1), - forbiddenBypassSignals: exports_external.array(NonEmptyStringSchema).min(1), - disabledLiveSmoke: NonEmptyStringSchema - }).strict(), - noSideEffectSmoke: exports_external.object({ - requiredForModes: exports_external.array(ProviderModeSchema).min(1), - commandEvidence: exports_external.array(NonEmptyStringSchema).min(1), - secretOutputScan: exports_external.boolean().default(true) - }).strict(), - credentialPolicy: exports_external.object({ - acceptedInputs: exports_external.array(exports_external.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external.literal(false), - missingCredentialBehavior: exports_external.literal("fail_closed"), - revocationCheckRequired: exports_external.boolean().default(true) - }).strict(), - operationCards: exports_external.array(ProviderCapabilityCardSchema).min(1), - firstAdoptionTargets: exports_external.array(ProviderLiveModeTargetSchema).min(1), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema = exports_external.object({ - id: exports_external.string().min(1), - title: exports_external.string().min(1).optional(), - summary: exports_external.string().min(1), - text: exports_external.string().optional(), - tokens: exports_external.number().int().nonnegative().optional(), - source: EvidencePointerSchema, - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict(); -var ContextPackSchema = contractBaseSchema(SCHEMA_IDS.contextPack).extend({ - objective: exports_external.string().min(1), - budget: exports_external.object({ - maxTokens: exports_external.number().int().positive().optional(), - maxBytes: exports_external.number().int().positive().optional() - }).strict().optional(), - items: exports_external.array(ContextPackItemSchema).default([]), - citations: exports_external.array(EvidencePointerSchema).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external.array(exports_external.string().min(1)).default([]), - redactions: exports_external.array(exports_external.string().min(1)).default([]), - conflicts: exports_external.array(exports_external.string().min(1)).default([]), - uncertainty: exports_external.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema = NonEmptyStringSchema.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema = exports_external.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema = exports_external.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema = exports_external.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema = exports_external.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema = contractBaseSchema(SCHEMA_IDS.integrationRef).extend({ - kind: ProjectIntegrationKindSchema, - name: exports_external.string().min(1), - projectId: ProjectSlugSchema.optional(), - sourcePackage: NonEmptyStringSchema.optional(), - externalId: NonEmptyStringSchema.optional(), - uri: UriSchema.optional(), - enabled: exports_external.boolean().default(true), - readOnly: exports_external.boolean().default(true), - capabilities: exports_external.array(exports_external.string().min(1)).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - config: MetadataSchema.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema = exports_external.object({ - schemaRoot: RelativeProjectPathSchema.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema.default("documents"), - reportsDir: RelativeProjectPathSchema.default("reports"), - evidenceDir: RelativeProjectPathSchema.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema = contractBaseSchema(SCHEMA_IDS.projectManifest).extend({ - projectId: ProjectSlugSchema, - slug: ProjectSlugSchema, - name: exports_external.string().min(1), - summary: exports_external.string().min(1).optional(), - status: ProjectStatusSchema.default("active"), - classification: ProjectClassificationSchema.default("private"), - owner: ActorPointerSchema.optional(), - layout: ProjectLayoutSchema.default({}), - integrations: exports_external.array(IntegrationRefSchema).default([]), - renderManifests: exports_external.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema = exports_external.enum(["local", "package", "provider", "url"]); -var RenderImportSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: RenderImportKindSchema, - specifier: exports_external.string().min(1), - path: RelativeProjectPathSchema.optional(), - packageName: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - provider: ProjectIntegrationKindSchema.optional(), - schemaId: SchemaIdSchema.optional(), - integrity: HashStringSchema.optional(), - resourceRef: ResourcePointerSchema.optional(), - optional: exports_external.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema = exports_external.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema = exports_external.object({ - id: exports_external.string().min(1), - title: exports_external.string().min(1), - kind: RenderViewKindSchema, - default: exports_external.boolean().default(false), - entry: RelativeProjectPathSchema.optional(), - imports: exports_external.array(RenderImportSchema).default([]), - panelRefs: exports_external.array(ResourcePointerSchema).default([]), - dataRefs: exports_external.array(ResourcePointerSchema).default([]), - layout: MetadataSchema.optional() -}).strict(); -var RenderManifestSchema = contractBaseSchema(SCHEMA_IDS.renderManifest).extend({ - projectId: ProjectSlugSchema, - name: exports_external.string().min(1), - version: exports_external.string().min(1), - manifestPath: RelativeProjectPathSchema.default(".hasna/project/dashboard.render.json"), - renderer: exports_external.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external.array(RenderViewSchema).min(1), - imports: exports_external.array(RenderImportSchema).default([]), - theme: MetadataSchema.optional(), - compatibility: exports_external.object({ - minProjectsVersion: exports_external.string().min(1).optional(), - minContractsVersion: exports_external.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema = exports_external.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema = exports_external.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema = exports_external.object({ - id: exports_external.string().min(1), - label: exports_external.string().min(1), - value: exports_external.union([exports_external.string(), exports_external.number(), exports_external.boolean()]), - unit: exports_external.string().min(1).optional(), - status: exports_external.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict(); -var ProjectPanelItemSchema = exports_external.object({ - id: exports_external.string().min(1), - title: exports_external.string().min(1), - summary: exports_external.string().min(1).optional(), - status: exports_external.string().min(1).optional(), - priority: exports_external.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema.optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - metadata: MetadataSchema.optional() -}).strict(); -var ProjectRenderFragmentSchema = exports_external.object({ - renderer: exports_external.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external.string().min(1).optional(), - entry: RelativeProjectPathSchema.optional(), - imports: exports_external.array(RenderImportSchema).default([]), - spec: MetadataSchema.default({}) -}).strict(); -var ProjectPanelSchema = contractBaseSchema(SCHEMA_IDS.projectPanel).extend({ - projectId: ProjectSlugSchema, - provider: exports_external.object({ - kind: ProjectIntegrationKindSchema, - id: exports_external.string().min(1), - name: exports_external.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema.optional(), - externalId: NonEmptyStringSchema.optional() - }).strict(), - kind: ProjectPanelKindSchema, - title: exports_external.string().min(1), - summary: exports_external.string().min(1).optional(), - state: ProjectPanelStateSchema.default("ready"), - stateReason: exports_external.string().min(1).optional(), - generatedAt: TimestampSchema, - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external.array(ProjectPanelMetricSchema).default([]), - items: exports_external.array(ProjectPanelItemSchema).default([]), - actions: exports_external.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - renderFragment: ProjectRenderFragmentSchema.optional(), - warnings: exports_external.array(exports_external.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema = contractBaseSchema(SCHEMA_IDS.projectSnapshot).extend({ - projectId: ProjectSlugSchema, - generatedAt: TimestampSchema, - status: ContractStatusSchema.default("unknown"), - manifestRef: ResourcePointerSchema, - renderManifestRef: ResourcePointerSchema.optional(), - panels: exports_external.array(ProjectPanelSchema).default([]), - contextPacks: exports_external.array(ContextPackSchema).default([]), - proofBundleRefs: exports_external.array(ResourcePointerSchema).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - warnings: exports_external.array(exports_external.string().min(1)).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: exports_external.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external.boolean().default(true), - command: exports_external.string().min(1).optional(), - expected: exports_external.string().min(1).optional(), - timeoutMs: exports_external.number().int().positive().optional(), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema = contractBaseSchema(SCHEMA_IDS.validationPlan).extend({ - objective: exports_external.string().min(1), - subject: ResourcePointerSchema.optional(), - checks: exports_external.array(ValidationCheckSchema).min(1), - verifier: ActorPointerSchema.optional(), - requiredEvidenceKinds: exports_external.array(EvidenceKindSchema).default([]) -}).strict(); -var ScaffoldTypeSchema = exports_external.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema = exports_external.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema = exports_external.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema = exports_external.object({ - key: exports_external.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external.string().min(1), - required: exports_external.boolean().default(false), - ["secret"]: exports_external.boolean().default(false), - group: exports_external.string().min(1).optional(), - default: exports_external.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema = exports_external.object({ - name: exports_external.string().min(1), - command: exports_external.string().min(1), - description: exports_external.string().min(1).optional(), - required: exports_external.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema = exports_external.object({ - packageManager: exports_external.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external.array(exports_external.string().min(1)).default([]), - requiredFiles: exports_external.array(exports_external.string().min(1)).default([]), - requiredDirectories: exports_external.array(exports_external.string().min(1)).default([]), - optionalDirectories: exports_external.array(exports_external.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema = contractBaseSchema(SCHEMA_IDS.scaffoldManifest).extend({ - name: exports_external.string().min(1), - version: exports_external.string().min(1), - summary: exports_external.string().min(1), - type: ScaffoldTypeSchema, - status: ScaffoldStatusSchema.default("draft"), - capabilities: exports_external.array(ScaffoldCapabilitySchema).default([]), - techStack: exports_external.array(exports_external.string().min(1)).default([]), - tags: TagsSchema, - source: ResourcePointerSchema.optional(), - output: ScaffoldOutputShapeSchema, - env: exports_external.array(ScaffoldEnvVarSchema).default([]), - scripts: exports_external.array(ScaffoldScriptSchema).default([]), - validationChecks: exports_external.array(ValidationCheckSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema = exports_external.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema = contractBaseSchema(SCHEMA_IDS.scaffoldInstallRecord).extend({ - scaffoldId: exports_external.string().min(1), - scaffoldVersion: exports_external.string().min(1).optional(), - manifestRef: ResourcePointerSchema.optional(), - target: ResourcePointerSchema, - status: ScaffoldInstallStatusSchema, - installedAt: TimestampSchema.optional(), - installer: ActorPointerSchema.optional(), - packageManager: exports_external.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema.optional(), - generatedFiles: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - proofBundleRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema = exports_external.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema = exports_external.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema = exports_external.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema = exports_external.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema = NonEmptyStringSchema.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema = exports_external.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema = exports_external.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema = exports_external.object({ - transport: exports_external.enum(["http", "stdio"]).default("http"), - bin: exports_external.string().min(1).optional(), - url: UriSchema.optional() -}).strict(); -var AppHttpSurfaceSchema = exports_external.object({ - healthPath: exports_external.string().min(1).default("/health"), - port: exports_external.number().int().positive().optional(), - baseUrl: UriSchema.optional() -}).strict(); -var AppSurfacesSchema = exports_external.object({ - bins: exports_external.array(exports_external.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema.optional(), - http: AppHttpSurfaceSchema.optional() -}).strict(); -var AppSchema = contractBaseSchema(SCHEMA_IDS.app).extend({ - appId: AppIdSchema, - npmName: NpmPackageNameSchema, - repoFolder: AppIdSchema, - githubUrl: GithubUrlSchema, - projectSlug: ProjectSlugSchema, - surfaces: AppSurfacesSchema.default({}), - lifecycle: AppLifecycleSchema, - releaseChannel: ReleaseChannelSchema.default("stable"), - summary: exports_external.string().min(1).optional(), - tags: TagsSchema -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema = exports_external.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema = contractBaseSchema(SCHEMA_IDS.release).extend({ - appId: AppIdSchema, - package: NpmPackageNameSchema, - version: SemverSchema, - gitSha: GitShaSchema, - publishedAt: TimestampSchema, - publishPath: PublishPathSchema, - changelogRef: ResourcePointerSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema = exports_external.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema = exports_external.object({ - cliVersion: exports_external.string().min(1).optional(), - mcpHealth: exports_external.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema = contractBaseSchema(SCHEMA_IDS.rolloutRecord).extend({ - appId: AppIdSchema, - package: NpmPackageNameSchema, - version: SemverSchema, - machine: NonEmptyStringSchema, - action: RolloutActionSchema, - result: ContractStatusSchema, - verifiedBy: RolloutVerificationSchema.optional(), - at: TimestampSchema, - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema = exports_external.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema = exports_external.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema = exports_external.object({ - channel: AnnouncementChannelKindSchema, - status: AnnouncementDeliveryStatusSchema, - deliveredAt: TimestampSchema.optional(), - detail: exports_external.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema = contractBaseSchema(SCHEMA_IDS.announcement).extend({ - campaignId: NonEmptyStringSchema, - appId: AppIdSchema.optional(), - releaseRef: ResourcePointerSchema.optional(), - channels: exports_external.array(AnnouncementChannelSchema).min(1), - audienceRef: ResourcePointerSchema, - sentAt: TimestampSchema -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema = exports_external.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema = exports_external.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema = exports_external.union([exports_external.string(), exports_external.number(), exports_external.boolean()]); -var AudiencePredicateSchema = exports_external.object({ - kind: AudiencePredicateKindSchema, - key: exports_external.string().min(1).optional(), - op: AudiencePredicateOpSchema.default("eq"), - value: AudiencePredicateValueSchema.optional(), - values: exports_external.array(AudiencePredicateValueSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema = exports_external.object({ - match: exports_external.enum(["all", "any"]).default("all"), - predicates: exports_external.array(AudiencePredicateSchema).min(1) -}).strict(); -var ConsentPolicySchema = exports_external.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema = contractBaseSchema(SCHEMA_IDS.audience).extend({ - audienceId: AppIdSchema, - name: NonEmptyStringSchema, - definition: AudienceDefinitionSchema, - consentPolicy: ConsentPolicySchema, - suppressionSyncedAt: OptionalTimestampSchema -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema = exports_external.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema = exports_external.object({ - id: exports_external.string().min(1), - provider: AppCloudProviderSchema, - kind: exports_external.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external.string().min(1), - region: exports_external.string().min(1).optional(), - accountId: exports_external.string().min(1).optional(), - uri: UriSchema.optional(), - machineScoped: exports_external.boolean().default(false) -}).strict(); -var AppCloudManifestSchema = contractBaseSchema(SCHEMA_IDS.appCloudManifest).extend({ - packageName: exports_external.string().min(1), - packageVersion: exports_external.string().min(1).optional(), - appId: exports_external.string().min(1), - repository: ResourcePointerSchema.optional(), - storageMode: exports_external.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external.array(AppCloudResourceSchema).default([]), - localCache: exports_external.object({ - path: exports_external.string().min(1).optional(), - pullMode: exports_external.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external.array(exports_external.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES]), - dependencies: exports_external.array(exports_external.string().min(1)).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema = exports_external.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema = exports_external.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: NoCloudCheckKindSchema, - severity: NoCloudFindingSeveritySchema, - path: exports_external.string().min(1).optional(), - packageName: exports_external.string().min(1).optional(), - pattern: exports_external.string().min(1), - message: exports_external.string().min(1), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict(); -var NoCloudCheckResultSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: NoCloudCheckKindSchema, - status: ContractStatusSchema, - target: exports_external.string().min(1), - command: exports_external.string().min(1).optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - findings: exports_external.array(NoCloudFindingSchema).default([]) -}).strict(); -var NoCloudEvidencePackSchema = contractBaseSchema(SCHEMA_IDS.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema, - packageName: exports_external.string().min(1).optional(), - packageVersion: exports_external.string().min(1).optional(), - generatedBy: ActorPointerSchema.optional(), - scanMode: exports_external.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema, - verdict: exports_external.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema.optional(), - checks: exports_external.array(NoCloudCheckResultSchema).min(1), - findings: exports_external.array(NoCloudFindingSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check) => check.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check) => check.status !== "succeeded")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check) => check.status === "failed")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check, index) => { - const checkBlockingFindings = check.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema = exports_external.object({ - checkId: exports_external.string().min(1), - status: ContractStatusSchema, - summary: exports_external.string().min(1).optional(), - startedAt: OptionalTimestampSchema, - finishedAt: OptionalTimestampSchema, - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict(); -var ProofBundleSchema = contractBaseSchema(SCHEMA_IDS.proofBundle).extend({ - subject: ResourcePointerSchema, - validationPlanRef: ResourcePointerSchema.optional(), - status: ContractStatusSchema, - verdict: exports_external.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external.array(ProofCheckResultSchema).default([]), - verifier: ActorPointerSchema.optional(), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - residualRisks: exports_external.array(exports_external.string().min(1)).default([]), - freshness: exports_external.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check, index) => { - if (check.status !== "succeeded") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check) => check.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check) => check.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema = contractBaseSchema(SCHEMA_IDS.workRun).extend({ - objective: exports_external.string().min(1), - status: ContractStatusSchema, - actor: ActorPointerSchema, - traceId: exports_external.string().min(1).optional(), - startedAt: OptionalTimestampSchema, - finishedAt: OptionalTimestampSchema, - constraints: exports_external.array(exports_external.string().min(1)).default([]), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - decisions: exports_external.array(DecisionEnvelopeSchema).default([]), - costEstimates: exports_external.array(CostEstimateSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - validationPlanRefs: exports_external.array(ResourcePointerSchema).default([]), - proofBundleRefs: exports_external.array(ResourcePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema = exports_external.object({ - id: exports_external.string().min(1), - at: TimestampSchema, - kind: exports_external.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external.string().min(1), - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]), - costEstimate: CostEstimateSchema.optional() -}).strict(); -var AgentTrajectorySchema = contractBaseSchema(SCHEMA_IDS.agentTrajectory).extend({ - actor: ActorPointerSchema, - workRunRef: ResourcePointerSchema.optional(), - events: exports_external.array(TrajectoryEventSchema).default([]), - outcome: exports_external.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION = "v1"; -var RepoClassSchema = exports_external.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema = exports_external.enum(DEPLOYMENT_MODES); -var ServiceSurfaceStatusSchema = exports_external.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema = exports_external.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema = exports_external.object({ - method: exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external.boolean().default(false), - description: exports_external.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema = exports_external.object({ - id: exports_external.string().min(1), - kind: exports_external.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external.boolean().default(true), - command: exports_external.string().min(1).optional(), - evidenceRef: EvidencePointerSchema.optional(), - status: exports_external.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema = exports_external.object({ - name: exports_external.string().min(1), - status: ServiceSurfaceStatusSchema, - bin: exports_external.string().min(1).optional(), - mcpBin: exports_external.string().min(1).optional(), - authMode: ServiceAuthModeSchema, - deploymentModes: exports_external.array(DeploymentModeSchema).min(1), - health: ServiceEndpointSchema.optional(), - readiness: ServiceEndpointSchema.optional(), - version: ServiceEndpointSchema.optional(), - apiBasePath: exports_external.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external.string().min(1).optional(), - readinessGates: exports_external.array(DeploymentReadinessGateSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES = ["local", "cloud"]; -var StorageModeSchema = exports_external.enum(STORAGE_MODES); -var DEPRECATED_STORAGE_MODE_ALIASES = ["remote", "hybrid", "self_hosted"]; -var AppNameSchema = exports_external.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName(name) { - return ALLOWED_BIN_SUFFIXES.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema = exports_external.object({ - mode: StorageModeSchema, - envPrefix: exports_external.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema = exports_external.object({ - $schema: exports_external.string().min(1).optional(), - schema: exports_external.literal(SCHEMA_IDS.serviceContract), - name: AppNameSchema, - class: RepoClassSchema, - contractVersion: exports_external.literal(SERVICE_CONTRACT_VERSION), - kitVersion: exports_external.string().min(1), - description: exports_external.string().min(1).optional(), - bins: exports_external.array(exports_external.string().min(1)).default([]), - storage: StorageContractSchema.optional(), - deploymentModes: exports_external.array(DeploymentModeSchema).default(["local"]), - serviceSurfaces: exports_external.array(ServiceSurfaceSchema).default([]), - metadata: MetadataSchema.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor(value.name)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } - } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); - } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } - } - } -}); -var HealthResponseSchema = exports_external.object({ - status: exports_external.enum(["ok", "degraded", "unavailable"]), - version: exports_external.string().min(1), - mode: StorageModeSchema -}).strict(); -var ReadyResponseSchema = exports_external.object({ - ready: exports_external.boolean(), - reason: exports_external.string().min(1).optional() -}).strict(); -var VersionResponseSchema = exports_external.object({ - version: exports_external.string().min(1) -}).strict(); -var CommsSeveritySchema = exports_external.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema = exports_external.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); -var COMMS_SEVERITY_TAGS = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema = exports_external.enum(COMMS_SEVERITY_TAGS); -var CommsScopeSchema = exports_external.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema = contractBaseSchema(SCHEMA_IDS.commsEventEnvelope).extend({ - type: CommsEventTypeSchema, - severity: CommsSeveritySchema, - scope: CommsScopeSchema, - summary: exports_external.string().min(1).optional(), - source: ActorPointerSchema.optional(), - affected_packages: exports_external.array(NonEmptyStringSchema).default([]), - affected_machines: exports_external.array(NonEmptyStringSchema).default([]), - action_required: exports_external.boolean().default(false), - ack_by: TimestampSchema.optional(), - dedupe_key: NonEmptyStringSchema, - resourceRefs: exports_external.array(ResourcePointerSchema).default([]), - evidenceRefs: exports_external.array(EvidencePointerSchema).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); - } - } -}); -var CommsChannelClassSchema = exports_external.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema = exports_external.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema = NonEmptyStringSchema.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); -var CommsChannelMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsChannelMetadata).extend({ - class: CommsChannelClassSchema, - noise: CommsChannelNoiseSchema.optional(), - owner: NonEmptyStringSchema.optional(), - until: CommsUntilHorizonSchema.optional(), - successor: NonEmptyStringSchema.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); - } - } -}); -var COMMS_SEVERITY_TAG_INFO = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema = contractBaseSchema(SCHEMA_IDS.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema, - envelope: CommsEventEnvelopeSchema -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] - }); - } - } -}); -var ContractSchemaRegistry = { - [SCHEMA_IDS.actorRef]: ActorRefSchema, - [SCHEMA_IDS.resourceRef]: ResourceRefSchema, - [SCHEMA_IDS.evidenceRef]: EvidenceRefSchema, - [SCHEMA_IDS.workRun]: WorkRunSchema, - [SCHEMA_IDS.decisionEnvelope]: DecisionEnvelopeSchema, - [SCHEMA_IDS.costEstimate]: CostEstimateSchema, - [SCHEMA_IDS.capabilityCard]: CapabilityCardSchema, - [SCHEMA_IDS.providerLiveModeStandard]: ProviderLiveModeStandardSchema, - [SCHEMA_IDS.contextPack]: ContextPackSchema, - [SCHEMA_IDS.integrationRef]: IntegrationRefSchema, - [SCHEMA_IDS.projectManifest]: ProjectManifestSchema, - [SCHEMA_IDS.projectPanel]: ProjectPanelSchema, - [SCHEMA_IDS.projectSnapshot]: ProjectSnapshotSchema, - [SCHEMA_IDS.renderManifest]: RenderManifestSchema, - [SCHEMA_IDS.agentTrajectory]: AgentTrajectorySchema, - [SCHEMA_IDS.validationPlan]: ValidationPlanSchema, - [SCHEMA_IDS.proofBundle]: ProofBundleSchema, - [SCHEMA_IDS.scaffoldManifest]: ScaffoldManifestSchema, - [SCHEMA_IDS.scaffoldInstallRecord]: ScaffoldInstallRecordSchema, - [SCHEMA_IDS.appCloudManifest]: AppCloudManifestSchema, - [SCHEMA_IDS.noCloudEvidencePack]: NoCloudEvidencePackSchema, - [SCHEMA_IDS.serviceContract]: ServiceContractManifestSchema, - [SCHEMA_IDS.commsEventEnvelope]: CommsEventEnvelopeSchema, - [SCHEMA_IDS.commsChannelMetadata]: CommsChannelMetadataSchema, - [SCHEMA_IDS.commsMessageMetadata]: CommsMessageMetadataSchema, - [SCHEMA_IDS.app]: AppSchema, - [SCHEMA_IDS.release]: ReleaseSchema, - [SCHEMA_IDS.rolloutRecord]: RolloutRecordSchema, - [SCHEMA_IDS.announcement]: AnnouncementSchema, - [SCHEMA_IDS.audience]: AudienceSchema -}; -function normalizeStorageMode(value) { - const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); -} -function envToken(name) { - return name.toUpperCase().replace(/-/g, "_"); -} -function defaultCloudBaseUrl(name) { - return `https://${name}.hasna.xyz`; -} -function clientTransportEnvKeys(name) { - const envSegment = envToken(name); - return { - modeKeys: [ - `HASNA_${envSegment}_STORAGE_MODE`, - `HASNA_${envSegment}_MODE`, - `${envSegment}_STORAGE_MODE`, - `${envSegment}_MODE` - ], - apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], - apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] - }; -} -function firstEnv2(env, keys) { - for (const key of keys) { - const value = env[key]?.trim(); - if (value) - return { key, value }; - } - return null; -} -function toV1BaseUrl(apiUrl) { - const url = new URL(apiUrl); - if (url.protocol !== "http:" && url.protocol !== "https:") { - throw new Error("API URL must use http or https."); - } - let path = url.pathname.replace(/\/+$/, ""); - if (path.endsWith("/v1")) - path = path.slice(0, -"/v1".length); - url.pathname = `${path}/v1`; - url.search = ""; - url.hash = ""; - return url.toString().replace(/\/+$/, ""); -} -function resolveClientTransport(name, env = process.env) { - const keys = clientTransportEnvKeys(name); - const modeHit = firstEnv2(env, keys.modeKeys); - const urlHit = firstEnv2(env, keys.apiUrlKeys); - const keyHit = firstEnv2(env, keys.apiKeyKeys); - let mode = "local"; - let deprecatedAlias = null; - let modeSource = "default"; - const warnings = []; - if (modeHit) { - const normalized = normalizeStorageMode(modeHit.value); - mode = normalized.mode; - deprecatedAlias = normalized.deprecatedAlias; - modeSource = modeHit.key; - if (deprecatedAlias) { - warnings.push(`Deprecated mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Prefer ${keys.modeKeys[0]}=cloud.`); - } - } else if (urlHit && keyHit) { - mode = "cloud"; - modeSource = `${urlHit.key}+${keyHit.key}`; - } - if (mode === "local") { - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: Boolean(keyHit), - apiKeySource: keyHit ? keyHit.key : null, - misconfigured: false, - warning: warnings.length > 0 ? warnings.join(" ") : null - }; - } - if (!keyHit) { - warnings.push(`${modeSource}=cloud but no API key is set (${keys.apiKeyKeys[0]}). Refusing to route to cloud; using local store. Set ${keys.apiKeyKeys[0]} to enable the cloud client.`); - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: false, - apiKeySource: null, - misconfigured: true, - warning: warnings.join(" ") - }; - } - const rawUrl = urlHit?.value ?? defaultCloudBaseUrl(name); - const apiUrlSource = urlHit ? urlHit.key : "default"; - let baseUrl; - try { - baseUrl = toV1BaseUrl(rawUrl); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - warnings.push(`Invalid API URL from ${apiUrlSource}: ${message}. Using local store.`); - return { - transport: "local", - mode, - deprecatedAlias, - modeSource, - baseUrl: null, - apiUrlSource: null, - apiKeyPresent: true, - apiKeySource: keyHit.key, - misconfigured: true, - warning: warnings.join(" ") - }; - } - return { - transport: "cloud-http", - mode, - deprecatedAlias, - modeSource, - baseUrl, - apiUrlSource, - apiKeyPresent: true, - apiKeySource: keyHit.key, - misconfigured: false, - warning: warnings.length > 0 ? warnings.join(" ") : null - }; -} - -class HasnaHttpError extends Error { - status; - method; - path; - body; - constructor(method, path, status, body) { - super(`Hasna cloud request failed: ${method} ${path} -> ${status}`); - this.name = "HasnaHttpError"; - this.status = status; - this.method = method; - this.path = path; - this.body = body; - } -} -var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504]; -var IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); -function appendQuery(path, query) { - if (!query) - return path; - const params = query instanceof URLSearchParams ? query : new URLSearchParams; - if (!(query instanceof URLSearchParams)) { - for (const [key, value] of Object.entries(query)) { - if (value === null || value === undefined) - continue; - if (Array.isArray(value)) { - for (const v of value) - params.append(key, String(v)); - } else { - params.append(key, String(value)); - } - } - } - const qs = params.toString(); - if (!qs) - return path; - return `${path}${path.includes("?") ? "&" : "?"}${qs}`; -} -var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); -function createHasnaHttpTransport(options) { - const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init)); - const base = options.baseUrl.replace(/\/+$/, ""); - const timeoutMs = options.timeoutMs ?? 30000; - const sleep = options.sleepImpl ?? defaultSleep; - const defaultRetry = options.retry; - function resolveRetry(callRetry) { - const chosen = callRetry !== undefined ? callRetry : defaultRetry; - if (chosen === false) - return null; - const r = chosen ?? {}; - return { - retries: r.retries ?? 2, - baseDelayMs: r.baseDelayMs ?? 200, - maxDelayMs: r.maxDelayMs ?? 2000, - retryStatuses: r.retryStatuses ?? [...DEFAULT_RETRY_STATUSES] - }; - } - async function once(method, rel, url, body, opts) { - const headers = { - "x-api-key": options.apiKey, - Authorization: `Bearer ${options.apiKey}`, - Accept: "application/json", - ...options.headers ?? {}, - ...opts.headers ?? {} - }; - if (opts.idempotencyKey) - headers["Idempotency-Key"] = opts.idempotencyKey; - const init = { method, headers }; - if (body !== undefined) { - headers["Content-Type"] = "application/json"; - init.body = JSON.stringify(body); - } - const controller = new AbortController; - const onAbort = () => controller.abort(); - if (opts.signal) { - if (opts.signal.aborted) - controller.abort(); - else - opts.signal.addEventListener("abort", onAbort, { once: true }); - } - const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? timeoutMs); - init.signal = controller.signal; - let response; - try { - response = await fetchImpl(url, init); - } catch (error) { - const err = error instanceof Error ? error : new Error(String(error)); - if (opts.signal?.aborted) - return { ok: false, retryable: false, error: err }; - return { ok: false, retryable: true, error: err }; - } finally { - clearTimeout(timer); - if (opts.signal) - opts.signal.removeEventListener("abort", onAbort); - } - const text = await response.text(); - let parsed = undefined; - if (text.length > 0) { - try { - parsed = JSON.parse(text); - } catch { - parsed = text; - } - } - if (!response.ok) { - const retry = resolveRetry(opts.retry); - const retryable = retry ? retry.retryStatuses.includes(response.status) : false; - return { ok: false, retryable, error: new HasnaHttpError(method, rel, response.status, parsed) }; - } - return { ok: true, value: parsed }; - } - async function request(method, path, body, opts = {}) { - const upper = method.toUpperCase(); - const rel = appendQuery(path.startsWith("/") ? path : `/${path}`, opts.query); - const url = `${base}${rel}`; - const retry = resolveRetry(opts.retry); - const methodRetryable = IDEMPOTENT_METHODS.has(upper) || Boolean(opts.idempotencyKey); - const maxAttempts = retry && methodRetryable ? retry.retries + 1 : 1; - let last = null; - for (let attempt = 1;attempt <= maxAttempts; attempt++) { - const result = await once(upper, rel, url, body, opts); - if (result.ok) - return result.value; - last = result; - const canRetry = retry !== null && methodRetryable && result.retryable && attempt < maxAttempts; - if (!canRetry) - break; - const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1)); - const jitter = Math.floor(Math.random() * (backoff / 2 + 1)); - await sleep(backoff + jitter); - } - throw last.error; - } - return { - baseUrl: base, - request, - get: (path, opts) => request("GET", path, undefined, opts), - post: (path, body, opts) => request("POST", path, body, opts), - put: (path, body, opts) => request("PUT", path, body, opts), - patch: (path, body, opts) => request("PATCH", path, body, opts), - del: (path, body, opts) => request("DELETE", path, body, opts) - }; -} -function createClientTransport(name, env = process.env, overrides) { - const resolution = resolveClientTransport(name, env); - if (resolution.misconfigured) { - throw new Error(resolution.warning ?? `Client for '${name}' is misconfigured for cloud mode.`); - } - if (resolution.transport === "local" || !resolution.baseUrl) { - return { transport: "local", client: null, resolution }; - } - const keys = clientTransportEnvKeys(name); - const apiKey = firstEnv2(env, keys.apiKeyKeys)?.value; - if (!apiKey) { - throw new Error(`Client for '${name}' resolved to cloud-http without an API key.`); - } - return { - transport: "cloud-http", - client: createHasnaHttpTransport({ - name, - baseUrl: resolution.baseUrl, - apiKey, - ...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {}, - ...overrides?.headers ? { headers: overrides.headers } : {}, - ...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {}, - ...overrides?.retry !== undefined ? { retry: overrides.retry } : {}, - ...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {} - }), - resolution - }; -} -function resourcePath(resource) { - const trimmed = resource.replace(/^\/+|\/+$/g, ""); - if (!trimmed) - throw new Error("resource must be a non-empty path segment"); - return `/${trimmed}`; -} -function entityPath(resource, id) { - if (id === undefined || id === null || `${id}`.length === 0) { - throw new Error("id must be a non-empty string"); - } - return `${resourcePath(resource)}/${encodeURIComponent(String(id))}`; -} -function newIdempotencyKey() { - const g = globalThis; - if (g.crypto?.randomUUID) - return g.crypto.randomUUID(); - return `idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`; -} -function extractItems(raw) { - if (Array.isArray(raw)) - return raw; - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["items", "data", "results", "rows", "records"]) { - if (Array.isArray(obj[key])) - return obj[key]; - } - } - return []; -} -function extractTotal(raw) { - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["total", "count", "totalCount", "total_count"]) { - if (typeof obj[key] === "number") - return obj[key]; - } - } - return null; -} -function extractCursor(raw) { - if (raw && typeof raw === "object") { - const obj = raw; - for (const key of ["cursor", "nextCursor", "next_cursor", "next"]) { - if (typeof obj[key] === "string") - return obj[key]; - } - } - return null; -} -function createHasnaStorageClient(name, transport) { - return { - name, - baseUrl: transport.baseUrl, - transport, - async list(resource, options = {}) { - const raw = await transport.get(resourcePath(resource), options); - return { - items: extractItems(raw), - total: extractTotal(raw), - cursor: extractCursor(raw), - raw - }; - }, - async get(resource, id, options = {}) { - try { - return await transport.get(entityPath(resource, id), options); - } catch (error) { - if (error instanceof HasnaHttpError && error.status === 404) - return null; - throw error; - } - }, - async create(resource, body, options = {}) { - const { idempotencyKey, ...rest } = options; - return transport.post(resourcePath(resource), body, { - ...rest, - idempotencyKey: idempotencyKey ?? newIdempotencyKey() - }); - }, - async update(resource, id, patch, options = {}) { - const { method = "PATCH", idempotencyKey, ...rest } = options; - const call = method === "PUT" ? transport.put : transport.patch; - return call(entityPath(resource, id), patch, { ...rest, ...idempotencyKey ? { idempotencyKey } : {} }); - }, - async delete(resource, id, options = {}) { - try { - await transport.del(entityPath(resource, id), undefined, options); - } catch (error) { - if (error instanceof HasnaHttpError && error.status === 404) - return; - throw error; - } - } - }; -} -function resolveStorageClient(name, env = process.env, overrides) { - const wired = createClientTransport(name, env, overrides); - if (wired.transport === "cloud-http") { - return { transport: "cloud-http", client: createHasnaStorageClient(name, wired.client) }; - } - return { transport: "local", client: null }; -} - -// node_modules/@hasna/contracts/dist/client/transport.js -var __defProp3 = Object.defineProperty; -var __returnValue3 = (v) => v; -function __exportSetter3(name, newValue) { - this[name] = __returnValue3.bind(null, newValue); -} -var __export3 = (target, all) => { - for (var name in all) - __defProp3(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter3.bind(all, name) - }); -}; -var exports_external2 = {}; -__export3(exports_external2, { - void: () => voidType2, - util: () => util2, - unknown: () => unknownType2, - union: () => unionType2, - undefined: () => undefinedType2, - tuple: () => tupleType2, - transformer: () => effectsType2, - symbol: () => symbolType2, - string: () => stringType2, - strictObject: () => strictObjectType2, - setErrorMap: () => setErrorMap2, - set: () => setType2, - record: () => recordType2, - quotelessJson: () => quotelessJson2, - promise: () => promiseType2, - preprocess: () => preprocessType2, - pipeline: () => pipelineType2, - ostring: () => ostring2, - optional: () => optionalType2, - onumber: () => onumber2, - oboolean: () => oboolean2, - objectUtil: () => objectUtil2, - object: () => objectType2, - number: () => numberType2, - nullable: () => nullableType2, - null: () => nullType2, - never: () => neverType2, - nativeEnum: () => nativeEnumType2, - nan: () => nanType2, - map: () => mapType2, - makeIssue: () => makeIssue2, - literal: () => literalType2, - lazy: () => lazyType2, - late: () => late2, - isValid: () => isValid2, - isDirty: () => isDirty2, - isAsync: () => isAsync2, - isAborted: () => isAborted2, - intersection: () => intersectionType2, - instanceof: () => instanceOfType2, - getParsedType: () => getParsedType2, - getErrorMap: () => getErrorMap2, - function: () => functionType2, - enum: () => enumType2, - effect: () => effectsType2, - discriminatedUnion: () => discriminatedUnionType2, - defaultErrorMap: () => en_default2, - datetimeRegex: () => datetimeRegex2, - date: () => dateType2, - custom: () => custom2, - coerce: () => coerce2, - boolean: () => booleanType2, - bigint: () => bigIntType2, - array: () => arrayType2, - any: () => anyType2, - addIssueToContext: () => addIssueToContext2, - ZodVoid: () => ZodVoid2, - ZodUnknown: () => ZodUnknown2, - ZodUnion: () => ZodUnion2, - ZodUndefined: () => ZodUndefined2, - ZodType: () => ZodType2, - ZodTuple: () => ZodTuple2, - ZodTransformer: () => ZodEffects2, - ZodSymbol: () => ZodSymbol2, - ZodString: () => ZodString2, - ZodSet: () => ZodSet2, - ZodSchema: () => ZodType2, - ZodRecord: () => ZodRecord2, - ZodReadonly: () => ZodReadonly2, - ZodPromise: () => ZodPromise2, - ZodPipeline: () => ZodPipeline2, - ZodParsedType: () => ZodParsedType2, - ZodOptional: () => ZodOptional2, - ZodObject: () => ZodObject2, - ZodNumber: () => ZodNumber2, - ZodNullable: () => ZodNullable2, - ZodNull: () => ZodNull2, - ZodNever: () => ZodNever2, - ZodNativeEnum: () => ZodNativeEnum2, - ZodNaN: () => ZodNaN2, - ZodMap: () => ZodMap2, - ZodLiteral: () => ZodLiteral2, - ZodLazy: () => ZodLazy2, - ZodIssueCode: () => ZodIssueCode2, - ZodIntersection: () => ZodIntersection2, - ZodFunction: () => ZodFunction2, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, - ZodError: () => ZodError2, - ZodEnum: () => ZodEnum2, - ZodEffects: () => ZodEffects2, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, - ZodDefault: () => ZodDefault2, - ZodDate: () => ZodDate2, - ZodCatch: () => ZodCatch2, - ZodBranded: () => ZodBranded2, - ZodBoolean: () => ZodBoolean2, - ZodBigInt: () => ZodBigInt2, - ZodArray: () => ZodArray2, - ZodAny: () => ZodAny2, - Schema: () => ZodType2, - ParseStatus: () => ParseStatus2, - OK: () => OK2, - NEVER: () => NEVER2, - INVALID: () => INVALID2, - EMPTY_PATH: () => EMPTY_PATH2, - DIRTY: () => DIRTY2, - BRAND: () => BRAND2 -}); -var util2; -(function(util22) { - util22.assertEqual = (_) => {}; - function assertIs(_arg) {} - util22.assertIs = assertIs; - function assertNever(_x) { - throw new Error; - } - util22.assertNever = assertNever; - util22.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util22.getValidEnumValues = (obj) => { - const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util22.objectValues(filtered); - }; - util22.objectValues = (obj) => { - return util22.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util22.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util22.joinValues = joinValues; - util22.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util2 || (util2 = {})); -var objectUtil2; -(function(objectUtil22) { - objectUtil22.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; -})(objectUtil2 || (objectUtil2 = {})); -var ZodParsedType2 = util2.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType2.undefined; - case "string": - return ZodParsedType2.string; - case "number": - return Number.isNaN(data) ? ZodParsedType2.nan : ZodParsedType2.number; - case "boolean": - return ZodParsedType2.boolean; - case "function": - return ZodParsedType2.function; - case "bigint": - return ZodParsedType2.bigint; - case "symbol": - return ZodParsedType2.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType2.array; - } - if (data === null) { - return ZodParsedType2.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType2.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType2.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType2.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType2.date; - } - return ZodParsedType2.object; - default: - return ZodParsedType2.unknown; - } -}; -var ZodIssueCode2 = util2.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson2 = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; - -class ZodError2 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError2)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError2.create = (issues) => { - const error = new ZodError2(issues); - return error; -}; -var errorMap2 = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode2.invalid_type: - if (issue.received === ZodParsedType2.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode2.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`; - break; - case ZodIssueCode2.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode2.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`; - break; - case ZodIssueCode2.invalid_enum_value: - message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode2.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode2.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode2.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode2.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util2.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode2.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.custom: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode2.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode2.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util2.assertNever(issue); - } - return { message }; -}; -var en_default2 = errorMap2; -var overrideErrorMap2 = en_default2; -function setErrorMap2(map) { - overrideErrorMap2 = map; -} -function getErrorMap2() { - return overrideErrorMap2; -} -var makeIssue2 = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH2 = []; -function addIssueToContext2(ctx, issueData) { - const overrideMap = getErrorMap2(); - const issue = makeIssue2({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default2 ? undefined : en_default2 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); -} - -class ParseStatus2 { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID2; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus2.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID2; - if (value.status === "aborted") - return INVALID2; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -var INVALID2 = Object.freeze({ - status: "aborted" -}); -var DIRTY2 = (value) => ({ status: "dirty", value }); -var OK2 = (value) => ({ status: "valid", value }); -var isAborted2 = (x) => x.status === "aborted"; -var isDirty2 = (x) => x.status === "dirty"; -var isValid2 = (x) => x.status === "valid"; -var isAsync2 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil2; -(function(errorUtil22) { - errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil2 || (errorUtil2 = {})); - -class ParseInputLazyPath2 { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -var handleResult2 = (ctx, result) => { - if (isValid2(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError2(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams2(params) { - if (!params) - return {}; - const { errorMap: errorMap22, invalid_type_error, required_error, description } = params; - if (errorMap22 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap22) - return { errorMap: errorMap22, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -class ZodType2 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType2(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus2, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync2(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult2(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult2(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode2.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects2({ - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional2.create(this, this._def); - } - nullable() { - return ZodNullable2.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray2.create(this); - } - promise() { - return ZodPromise2.create(this, this._def); - } - or(option) { - return ZodUnion2.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection2.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects2({ - ...processCreateParams2(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault2({ - ...processCreateParams2(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodDefault - }); - } - brand() { - return new ZodBranded2({ - typeName: ZodFirstPartyTypeKind2.ZodBranded, - type: this, - ...processCreateParams2(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch2({ - ...processCreateParams2(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline2.create(this, target); - } - readonly() { - return ZodReadonly2.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex2 = /^c[^\s-]{8,}$/i; -var cuid2Regex2 = /^[0-9a-z]+$/; -var ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex2 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex2 = /^[a-z0-9_-]{21}$/i; -var jwtRegex2 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex2 = /^[-+]?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)?)??$/; -var emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex2 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex2; -var ipv4Regex2 = /^(?:(?: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])$/; -var ipv4CidrRegex2 = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex2 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex2 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex2 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource2 = `((\\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])))`; -var dateRegex2 = new RegExp(`^${dateRegexSource2}$`); -function timeRegexSource2(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex2(args) { - return new RegExp(`^${timeRegexSource2(args)}$`); -} -function datetimeRegex2(args) { - let regex = `${dateRegexSource2}T${timeRegexSource2(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP2(ip, version) { - if ((version === "v4" || !version) && ipv4Regex2.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex2.test(ip)) { - return true; - } - return false; -} -function isValidJWT2(jwt, alg) { - if (!jwtRegex2.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr2(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex2.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex2.test(ip)) { - return true; - } - return false; -} - -class ZodString2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.string, - received: ctx2.parsedType - }); - return INVALID2; - } - const status = new ParseStatus2; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "email", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex2) { - emojiRegex2 = new RegExp(_emojiRegex2, "u"); - } - if (!emojiRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "emoji", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "uuid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "nanoid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid2", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ulid", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "url", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "regex", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex2(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex2; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex2(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "duration", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP2(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ip", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT2(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "jwt", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr2(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cidr", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64url", - code: ZodIssueCode2.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode2.invalid_string, - ...errorUtil2.errToObj(message) - }); - } - _addCheck(check) { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil2.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil2.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil2.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil2.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil2.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil2.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil2.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil2.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil2.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil2.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil2.errToObj(message)); - } - trim() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString2.create = (params) => { - return new ZodString2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); -}; -function floatSafeRemainder2(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} - -class ZodNumber2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.number, - received: ctx2.parsedType - }); - return INVALID2; - } - let ctx = undefined; - const status = new ParseStatus2; - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util2.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder2(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodNumber2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil2.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil2.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil2.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil2.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber2.create = (params) => { - return new ZodNumber2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); -}; - -class ZodBigInt2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus2; - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.bigint, - received: ctx.parsedType - }); - return INVALID2; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodBigInt2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt2.create = (params) => { - return new ZodBigInt2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); -}; - -class ZodBoolean2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.boolean, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodBoolean2.create = (params) => { - return new ZodBoolean2({ - typeName: ZodFirstPartyTypeKind2.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); -}; - -class ZodDate2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.date, - received: ctx2.parsedType - }); - return INVALID2; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_date - }); - return INVALID2; - } - const status = new ParseStatus2; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new ZodDate2({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil2.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil2.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate2.create = (params) => { - return new ZodDate2({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind2.ZodDate, - ...processCreateParams2(params) - }); -}; - -class ZodSymbol2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.symbol, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodSymbol2.create = (params) => { - return new ZodSymbol2({ - typeName: ZodFirstPartyTypeKind2.ZodSymbol, - ...processCreateParams2(params) - }); -}; - -class ZodUndefined2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.undefined, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodUndefined2.create = (params) => { - return new ZodUndefined2({ - typeName: ZodFirstPartyTypeKind2.ZodUndefined, - ...processCreateParams2(params) - }); -}; - -class ZodNull2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.null, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodNull2.create = (params) => { - return new ZodNull2({ - typeName: ZodFirstPartyTypeKind2.ZodNull, - ...processCreateParams2(params) - }); -}; - -class ZodAny2 extends ZodType2 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK2(input.data); - } -} -ZodAny2.create = (params) => { - return new ZodAny2({ - typeName: ZodFirstPartyTypeKind2.ZodAny, - ...processCreateParams2(params) - }); -}; - -class ZodUnknown2 extends ZodType2 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK2(input.data); - } -} -ZodUnknown2.create = (params) => { - return new ZodUnknown2({ - typeName: ZodFirstPartyTypeKind2.ZodUnknown, - ...processCreateParams2(params) - }); -}; - -class ZodNever2 extends ZodType2 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.never, - received: ctx.parsedType - }); - return INVALID2; - } -} -ZodNever2.create = (params) => { - return new ZodNever2({ - typeName: ZodFirstPartyTypeKind2.ZodNever, - ...processCreateParams2(params) - }); -}; - -class ZodVoid2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.void, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); - } -} -ZodVoid2.create = (params) => { - return new ZodVoid2({ - typeName: ZodFirstPartyTypeKind2.ZodVoid, - ...processCreateParams2(params) - }); -}; - -class ZodArray2 extends ZodType2 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext2(ctx, { - code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus2.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - }); - return ParseStatus2.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray2({ - ...this._def, - minLength: { value: minLength, message: errorUtil2.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray2({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil2.toString(message) } - }); - } - length(len, message) { - return new ZodArray2({ - ...this._def, - exactLength: { value: len, message: errorUtil2.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray2.create = (schema, params) => { - return new ZodArray2({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind2.ZodArray, - ...processCreateParams2(params) - }); -}; -function deepPartialify2(schema) { - if (schema instanceof ZodObject2) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional2.create(deepPartialify2(fieldSchema)); - } - return new ZodObject2({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray2) { - return new ZodArray2({ - ...schema._def, - type: deepPartialify2(schema.element) - }); - } else if (schema instanceof ZodOptional2) { - return ZodOptional2.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodNullable2) { - return ZodNullable2.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodTuple2) { - return ZodTuple2.create(schema.items.map((item) => deepPartialify2(item))); - } else { - return schema; - } -} - -class ZodObject2 extends ZodType2 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util2.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.object, - received: ctx2.parsedType - }); - return INVALID2; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever2) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus2.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus2.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil2.errToObj; - return new ZodObject2({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil2.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject2({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject2({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject2({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject2({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind2.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject2({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util2.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify2(this); - } - partial(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject2({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional2) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject2({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum2(util2.objectKeys(this.shape)); - } -} -ZodObject2.create = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams2(params) - }); -}; -ZodObject2.strictCreate = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams2(params) - }); -}; -ZodObject2.lazycreate = (shape, params) => { - return new ZodObject2({ - shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams2(params) - }); -}; - -class ZodUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors - }); - return INVALID2; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError2(issues2)); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors - }); - return INVALID2; - } - } - get options() { - return this._def.options; - } -} -ZodUnion2.create = (types, params) => { - return new ZodUnion2({ - options: types, - typeName: ZodFirstPartyTypeKind2.ZodUnion, - ...processCreateParams2(params) - }); -}; -var getDiscriminator2 = (type) => { - if (type instanceof ZodLazy2) { - return getDiscriminator2(type.schema); - } else if (type instanceof ZodEffects2) { - return getDiscriminator2(type.innerType()); - } else if (type instanceof ZodLiteral2) { - return [type.value]; - } else if (type instanceof ZodEnum2) { - return type.options; - } else if (type instanceof ZodNativeEnum2) { - return util2.objectValues(type.enum); - } else if (type instanceof ZodDefault2) { - return getDiscriminator2(type._def.innerType); - } else if (type instanceof ZodUndefined2) { - return [undefined]; - } else if (type instanceof ZodNull2) { - return [null]; - } else if (type instanceof ZodOptional2) { - return [undefined, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodNullable2) { - return [null, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodBranded2) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodReadonly2) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodCatch2) { - return getDiscriminator2(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID2; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator2(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion2({ - typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams2(params) - }); - } -} -function mergeValues2(a, b) { - const aType = getParsedType2(a); - const bType = getParsedType2(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) { - const bKeys = util2.objectKeys(b); - const sharedKeys = util2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues2(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues2(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted2(parsedLeft) || isAborted2(parsedRight)) { - return INVALID2; - } - const merged = mergeValues2(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_intersection_types - }); - return INVALID2; - } - if (isDirty2(parsedLeft) || isDirty2(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection2.create = (left, right, params) => { - return new ZodIntersection2({ - left, - right, - typeName: ZodFirstPartyTypeKind2.ZodIntersection, - ...processCreateParams2(params) - }); -}; - -class ZodTuple2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID2; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath2(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus2.mergeArray(status, results); - }); - } else { - return ParseStatus2.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple2({ - ...this._def, - rest - }); - } -} -ZodTuple2.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple2({ - items: schemas, - typeName: ZodFirstPartyTypeKind2.ZodTuple, - rest: null, - ...processCreateParams2(params) - }); -}; - -class ZodRecord2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus2.mergeObjectAsync(status, pairs); - } else { - return ParseStatus2.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType2) { - return new ZodRecord2({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams2(third) - }); - } - return new ZodRecord2({ - keyType: ZodString2.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams2(second) - }); - } -} - -class ZodMap2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.map) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.map, - received: ctx.parsedType - }); - return INVALID2; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap2.create = (keyType, valueType, params) => { - return new ZodMap2({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind2.ZodMap, - ...processCreateParams2(params) - }); -}; - -class ZodSet2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.set) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.set, - received: ctx.parsedType - }); - return INVALID2; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID2; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet2({ - ...this._def, - minSize: { value: minSize, message: errorUtil2.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet2({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil2.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet2.create = (valueType, params) => { - return new ZodSet2({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind2.ZodSet, - ...processCreateParams2(params) - }); -}; - -class ZodFunction2 extends ZodType2 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.function) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.function, - received: ctx.parsedType - }); - return INVALID2; - } - function makeArgsIssue(args, error) { - return makeIssue2({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue2({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise2) { - const me = this; - return OK2(async function(...args) { - const error = new ZodError2([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK2(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction2({ - ...this._def, - args: ZodTuple2.create(items).rest(ZodUnknown2.create()) - }); - } - returns(returnType) { - return new ZodFunction2({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction2({ - args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), - returns: returns || ZodUnknown2.create(), - typeName: ZodFirstPartyTypeKind2.ZodFunction, - ...processCreateParams2(params) - }); - } -} - -class ZodLazy2 extends ZodType2 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy2.create = (getter, params) => { - return new ZodLazy2({ - getter, - typeName: ZodFirstPartyTypeKind2.ZodLazy, - ...processCreateParams2(params) - }); -}; - -class ZodLiteral2 extends ZodType2 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_literal, - expected: this._def.value - }); - return INVALID2; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral2.create = (value, params) => { - return new ZodLiteral2({ - value, - typeName: ZodFirstPartyTypeKind2.ZodLiteral, - ...processCreateParams2(params) - }); -}; -function createZodEnum2(values, params) { - return new ZodEnum2({ - values, - typeName: ZodFirstPartyTypeKind2.ZodEnum, - ...processCreateParams2(params) - }); -} - -class ZodEnum2 extends ZodType2 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID2; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID2; - } - return OK2(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum2.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum2.create = createZodEnum2; - -class ZodNativeEnum2 extends ZodType2 { - _parse(input) { - const nativeEnumValues = util2.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID2; - } - if (!this._cache) { - this._cache = new Set(util2.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID2; - } - return OK2(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum2.create = (values, params) => { - return new ZodNativeEnum2({ - values, - typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, - ...processCreateParams2(params) - }); -}; - -class ZodPromise2 extends ZodType2 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) { - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.promise, - received: ctx.parsedType - }); - return INVALID2; - } - const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data); - return OK2(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise2.create = (schema, params) => { - return new ZodPromise2({ - type: schema, - typeName: ZodFirstPartyTypeKind2.ZodPromise, - ...processCreateParams2(params) - }); -}; - -class ZodEffects2 extends ZodType2 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext2(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID2; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID2; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid2(base)) - return INVALID2; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid2(base)) - return INVALID2; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util2.assertNever(effect); - } -} -ZodEffects2.create = (schema, effect, params) => { - return new ZodEffects2({ - schema, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect, - ...processCreateParams2(params) - }); -}; -ZodEffects2.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects2({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - ...processCreateParams2(params) - }); -}; - -class ZodOptional2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType2.undefined) { - return OK2(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional2.create = (type, params) => { - return new ZodOptional2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodOptional, - ...processCreateParams2(params) - }); -}; - -class ZodNullable2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType2.null) { - return OK2(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable2.create = (type, params) => { - return new ZodNullable2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodNullable, - ...processCreateParams2(params) - }); -}; - -class ZodDefault2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType2.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault2.create = (type, params) => { - return new ZodDefault2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams2(params) - }); -}; - -class ZodCatch2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync2(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch2.create = (type, params) => { - return new ZodCatch2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams2(params) - }); -}; - -class ZodNaN2 extends ZodType2 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType2.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType2.nan, - received: ctx.parsedType - }); - return INVALID2; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN2.create = (params) => { - return new ZodNaN2({ - typeName: ZodFirstPartyTypeKind2.ZodNaN, - ...processCreateParams2(params) - }); -}; -var BRAND2 = Symbol("zod_brand"); - -class ZodBranded2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY2(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline2({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind2.ZodPipeline - }); - } -} - -class ZodReadonly2 extends ZodType2 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid2(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync2(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly2.create = (type, params) => { - return new ZodReadonly2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodReadonly, - ...processCreateParams2(params) - }); -}; -function cleanParams2(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom2(check, _params = {}, fatal) { - if (check) - return ZodAny2.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny2.create(); -} -var late2 = { - object: ZodObject2.lazycreate -}; -var ZodFirstPartyTypeKind2; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); -var instanceOfType2 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom2((data) => data instanceof cls, params); -var stringType2 = ZodString2.create; -var numberType2 = ZodNumber2.create; -var nanType2 = ZodNaN2.create; -var bigIntType2 = ZodBigInt2.create; -var booleanType2 = ZodBoolean2.create; -var dateType2 = ZodDate2.create; -var symbolType2 = ZodSymbol2.create; -var undefinedType2 = ZodUndefined2.create; -var nullType2 = ZodNull2.create; -var anyType2 = ZodAny2.create; -var unknownType2 = ZodUnknown2.create; -var neverType2 = ZodNever2.create; -var voidType2 = ZodVoid2.create; -var arrayType2 = ZodArray2.create; -var objectType2 = ZodObject2.create; -var strictObjectType2 = ZodObject2.strictCreate; -var unionType2 = ZodUnion2.create; -var discriminatedUnionType2 = ZodDiscriminatedUnion2.create; -var intersectionType2 = ZodIntersection2.create; -var tupleType2 = ZodTuple2.create; -var recordType2 = ZodRecord2.create; -var mapType2 = ZodMap2.create; -var setType2 = ZodSet2.create; -var functionType2 = ZodFunction2.create; -var lazyType2 = ZodLazy2.create; -var literalType2 = ZodLiteral2.create; -var enumType2 = ZodEnum2.create; -var nativeEnumType2 = ZodNativeEnum2.create; -var promiseType2 = ZodPromise2.create; -var effectsType2 = ZodEffects2.create; -var optionalType2 = ZodOptional2.create; -var nullableType2 = ZodNullable2.create; -var preprocessType2 = ZodEffects2.createWithPreprocess; -var pipelineType2 = ZodPipeline2.create; -var ostring2 = () => stringType2().optional(); -var onumber2 = () => numberType2().optional(); -var oboolean2 = () => booleanType2().optional(); -var coerce2 = { - string: (arg) => ZodString2.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber2.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean2.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt2.create({ ...arg, coerce: true }), - date: (arg) => ZodDate2.create({ ...arg, coerce: true }) -}; -var NEVER2 = INVALID2; -var SCHEMA_IDS2 = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema2 = exports_external2.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema2 = exports_external2.string().datetime(); -var NonEmptyStringSchema2 = exports_external2.string().trim().min(1); -var UriSchema2 = NonEmptyStringSchema2.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema2 = exports_external2.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema2 = exports_external2.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema2 = exports_external2.record(exports_external2.unknown()); -var TagsSchema2 = exports_external2.array(exports_external2.string().min(1)).default([]); -var OptionalTimestampSchema2 = TimestampSchema2.nullable().optional(); -var TerminalStatuses2 = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema2 = exports_external2.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema2(schema) { - return exports_external2.object({ - schema: exports_external2.literal(schema), - id: exports_external2.string().min(1), - createdAt: TimestampSchema2, - updatedAt: OptionalTimestampSchema2, - metadata: MetadataSchema2.optional() - }).strict(); -} -var ContractEnvelopeSchema2 = exports_external2.object({ - schema: SchemaIdSchema2, - id: exports_external2.string().min(1), - createdAt: TimestampSchema2, - updatedAt: OptionalTimestampSchema2, - metadata: MetadataSchema2.optional() -}).strict(); -var ActorKindSchema2 = exports_external2.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.actorRef).extend({ - kind: ActorKindSchema2, - name: exports_external2.string().min(1).optional(), - provider: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - machineId: exports_external2.string().min(1).optional(), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema2 = exports_external2.object({ - kind: ActorKindSchema2, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - provider: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - machineId: exports_external2.string().min(1).optional() -}).strict(); -var ResourceKindSchema2 = exports_external2.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.resourceRef).extend({ - kind: ResourceKindSchema2, - name: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema2 = exports_external2.object({ - kind: ResourceKindSchema2, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema2 = exports_external2.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema2 = exports_external2.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.evidenceRef).extend({ - kind: EvidenceKindSchema2, - uri: UriSchema2, - sha256: Sha256DigestSchema2.optional(), - summary: exports_external2.string().min(1).optional(), - contentType: exports_external2.string().min(1).optional(), - sizeBytes: exports_external2.number().int().nonnegative().optional(), - redaction: RedactionStateSchema2.default("unknown"), - producer: ActorPointerSchema2.optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - tags: TagsSchema2 -}).strict(); -var EvidencePointerSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: EvidenceKindSchema2.optional(), - uri: UriSchema2.optional(), - sha256: Sha256DigestSchema2.optional(), - summary: exports_external2.string().min(1).optional() -}).strict(); -var CostEstimateSchema2 = contractBaseSchema2(SCHEMA_IDS2.costEstimate).extend({ - currency: exports_external2.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external2.number().int().nonnegative(), - provider: exports_external2.string().min(1).optional(), - model: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - promptTokens: exports_external2.number().int().nonnegative().optional(), - completionTokens: exports_external2.number().int().nonnegative().optional(), - totalTokens: exports_external2.number().int().nonnegative().optional(), - basis: exports_external2.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema2 = exports_external2.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema2 = contractBaseSchema2(SCHEMA_IDS2.decisionEnvelope).extend({ - decisionType: exports_external2.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema2, - actor: ActorPointerSchema2.optional(), - traceId: exports_external2.string().min(1).optional(), - inputHash: HashStringSchema2.optional(), - policyBundleId: exports_external2.string().min(1).optional(), - selected: exports_external2.array(ResourcePointerSchema2).default([]), - skipped: exports_external2.array(ResourcePointerSchema2).default([]), - reason: exports_external2.string().min(1), - obligations: exports_external2.array(exports_external2.string().min(1)).default([]), - redactions: exports_external2.array(exports_external2.string().min(1)).default([]), - costEstimate: CostEstimateSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema2 = contractBaseSchema2(SCHEMA_IDS2.capabilityCard).extend({ - kind: exports_external2.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external2.string().min(1), - version: exports_external2.string().min(1).optional(), - status: exports_external2.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), - limitations: exports_external2.array(exports_external2.string().min(1)).default([]), - riskLevel: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict(); -var ProviderModeSchema2 = exports_external2.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema2 = exports_external2.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema2 = exports_external2.object({ - refName: NonEmptyStringSchema2, - requiredForModes: exports_external2.array(ProviderModeSchema2).min(1), - allowedSecretInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema2, - revocationCheck: exports_external2.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema2 = exports_external2.object({ - operation: NonEmptyStringSchema2, - supportedModes: exports_external2.array(ProviderModeSchema2).min(1), - sideEffectClass: ProviderSideEffectClassSchema2, - requiresApproval: exports_external2.boolean().default(false), - requiresIdempotencyKey: exports_external2.boolean().default(false), - requiresSandboxEvidence: exports_external2.boolean().default(false), - requiresRollbackOrRevocation: exports_external2.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema2.optional(), - noSideEffectSmoke: NonEmptyStringSchema2.optional(), - reconciliation: NonEmptyStringSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema2 = exports_external2.object({ - providerId: NonEmptyStringSchema2, - appId: NonEmptyStringSchema2, - adapterId: NonEmptyStringSchema2, - ownerPackage: NonEmptyStringSchema2, - modes: exports_external2.array(ProviderModeSchema2).min(1), - defaultMode: ProviderModeSchema2, - credentialRequirements: exports_external2.array(CredentialRequirementSchema2).default([]), - operations: exports_external2.array(ProviderOperationCardSchema2).min(1), - rateLimitPosture: NonEmptyStringSchema2, - costPosture: NonEmptyStringSchema2.optional(), - auditEvents: exports_external2.array(NonEmptyStringSchema2).default([]), - redactionRules: exports_external2.array(NonEmptyStringSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema2 = exports_external2.object({ - appId: NonEmptyStringSchema2, - repo: NonEmptyStringSchema2, - priority: exports_external2.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external2.array(NonEmptyStringSchema2).min(1), - firstOperations: exports_external2.array(NonEmptyStringSchema2).min(1), - blockedUntil: exports_external2.array(NonEmptyStringSchema2).default([]) -}).strict(); -var ProviderLiveModeStandardSchema2 = contractBaseSchema2(SCHEMA_IDS2.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema2, - version: NonEmptyStringSchema2, - modes: exports_external2.array(ProviderModeSchema2).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external2.array(NonEmptyStringSchema2).min(1), - liveMutationGate: exports_external2.object({ - requiredMode: exports_external2.literal("live_mutating"), - requiredChecks: exports_external2.array(NonEmptyStringSchema2).min(1), - forbiddenBypassSignals: exports_external2.array(NonEmptyStringSchema2).min(1), - disabledLiveSmoke: NonEmptyStringSchema2 - }).strict(), - noSideEffectSmoke: exports_external2.object({ - requiredForModes: exports_external2.array(ProviderModeSchema2).min(1), - commandEvidence: exports_external2.array(NonEmptyStringSchema2).min(1), - secretOutputScan: exports_external2.boolean().default(true) - }).strict(), - credentialPolicy: exports_external2.object({ - acceptedInputs: exports_external2.array(exports_external2.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external2.literal(false), - missingCredentialBehavior: exports_external2.literal("fail_closed"), - revocationCheckRequired: exports_external2.boolean().default(true) - }).strict(), - operationCards: exports_external2.array(ProviderCapabilityCardSchema2).min(1), - firstAdoptionTargets: exports_external2.array(ProviderLiveModeTargetSchema2).min(1), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1).optional(), - summary: exports_external2.string().min(1), - text: exports_external2.string().optional(), - tokens: exports_external2.number().int().nonnegative().optional(), - source: EvidencePointerSchema2, - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict(); -var ContextPackSchema2 = contractBaseSchema2(SCHEMA_IDS2.contextPack).extend({ - objective: exports_external2.string().min(1), - budget: exports_external2.object({ - maxTokens: exports_external2.number().int().positive().optional(), - maxBytes: exports_external2.number().int().positive().optional() - }).strict().optional(), - items: exports_external2.array(ContextPackItemSchema2).default([]), - citations: exports_external2.array(EvidencePointerSchema2).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external2.array(exports_external2.string().min(1)).default([]), - redactions: exports_external2.array(exports_external2.string().min(1)).default([]), - conflicts: exports_external2.array(exports_external2.string().min(1)).default([]), - uncertainty: exports_external2.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema2 = NonEmptyStringSchema2.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema2 = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema2 = exports_external2.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema2 = exports_external2.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema2 = exports_external2.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema2 = contractBaseSchema2(SCHEMA_IDS2.integrationRef).extend({ - kind: ProjectIntegrationKindSchema2, - name: exports_external2.string().min(1), - projectId: ProjectSlugSchema2.optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - externalId: NonEmptyStringSchema2.optional(), - uri: UriSchema2.optional(), - enabled: exports_external2.boolean().default(true), - readOnly: exports_external2.boolean().default(true), - capabilities: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - config: MetadataSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema2 = exports_external2.object({ - schemaRoot: RelativeProjectPathSchema2.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema2.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema2.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema2.default("documents"), - reportsDir: RelativeProjectPathSchema2.default("reports"), - evidenceDir: RelativeProjectPathSchema2.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema2.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectManifest).extend({ - projectId: ProjectSlugSchema2, - slug: ProjectSlugSchema2, - name: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - status: ProjectStatusSchema2.default("active"), - classification: ProjectClassificationSchema2.default("private"), - owner: ActorPointerSchema2.optional(), - layout: ProjectLayoutSchema2.default({}), - integrations: exports_external2.array(IntegrationRefSchema2).default([]), - renderManifests: exports_external2.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema2 = exports_external2.enum(["local", "package", "provider", "url"]); -var RenderImportSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: RenderImportKindSchema2, - specifier: exports_external2.string().min(1), - path: RelativeProjectPathSchema2.optional(), - packageName: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - provider: ProjectIntegrationKindSchema2.optional(), - schemaId: SchemaIdSchema2.optional(), - integrity: HashStringSchema2.optional(), - resourceRef: ResourcePointerSchema2.optional(), - optional: exports_external2.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema2 = exports_external2.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1), - kind: RenderViewKindSchema2, - default: exports_external2.boolean().default(false), - entry: RelativeProjectPathSchema2.optional(), - imports: exports_external2.array(RenderImportSchema2).default([]), - panelRefs: exports_external2.array(ResourcePointerSchema2).default([]), - dataRefs: exports_external2.array(ResourcePointerSchema2).default([]), - layout: MetadataSchema2.optional() -}).strict(); -var RenderManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.renderManifest).extend({ - projectId: ProjectSlugSchema2, - name: exports_external2.string().min(1), - version: exports_external2.string().min(1), - manifestPath: RelativeProjectPathSchema2.default(".hasna/project/dashboard.render.json"), - renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external2.array(RenderViewSchema2).min(1), - imports: exports_external2.array(RenderImportSchema2).default([]), - theme: MetadataSchema2.optional(), - compatibility: exports_external2.object({ - minProjectsVersion: exports_external2.string().min(1).optional(), - minContractsVersion: exports_external2.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema2 = exports_external2.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema2 = exports_external2.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - label: exports_external2.string().min(1), - value: exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]), - unit: exports_external2.string().min(1).optional(), - status: exports_external2.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict(); -var ProjectPanelItemSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - title: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - status: exports_external2.string().min(1).optional(), - priority: exports_external2.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema2.optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - metadata: MetadataSchema2.optional() -}).strict(); -var ProjectRenderFragmentSchema2 = exports_external2.object({ - renderer: exports_external2.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external2.string().min(1).optional(), - entry: RelativeProjectPathSchema2.optional(), - imports: exports_external2.array(RenderImportSchema2).default([]), - spec: MetadataSchema2.default({}) -}).strict(); -var ProjectPanelSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectPanel).extend({ - projectId: ProjectSlugSchema2, - provider: exports_external2.object({ - kind: ProjectIntegrationKindSchema2, - id: exports_external2.string().min(1), - name: exports_external2.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema2.optional(), - externalId: NonEmptyStringSchema2.optional() - }).strict(), - kind: ProjectPanelKindSchema2, - title: exports_external2.string().min(1), - summary: exports_external2.string().min(1).optional(), - state: ProjectPanelStateSchema2.default("ready"), - stateReason: exports_external2.string().min(1).optional(), - generatedAt: TimestampSchema2, - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external2.array(ProjectPanelMetricSchema2).default([]), - items: exports_external2.array(ProjectPanelItemSchema2).default([]), - actions: exports_external2.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - renderFragment: ProjectRenderFragmentSchema2.optional(), - warnings: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema2 = contractBaseSchema2(SCHEMA_IDS2.projectSnapshot).extend({ - projectId: ProjectSlugSchema2, - generatedAt: TimestampSchema2, - status: ContractStatusSchema2.default("unknown"), - manifestRef: ResourcePointerSchema2, - renderManifestRef: ResourcePointerSchema2.optional(), - panels: exports_external2.array(ProjectPanelSchema2).default([]), - contextPacks: exports_external2.array(ContextPackSchema2).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema2).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - warnings: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: exports_external2.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external2.boolean().default(true), - command: exports_external2.string().min(1).optional(), - expected: exports_external2.string().min(1).optional(), - timeoutMs: exports_external2.number().int().positive().optional(), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema2 = contractBaseSchema2(SCHEMA_IDS2.validationPlan).extend({ - objective: exports_external2.string().min(1), - subject: ResourcePointerSchema2.optional(), - checks: exports_external2.array(ValidationCheckSchema2).min(1), - verifier: ActorPointerSchema2.optional(), - requiredEvidenceKinds: exports_external2.array(EvidenceKindSchema2).default([]) -}).strict(); -var ScaffoldTypeSchema2 = exports_external2.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema2 = exports_external2.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema2 = exports_external2.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema2 = exports_external2.object({ - key: exports_external2.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external2.string().min(1), - required: exports_external2.boolean().default(false), - ["secret"]: exports_external2.boolean().default(false), - group: exports_external2.string().min(1).optional(), - default: exports_external2.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema2 = exports_external2.object({ - name: exports_external2.string().min(1), - command: exports_external2.string().min(1), - description: exports_external2.string().min(1).optional(), - required: exports_external2.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema2 = exports_external2.object({ - packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external2.array(exports_external2.string().min(1)).default([]), - requiredFiles: exports_external2.array(exports_external2.string().min(1)).default([]), - requiredDirectories: exports_external2.array(exports_external2.string().min(1)).default([]), - optionalDirectories: exports_external2.array(exports_external2.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.scaffoldManifest).extend({ - name: exports_external2.string().min(1), - version: exports_external2.string().min(1), - summary: exports_external2.string().min(1), - type: ScaffoldTypeSchema2, - status: ScaffoldStatusSchema2.default("draft"), - capabilities: exports_external2.array(ScaffoldCapabilitySchema2).default([]), - techStack: exports_external2.array(exports_external2.string().min(1)).default([]), - tags: TagsSchema2, - source: ResourcePointerSchema2.optional(), - output: ScaffoldOutputShapeSchema2, - env: exports_external2.array(ScaffoldEnvVarSchema2).default([]), - scripts: exports_external2.array(ScaffoldScriptSchema2).default([]), - validationChecks: exports_external2.array(ValidationCheckSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema2 = exports_external2.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema2 = contractBaseSchema2(SCHEMA_IDS2.scaffoldInstallRecord).extend({ - scaffoldId: exports_external2.string().min(1), - scaffoldVersion: exports_external2.string().min(1).optional(), - manifestRef: ResourcePointerSchema2.optional(), - target: ResourcePointerSchema2, - status: ScaffoldInstallStatusSchema2, - installedAt: TimestampSchema2.optional(), - installer: ActorPointerSchema2.optional(), - packageManager: exports_external2.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema2.optional(), - generatedFiles: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema2 = exports_external2.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema2 = exports_external2.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema2 = exports_external2.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema2 = exports_external2.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema2 = NonEmptyStringSchema2.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema2 = exports_external2.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema2 = exports_external2.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema2 = exports_external2.object({ - transport: exports_external2.enum(["http", "stdio"]).default("http"), - bin: exports_external2.string().min(1).optional(), - url: UriSchema2.optional() -}).strict(); -var AppHttpSurfaceSchema2 = exports_external2.object({ - healthPath: exports_external2.string().min(1).default("/health"), - port: exports_external2.number().int().positive().optional(), - baseUrl: UriSchema2.optional() -}).strict(); -var AppSurfacesSchema2 = exports_external2.object({ - bins: exports_external2.array(exports_external2.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema2.optional(), - http: AppHttpSurfaceSchema2.optional() -}).strict(); -var AppSchema2 = contractBaseSchema2(SCHEMA_IDS2.app).extend({ - appId: AppIdSchema2, - npmName: NpmPackageNameSchema2, - repoFolder: AppIdSchema2, - githubUrl: GithubUrlSchema2, - projectSlug: ProjectSlugSchema2, - surfaces: AppSurfacesSchema2.default({}), - lifecycle: AppLifecycleSchema2, - releaseChannel: ReleaseChannelSchema2.default("stable"), - summary: exports_external2.string().min(1).optional(), - tags: TagsSchema2 -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema2 = exports_external2.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema2 = contractBaseSchema2(SCHEMA_IDS2.release).extend({ - appId: AppIdSchema2, - package: NpmPackageNameSchema2, - version: SemverSchema2, - gitSha: GitShaSchema2, - publishedAt: TimestampSchema2, - publishPath: PublishPathSchema2, - changelogRef: ResourcePointerSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema2 = exports_external2.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema2 = exports_external2.object({ - cliVersion: exports_external2.string().min(1).optional(), - mcpHealth: exports_external2.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema2 = contractBaseSchema2(SCHEMA_IDS2.rolloutRecord).extend({ - appId: AppIdSchema2, - package: NpmPackageNameSchema2, - version: SemverSchema2, - machine: NonEmptyStringSchema2, - action: RolloutActionSchema2, - result: ContractStatusSchema2, - verifiedBy: RolloutVerificationSchema2.optional(), - at: TimestampSchema2, - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema2 = exports_external2.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema2 = exports_external2.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema2 = exports_external2.object({ - channel: AnnouncementChannelKindSchema2, - status: AnnouncementDeliveryStatusSchema2, - deliveredAt: TimestampSchema2.optional(), - detail: exports_external2.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema2 = contractBaseSchema2(SCHEMA_IDS2.announcement).extend({ - campaignId: NonEmptyStringSchema2, - appId: AppIdSchema2.optional(), - releaseRef: ResourcePointerSchema2.optional(), - channels: exports_external2.array(AnnouncementChannelSchema2).min(1), - audienceRef: ResourcePointerSchema2, - sentAt: TimestampSchema2 -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema2 = exports_external2.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema2 = exports_external2.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema2 = exports_external2.union([exports_external2.string(), exports_external2.number(), exports_external2.boolean()]); -var AudiencePredicateSchema2 = exports_external2.object({ - kind: AudiencePredicateKindSchema2, - key: exports_external2.string().min(1).optional(), - op: AudiencePredicateOpSchema2.default("eq"), - value: AudiencePredicateValueSchema2.optional(), - values: exports_external2.array(AudiencePredicateValueSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema2 = exports_external2.object({ - match: exports_external2.enum(["all", "any"]).default("all"), - predicates: exports_external2.array(AudiencePredicateSchema2).min(1) -}).strict(); -var ConsentPolicySchema2 = exports_external2.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema2 = contractBaseSchema2(SCHEMA_IDS2.audience).extend({ - audienceId: AppIdSchema2, - name: NonEmptyStringSchema2, - definition: AudienceDefinitionSchema2, - consentPolicy: ConsentPolicySchema2, - suppressionSyncedAt: OptionalTimestampSchema2 -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES2 = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema2 = exports_external2.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - provider: AppCloudProviderSchema2, - kind: exports_external2.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external2.string().min(1), - region: exports_external2.string().min(1).optional(), - accountId: exports_external2.string().min(1).optional(), - uri: UriSchema2.optional(), - machineScoped: exports_external2.boolean().default(false) -}).strict(); -var AppCloudManifestSchema2 = contractBaseSchema2(SCHEMA_IDS2.appCloudManifest).extend({ - packageName: exports_external2.string().min(1), - packageVersion: exports_external2.string().min(1).optional(), - appId: exports_external2.string().min(1), - repository: ResourcePointerSchema2.optional(), - storageMode: exports_external2.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external2.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external2.array(AppCloudResourceSchema2).default([]), - localCache: exports_external2.object({ - path: exports_external2.string().min(1).optional(), - pullMode: exports_external2.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external2.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external2.array(exports_external2.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES2]), - dependencies: exports_external2.array(exports_external2.string().min(1)).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES2, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES2) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema2 = exports_external2.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema2 = exports_external2.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: NoCloudCheckKindSchema2, - severity: NoCloudFindingSeveritySchema2, - path: exports_external2.string().min(1).optional(), - packageName: exports_external2.string().min(1).optional(), - pattern: exports_external2.string().min(1), - message: exports_external2.string().min(1), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict(); -var NoCloudCheckResultSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: NoCloudCheckKindSchema2, - status: ContractStatusSchema2, - target: exports_external2.string().min(1), - command: exports_external2.string().min(1).optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - findings: exports_external2.array(NoCloudFindingSchema2).default([]) -}).strict(); -var NoCloudEvidencePackSchema2 = contractBaseSchema2(SCHEMA_IDS2.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema2, - packageName: exports_external2.string().min(1).optional(), - packageVersion: exports_external2.string().min(1).optional(), - generatedBy: ActorPointerSchema2.optional(), - scanMode: exports_external2.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema2, - verdict: exports_external2.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema2.optional(), - checks: exports_external2.array(NoCloudCheckResultSchema2).min(1), - findings: exports_external2.array(NoCloudFindingSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check) => check.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check) => check.status !== "succeeded")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check) => check.status === "failed")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check, index) => { - const checkBlockingFindings = check.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema2 = exports_external2.object({ - checkId: exports_external2.string().min(1), - status: ContractStatusSchema2, - summary: exports_external2.string().min(1).optional(), - startedAt: OptionalTimestampSchema2, - finishedAt: OptionalTimestampSchema2, - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict(); -var ProofBundleSchema2 = contractBaseSchema2(SCHEMA_IDS2.proofBundle).extend({ - subject: ResourcePointerSchema2, - validationPlanRef: ResourcePointerSchema2.optional(), - status: ContractStatusSchema2, - verdict: exports_external2.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external2.array(ProofCheckResultSchema2).default([]), - verifier: ActorPointerSchema2.optional(), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - residualRisks: exports_external2.array(exports_external2.string().min(1)).default([]), - freshness: exports_external2.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check, index) => { - if (check.status !== "succeeded") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check) => check.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check) => check.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema2 = contractBaseSchema2(SCHEMA_IDS2.workRun).extend({ - objective: exports_external2.string().min(1), - status: ContractStatusSchema2, - actor: ActorPointerSchema2, - traceId: exports_external2.string().min(1).optional(), - startedAt: OptionalTimestampSchema2, - finishedAt: OptionalTimestampSchema2, - constraints: exports_external2.array(exports_external2.string().min(1)).default([]), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - decisions: exports_external2.array(DecisionEnvelopeSchema2).default([]), - costEstimates: exports_external2.array(CostEstimateSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - validationPlanRefs: exports_external2.array(ResourcePointerSchema2).default([]), - proofBundleRefs: exports_external2.array(ResourcePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses2.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - at: TimestampSchema2, - kind: exports_external2.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external2.string().min(1), - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]), - costEstimate: CostEstimateSchema2.optional() -}).strict(); -var AgentTrajectorySchema2 = contractBaseSchema2(SCHEMA_IDS2.agentTrajectory).extend({ - actor: ActorPointerSchema2, - workRunRef: ResourcePointerSchema2.optional(), - events: exports_external2.array(TrajectoryEventSchema2).default([]), - outcome: exports_external2.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema2.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION2 = "v1"; -var RepoClassSchema2 = exports_external2.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES2 = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema2 = exports_external2.enum(DEPLOYMENT_MODES2); -var ServiceSurfaceStatusSchema2 = exports_external2.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema2 = exports_external2.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema2 = exports_external2.object({ - method: exports_external2.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external2.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external2.boolean().default(false), - description: exports_external2.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema2 = exports_external2.object({ - id: exports_external2.string().min(1), - kind: exports_external2.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external2.boolean().default(true), - command: exports_external2.string().min(1).optional(), - evidenceRef: EvidencePointerSchema2.optional(), - status: exports_external2.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external2.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema2 = exports_external2.object({ - name: exports_external2.string().min(1), - status: ServiceSurfaceStatusSchema2, - bin: exports_external2.string().min(1).optional(), - mcpBin: exports_external2.string().min(1).optional(), - authMode: ServiceAuthModeSchema2, - deploymentModes: exports_external2.array(DeploymentModeSchema2).min(1), - health: ServiceEndpointSchema2.optional(), - readiness: ServiceEndpointSchema2.optional(), - version: ServiceEndpointSchema2.optional(), - apiBasePath: exports_external2.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external2.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external2.string().min(1).optional(), - readinessGates: exports_external2.array(DeploymentReadinessGateSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES2 = ["local", "cloud"]; -var StorageModeSchema2 = exports_external2.enum(STORAGE_MODES2); -var AppNameSchema2 = exports_external2.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES2 = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName2(name) { - return ALLOWED_BIN_SUFFIXES2.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor2(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema2 = exports_external2.object({ - mode: StorageModeSchema2, - envPrefix: exports_external2.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external2.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external2.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external2.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema2 = exports_external2.object({ - $schema: exports_external2.string().min(1).optional(), - schema: exports_external2.literal(SCHEMA_IDS2.serviceContract), - name: AppNameSchema2, - class: RepoClassSchema2, - contractVersion: exports_external2.literal(SERVICE_CONTRACT_VERSION2), - kitVersion: exports_external2.string().min(1), - description: exports_external2.string().min(1).optional(), - bins: exports_external2.array(exports_external2.string().min(1)).default([]), - storage: StorageContractSchema2.optional(), - deploymentModes: exports_external2.array(DeploymentModeSchema2).default(["local"]), - serviceSurfaces: exports_external2.array(ServiceSurfaceSchema2).default([]), - metadata: MetadataSchema2.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName2(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); - } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); - } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); - } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor2(value.name)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor2(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); - } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); - } - } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); - } - } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } - } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } - } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external2.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); - } - } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } - } - } -}); -var HealthResponseSchema2 = exports_external2.object({ - status: exports_external2.enum(["ok", "degraded", "unavailable"]), - version: exports_external2.string().min(1), - mode: StorageModeSchema2 -}).strict(); -var ReadyResponseSchema2 = exports_external2.object({ - ready: exports_external2.boolean(), - reason: exports_external2.string().min(1).optional() -}).strict(); -var VersionResponseSchema2 = exports_external2.object({ - version: exports_external2.string().min(1) -}).strict(); -var CommsSeveritySchema2 = exports_external2.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema2 = exports_external2.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); -var COMMS_SEVERITY_TAGS2 = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema2 = exports_external2.enum(COMMS_SEVERITY_TAGS2); -var CommsScopeSchema2 = exports_external2.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsEventEnvelope).extend({ - type: CommsEventTypeSchema2, - severity: CommsSeveritySchema2, - scope: CommsScopeSchema2, - summary: exports_external2.string().min(1).optional(), - source: ActorPointerSchema2.optional(), - affected_packages: exports_external2.array(NonEmptyStringSchema2).default([]), - affected_machines: exports_external2.array(NonEmptyStringSchema2).default([]), - action_required: exports_external2.boolean().default(false), - ack_by: TimestampSchema2.optional(), - dedupe_key: NonEmptyStringSchema2, - resourceRefs: exports_external2.array(ResourcePointerSchema2).default([]), - evidenceRefs: exports_external2.array(EvidencePointerSchema2).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); - } - } -}); -var CommsChannelClassSchema2 = exports_external2.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema2 = exports_external2.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema2 = NonEmptyStringSchema2.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); -var CommsChannelMetadataSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsChannelMetadata).extend({ - class: CommsChannelClassSchema2, - noise: CommsChannelNoiseSchema2.optional(), - owner: NonEmptyStringSchema2.optional(), - until: CommsUntilHorizonSchema2.optional(), - successor: NonEmptyStringSchema2.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); - } - } -}); -var COMMS_SEVERITY_TAG_INFO2 = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema2 = contractBaseSchema2(SCHEMA_IDS2.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema2, - envelope: CommsEventEnvelopeSchema2 -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO2[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO2)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external2.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] - }); - } - } -}); -var ContractSchemaRegistry2 = { - [SCHEMA_IDS2.actorRef]: ActorRefSchema2, - [SCHEMA_IDS2.resourceRef]: ResourceRefSchema2, - [SCHEMA_IDS2.evidenceRef]: EvidenceRefSchema2, - [SCHEMA_IDS2.workRun]: WorkRunSchema2, - [SCHEMA_IDS2.decisionEnvelope]: DecisionEnvelopeSchema2, - [SCHEMA_IDS2.costEstimate]: CostEstimateSchema2, - [SCHEMA_IDS2.capabilityCard]: CapabilityCardSchema2, - [SCHEMA_IDS2.providerLiveModeStandard]: ProviderLiveModeStandardSchema2, - [SCHEMA_IDS2.contextPack]: ContextPackSchema2, - [SCHEMA_IDS2.integrationRef]: IntegrationRefSchema2, - [SCHEMA_IDS2.projectManifest]: ProjectManifestSchema2, - [SCHEMA_IDS2.projectPanel]: ProjectPanelSchema2, - [SCHEMA_IDS2.projectSnapshot]: ProjectSnapshotSchema2, - [SCHEMA_IDS2.renderManifest]: RenderManifestSchema2, - [SCHEMA_IDS2.agentTrajectory]: AgentTrajectorySchema2, - [SCHEMA_IDS2.validationPlan]: ValidationPlanSchema2, - [SCHEMA_IDS2.proofBundle]: ProofBundleSchema2, - [SCHEMA_IDS2.scaffoldManifest]: ScaffoldManifestSchema2, - [SCHEMA_IDS2.scaffoldInstallRecord]: ScaffoldInstallRecordSchema2, - [SCHEMA_IDS2.appCloudManifest]: AppCloudManifestSchema2, - [SCHEMA_IDS2.noCloudEvidencePack]: NoCloudEvidencePackSchema2, - [SCHEMA_IDS2.serviceContract]: ServiceContractManifestSchema2, - [SCHEMA_IDS2.commsEventEnvelope]: CommsEventEnvelopeSchema2, - [SCHEMA_IDS2.commsChannelMetadata]: CommsChannelMetadataSchema2, - [SCHEMA_IDS2.commsMessageMetadata]: CommsMessageMetadataSchema2, - [SCHEMA_IDS2.app]: AppSchema2, - [SCHEMA_IDS2.release]: ReleaseSchema2, - [SCHEMA_IDS2.rolloutRecord]: RolloutRecordSchema2, - [SCHEMA_IDS2.announcement]: AnnouncementSchema2, - [SCHEMA_IDS2.audience]: AudienceSchema2 -}; -function envToken2(name) { - return name.toUpperCase().replace(/-/g, "_"); -} -function clientTransportEnvKeys2(name) { - const envSegment = envToken2(name); - return { - modeKeys: [ - `HASNA_${envSegment}_STORAGE_MODE`, - `HASNA_${envSegment}_MODE`, - `${envSegment}_STORAGE_MODE`, - `${envSegment}_MODE` - ], - apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], - apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] - }; -} -var IDEMPOTENT_METHODS2 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); - -// node_modules/@hasna/contracts/dist/mode.js -var __defProp4 = Object.defineProperty; -var __returnValue4 = (v) => v; -function __exportSetter4(name, newValue) { - this[name] = __returnValue4.bind(null, newValue); -} -var __export4 = (target, all) => { - for (var name in all) - __defProp4(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: __exportSetter4.bind(all, name) - }); -}; -var exports_external3 = {}; -__export4(exports_external3, { - void: () => voidType3, - util: () => util3, - unknown: () => unknownType3, - union: () => unionType3, - undefined: () => undefinedType3, - tuple: () => tupleType3, - transformer: () => effectsType3, - symbol: () => symbolType3, - string: () => stringType3, - strictObject: () => strictObjectType3, - setErrorMap: () => setErrorMap3, - set: () => setType3, - record: () => recordType3, - quotelessJson: () => quotelessJson3, - promise: () => promiseType3, - preprocess: () => preprocessType3, - pipeline: () => pipelineType3, - ostring: () => ostring3, - optional: () => optionalType3, - onumber: () => onumber3, - oboolean: () => oboolean3, - objectUtil: () => objectUtil3, - object: () => objectType3, - number: () => numberType3, - nullable: () => nullableType3, - null: () => nullType3, - never: () => neverType3, - nativeEnum: () => nativeEnumType3, - nan: () => nanType3, - map: () => mapType3, - makeIssue: () => makeIssue3, - literal: () => literalType3, - lazy: () => lazyType3, - late: () => late3, - isValid: () => isValid3, - isDirty: () => isDirty3, - isAsync: () => isAsync3, - isAborted: () => isAborted3, - intersection: () => intersectionType3, - instanceof: () => instanceOfType3, - getParsedType: () => getParsedType3, - getErrorMap: () => getErrorMap3, - function: () => functionType3, - enum: () => enumType3, - effect: () => effectsType3, - discriminatedUnion: () => discriminatedUnionType3, - defaultErrorMap: () => en_default3, - datetimeRegex: () => datetimeRegex3, - date: () => dateType3, - custom: () => custom3, - coerce: () => coerce3, - boolean: () => booleanType3, - bigint: () => bigIntType3, - array: () => arrayType3, - any: () => anyType3, - addIssueToContext: () => addIssueToContext3, - ZodVoid: () => ZodVoid3, - ZodUnknown: () => ZodUnknown3, - ZodUnion: () => ZodUnion3, - ZodUndefined: () => ZodUndefined3, - ZodType: () => ZodType3, - ZodTuple: () => ZodTuple3, - ZodTransformer: () => ZodEffects3, - ZodSymbol: () => ZodSymbol3, - ZodString: () => ZodString3, - ZodSet: () => ZodSet3, - ZodSchema: () => ZodType3, - ZodRecord: () => ZodRecord3, - ZodReadonly: () => ZodReadonly3, - ZodPromise: () => ZodPromise3, - ZodPipeline: () => ZodPipeline3, - ZodParsedType: () => ZodParsedType3, - ZodOptional: () => ZodOptional3, - ZodObject: () => ZodObject3, - ZodNumber: () => ZodNumber3, - ZodNullable: () => ZodNullable3, - ZodNull: () => ZodNull3, - ZodNever: () => ZodNever3, - ZodNativeEnum: () => ZodNativeEnum3, - ZodNaN: () => ZodNaN3, - ZodMap: () => ZodMap3, - ZodLiteral: () => ZodLiteral3, - ZodLazy: () => ZodLazy3, - ZodIssueCode: () => ZodIssueCode3, - ZodIntersection: () => ZodIntersection3, - ZodFunction: () => ZodFunction3, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind3, - ZodError: () => ZodError3, - ZodEnum: () => ZodEnum3, - ZodEffects: () => ZodEffects3, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion3, - ZodDefault: () => ZodDefault3, - ZodDate: () => ZodDate3, - ZodCatch: () => ZodCatch3, - ZodBranded: () => ZodBranded3, - ZodBoolean: () => ZodBoolean3, - ZodBigInt: () => ZodBigInt3, - ZodArray: () => ZodArray3, - ZodAny: () => ZodAny3, - Schema: () => ZodType3, - ParseStatus: () => ParseStatus3, - OK: () => OK3, - NEVER: () => NEVER3, - INVALID: () => INVALID3, - EMPTY_PATH: () => EMPTY_PATH3, - DIRTY: () => DIRTY3, - BRAND: () => BRAND3 -}); -var util3; -(function(util22) { - util22.assertEqual = (_) => {}; - function assertIs(_arg) {} - util22.assertIs = assertIs; - function assertNever(_x) { - throw new Error; - } - util22.assertNever = assertNever; - util22.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util22.getValidEnumValues = (obj) => { - const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util22.objectValues(filtered); - }; - util22.objectValues = (obj) => { - return util22.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util22.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return; - }; - util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util22.joinValues = joinValues; - util22.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util3 || (util3 = {})); -var objectUtil3; -(function(objectUtil22) { - objectUtil22.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; -})(objectUtil3 || (objectUtil3 = {})); -var ZodParsedType3 = util3.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType3 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType3.undefined; - case "string": - return ZodParsedType3.string; - case "number": - return Number.isNaN(data) ? ZodParsedType3.nan : ZodParsedType3.number; - case "boolean": - return ZodParsedType3.boolean; - case "function": - return ZodParsedType3.function; - case "bigint": - return ZodParsedType3.bigint; - case "symbol": - return ZodParsedType3.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType3.array; - } - if (data === null) { - return ZodParsedType3.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType3.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType3.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType3.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType3.date; - } - return ZodParsedType3.object; - default: - return ZodParsedType3.unknown; - } -}; -var ZodIssueCode3 = util3.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson3 = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; - -class ZodError3 extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError3)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util3.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError3.create = (issues) => { - const error = new ZodError3(issues); - return error; -}; -var errorMap3 = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode3.invalid_type: - if (issue.received === ZodParsedType3.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode3.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util3.jsonStringifyReplacer)}`; - break; - case ZodIssueCode3.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util3.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode3.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode3.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util3.joinValues(issue.options)}`; - break; - case ZodIssueCode3.invalid_enum_value: - message = `Invalid enum value. Expected ${util3.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode3.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode3.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode3.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode3.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util3.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode3.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode3.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode3.custom: - message = `Invalid input`; - break; - case ZodIssueCode3.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode3.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode3.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util3.assertNever(issue); - } - return { message }; -}; -var en_default3 = errorMap3; -var overrideErrorMap3 = en_default3; -function setErrorMap3(map) { - overrideErrorMap3 = map; -} -function getErrorMap3() { - return overrideErrorMap3; -} -var makeIssue3 = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH3 = []; -function addIssueToContext3(ctx, issueData) { - const overrideMap = getErrorMap3(); - const issue = makeIssue3({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default3 ? undefined : en_default3 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); -} - -class ParseStatus3 { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID3; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus3.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID3; - if (value.status === "aborted") - return INVALID3; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -var INVALID3 = Object.freeze({ - status: "aborted" -}); -var DIRTY3 = (value) => ({ status: "dirty", value }); -var OK3 = (value) => ({ status: "valid", value }); -var isAborted3 = (x) => x.status === "aborted"; -var isDirty3 = (x) => x.status === "dirty"; -var isValid3 = (x) => x.status === "valid"; -var isAsync3 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var errorUtil3; -(function(errorUtil22) { - errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil3 || (errorUtil3 = {})); - -class ParseInputLazyPath3 { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -var handleResult3 = (ctx, result) => { - if (isValid3(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError3(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams3(params) { - if (!params) - return {}; - const { errorMap: errorMap22, invalid_type_error, required_error, description } = params; - if (errorMap22 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap22) - return { errorMap: errorMap22, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -class ZodType3 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType3(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType3(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus3, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType3(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync3(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult3(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid3(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid3(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType3(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync3(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult3(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode3.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects3({ - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional3.create(this, this._def); - } - nullable() { - return ZodNullable3.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray3.create(this); - } - promise() { - return ZodPromise3.create(this, this._def); - } - or(option) { - return ZodUnion3.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection3.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects3({ - ...processCreateParams3(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault3({ - ...processCreateParams3(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodDefault - }); - } - brand() { - return new ZodBranded3({ - typeName: ZodFirstPartyTypeKind3.ZodBranded, - type: this, - ...processCreateParams3(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch3({ - ...processCreateParams3(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline3.create(this, target); - } - readonly() { - return ZodReadonly3.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -var cuidRegex3 = /^c[^\s-]{8,}$/i; -var cuid2Regex3 = /^[0-9a-z]+$/; -var ulidRegex3 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex3 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex3 = /^[a-z0-9_-]{21}$/i; -var jwtRegex3 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex3 = /^[-+]?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)?)??$/; -var emailRegex3 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex3; -var ipv4Regex3 = /^(?:(?: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])$/; -var ipv4CidrRegex3 = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex3 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex3 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex3 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex3 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource3 = `((\\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])))`; -var dateRegex3 = new RegExp(`^${dateRegexSource3}$`); -function timeRegexSource3(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex3(args) { - return new RegExp(`^${timeRegexSource3(args)}$`); -} -function datetimeRegex3(args) { - let regex = `${dateRegexSource3}T${timeRegexSource3(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP3(ip, version) { - if ((version === "v4" || !version) && ipv4Regex3.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex3.test(ip)) { - return true; - } - return false; -} -function isValidJWT3(jwt, alg) { - if (!jwtRegex3.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr3(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex3.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex3.test(ip)) { - return true; - } - return false; -} - -class ZodString3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.string, - received: ctx2.parsedType - }); - return INVALID3; - } - const status = new ParseStatus3; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "email", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex3) { - emojiRegex3 = new RegExp(_emojiRegex3, "u"); - } - if (!emojiRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "emoji", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "uuid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "nanoid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cuid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cuid2", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "ulid", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "url", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "regex", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex3(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex3; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex3(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "duration", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP3(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "ip", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT3(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "jwt", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr3(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "cidr", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "base64", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - validation: "base64url", - code: ZodIssueCode3.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode3.invalid_string, - ...errorUtil3.errToObj(message) - }); - } - _addCheck(check) { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil3.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil3.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil3.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil3.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil3.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil3.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil3.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil3.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil3.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil3.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil3.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil3.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil3.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil3.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil3.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil3.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil3.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil3.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil3.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil3.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil3.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil3.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil3.errToObj(message) - }); - } - nonempty(message) { - return this.min(1, errorUtil3.errToObj(message)); - } - trim() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString3({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString3.create = (params) => { - return new ZodString3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams3(params) - }); -}; -function floatSafeRemainder3(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} - -class ZodNumber3 extends ZodType3 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.number, - received: ctx2.parsedType - }); - return INVALID3; - } - let ctx = undefined; - const status = new ParseStatus3; - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util3.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder3(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil3.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil3.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil3.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil3.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber3({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil3.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodNumber3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil3.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil3.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil3.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil3.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil3.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil3.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil3.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil3.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil3.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util3.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber3.create = (params) => { - return new ZodNumber3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams3(params) - }); -}; - -class ZodBigInt3 extends ZodType3 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus3; - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.bigint, - received: ctx.parsedType - }); - return INVALID3; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil3.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil3.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil3.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil3.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt3({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil3.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodBigInt3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil3.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil3.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil3.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil3.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil3.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt3.create = (params) => { - return new ZodBigInt3({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams3(params) - }); -}; - -class ZodBoolean3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.boolean, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodBoolean3.create = (params) => { - return new ZodBoolean3({ - typeName: ZodFirstPartyTypeKind3.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams3(params) - }); -}; - -class ZodDate3 extends ZodType3 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.date, - received: ctx2.parsedType - }); - return INVALID3; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_date - }); - return INVALID3; - } - const status = new ParseStatus3; - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util3.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new ZodDate3({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil3.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil3.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate3.create = (params) => { - return new ZodDate3({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind3.ZodDate, - ...processCreateParams3(params) - }); -}; - -class ZodSymbol3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.symbol, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodSymbol3.create = (params) => { - return new ZodSymbol3({ - typeName: ZodFirstPartyTypeKind3.ZodSymbol, - ...processCreateParams3(params) - }); -}; - -class ZodUndefined3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.undefined, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodUndefined3.create = (params) => { - return new ZodUndefined3({ - typeName: ZodFirstPartyTypeKind3.ZodUndefined, - ...processCreateParams3(params) - }); -}; - -class ZodNull3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.null, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodNull3.create = (params) => { - return new ZodNull3({ - typeName: ZodFirstPartyTypeKind3.ZodNull, - ...processCreateParams3(params) - }); -}; - -class ZodAny3 extends ZodType3 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK3(input.data); - } -} -ZodAny3.create = (params) => { - return new ZodAny3({ - typeName: ZodFirstPartyTypeKind3.ZodAny, - ...processCreateParams3(params) - }); -}; - -class ZodUnknown3 extends ZodType3 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK3(input.data); - } -} -ZodUnknown3.create = (params) => { - return new ZodUnknown3({ - typeName: ZodFirstPartyTypeKind3.ZodUnknown, - ...processCreateParams3(params) - }); -}; - -class ZodNever3 extends ZodType3 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.never, - received: ctx.parsedType - }); - return INVALID3; - } -} -ZodNever3.create = (params) => { - return new ZodNever3({ - typeName: ZodFirstPartyTypeKind3.ZodNever, - ...processCreateParams3(params) - }); -}; - -class ZodVoid3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.void, - received: ctx.parsedType - }); - return INVALID3; - } - return OK3(input.data); - } -} -ZodVoid3.create = (params) => { - return new ZodVoid3({ - typeName: ZodFirstPartyTypeKind3.ZodVoid, - ...processCreateParams3(params) - }); -}; - -class ZodArray3 extends ZodType3 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType3.array) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.array, - received: ctx.parsedType - }); - return INVALID3; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext3(ctx, { - code: tooBig ? ZodIssueCode3.too_big : ZodIssueCode3.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath3(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus3.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath3(ctx, item, ctx.path, i)); - }); - return ParseStatus3.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray3({ - ...this._def, - minLength: { value: minLength, message: errorUtil3.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray3({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil3.toString(message) } - }); - } - length(len, message) { - return new ZodArray3({ - ...this._def, - exactLength: { value: len, message: errorUtil3.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray3.create = (schema, params) => { - return new ZodArray3({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind3.ZodArray, - ...processCreateParams3(params) - }); -}; -function deepPartialify3(schema) { - if (schema instanceof ZodObject3) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional3.create(deepPartialify3(fieldSchema)); - } - return new ZodObject3({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray3) { - return new ZodArray3({ - ...schema._def, - type: deepPartialify3(schema.element) - }); - } else if (schema instanceof ZodOptional3) { - return ZodOptional3.create(deepPartialify3(schema.unwrap())); - } else if (schema instanceof ZodNullable3) { - return ZodNullable3.create(deepPartialify3(schema.unwrap())); - } else if (schema instanceof ZodTuple3) { - return ZodTuple3.create(schema.items.map((item) => deepPartialify3(item))); - } else { - return schema; - } -} - -class ZodObject3 extends ZodType3 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util3.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext3(ctx2, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.object, - received: ctx2.parsedType - }); - return INVALID3; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever3 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever3) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus3.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus3.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil3.errToObj; - return new ZodObject3({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil3.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject3({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject3({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject3({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject3({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind3.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject3({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util3.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject3({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject3({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify3(this); - } - partial(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject3({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional3) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject3({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum3(util3.objectKeys(this.shape)); - } -} -ZodObject3.create = (shape, params) => { - return new ZodObject3({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams3(params) - }); -}; -ZodObject3.strictCreate = (shape, params) => { - return new ZodObject3({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams3(params) - }); -}; -ZodObject3.lazycreate = (shape, params) => { - return new ZodObject3({ - shape, - unknownKeys: "strip", - catchall: ZodNever3.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams3(params) - }); -}; - -class ZodUnion3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError3(result.ctx.common.issues)); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_union, - unionErrors - }); - return INVALID3; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError3(issues2)); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_union, - unionErrors - }); - return INVALID3; - } - } - get options() { - return this._def.options; - } -} -ZodUnion3.create = (types, params) => { - return new ZodUnion3({ - options: types, - typeName: ZodFirstPartyTypeKind3.ZodUnion, - ...processCreateParams3(params) - }); -}; -var getDiscriminator3 = (type) => { - if (type instanceof ZodLazy3) { - return getDiscriminator3(type.schema); - } else if (type instanceof ZodEffects3) { - return getDiscriminator3(type.innerType()); - } else if (type instanceof ZodLiteral3) { - return [type.value]; - } else if (type instanceof ZodEnum3) { - return type.options; - } else if (type instanceof ZodNativeEnum3) { - return util3.objectValues(type.enum); - } else if (type instanceof ZodDefault3) { - return getDiscriminator3(type._def.innerType); - } else if (type instanceof ZodUndefined3) { - return [undefined]; - } else if (type instanceof ZodNull3) { - return [null]; - } else if (type instanceof ZodOptional3) { - return [undefined, ...getDiscriminator3(type.unwrap())]; - } else if (type instanceof ZodNullable3) { - return [null, ...getDiscriminator3(type.unwrap())]; - } else if (type instanceof ZodBranded3) { - return getDiscriminator3(type.unwrap()); - } else if (type instanceof ZodReadonly3) { - return getDiscriminator3(type.unwrap()); - } else if (type instanceof ZodCatch3) { - return getDiscriminator3(type._def.innerType); - } else { - return []; - } -}; - -class ZodDiscriminatedUnion3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.object) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.object, - received: ctx.parsedType - }); - return INVALID3; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID3; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator3(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion3({ - typeName: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams3(params) - }); - } -} -function mergeValues3(a, b) { - const aType = getParsedType3(a); - const bType = getParsedType3(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType3.object && bType === ZodParsedType3.object) { - const bKeys = util3.objectKeys(b); - const sharedKeys = util3.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues3(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType3.array && bType === ZodParsedType3.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0;index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues3(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType3.date && bType === ZodParsedType3.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -class ZodIntersection3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted3(parsedLeft) || isAborted3(parsedRight)) { - return INVALID3; - } - const merged = mergeValues3(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_intersection_types - }); - return INVALID3; - } - if (isDirty3(parsedLeft) || isDirty3(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -} -ZodIntersection3.create = (left, right, params) => { - return new ZodIntersection3({ - left, - right, - typeName: ZodFirstPartyTypeKind3.ZodIntersection, - ...processCreateParams3(params) - }); -}; - -class ZodTuple3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.array) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.array, - received: ctx.parsedType - }); - return INVALID3; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID3; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath3(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus3.mergeArray(status, results); - }); - } else { - return ParseStatus3.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple3({ - ...this._def, - rest - }); - } -} -ZodTuple3.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple3({ - items: schemas, - typeName: ZodFirstPartyTypeKind3.ZodTuple, - rest: null, - ...processCreateParams3(params) - }); -}; - -class ZodRecord3 extends ZodType3 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.object) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.object, - received: ctx.parsedType - }); - return INVALID3; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath3(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus3.mergeObjectAsync(status, pairs); - } else { - return ParseStatus3.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType3) { - return new ZodRecord3({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams3(third) - }); - } - return new ZodRecord3({ - keyType: ZodString3.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams3(second) - }); - } -} - -class ZodMap3 extends ZodType3 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.map) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.map, - received: ctx.parsedType - }); - return INVALID3; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath3(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID3; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID3; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap3.create = (keyType, valueType, params) => { - return new ZodMap3({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind3.ZodMap, - ...processCreateParams3(params) - }); -}; - -class ZodSet3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.set) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.set, - received: ctx.parsedType - }); - return INVALID3; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID3; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath3(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet3({ - ...this._def, - minSize: { value: minSize, message: errorUtil3.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet3({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil3.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet3.create = (valueType, params) => { - return new ZodSet3({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind3.ZodSet, - ...processCreateParams3(params) - }); -}; - -class ZodFunction3 extends ZodType3 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.function) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.function, - received: ctx.parsedType - }); - return INVALID3; - } - function makeArgsIssue(args, error) { - return makeIssue3({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap3(), en_default3].filter((x) => !!x), - issueData: { - code: ZodIssueCode3.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue3({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap3(), en_default3].filter((x) => !!x), - issueData: { - code: ZodIssueCode3.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise3) { - const me = this; - return OK3(async function(...args) { - const error = new ZodError3([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK3(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError3([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError3([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction3({ - ...this._def, - args: ZodTuple3.create(items).rest(ZodUnknown3.create()) - }); - } - returns(returnType) { - return new ZodFunction3({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction3({ - args: args ? args : ZodTuple3.create([]).rest(ZodUnknown3.create()), - returns: returns || ZodUnknown3.create(), - typeName: ZodFirstPartyTypeKind3.ZodFunction, - ...processCreateParams3(params) - }); - } -} - -class ZodLazy3 extends ZodType3 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy3.create = (getter, params) => { - return new ZodLazy3({ - getter, - typeName: ZodFirstPartyTypeKind3.ZodLazy, - ...processCreateParams3(params) - }); -}; - -class ZodLiteral3 extends ZodType3 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_literal, - expected: this._def.value - }); - return INVALID3; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral3.create = (value, params) => { - return new ZodLiteral3({ - value, - typeName: ZodFirstPartyTypeKind3.ZodLiteral, - ...processCreateParams3(params) - }); -}; -function createZodEnum3(values, params) { - return new ZodEnum3({ - values, - typeName: ZodFirstPartyTypeKind3.ZodEnum, - ...processCreateParams3(params) - }); -} - -class ZodEnum3 extends ZodType3 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext3(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode3.invalid_type - }); - return INVALID3; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_enum_value, - options: expectedValues - }); - return INVALID3; - } - return OK3(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum3.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum3.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -} -ZodEnum3.create = createZodEnum3; - -class ZodNativeEnum3 extends ZodType3 { - _parse(input) { - const nativeEnumValues = util3.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType3.string && ctx.parsedType !== ZodParsedType3.number) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext3(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode3.invalid_type - }); - return INVALID3; - } - if (!this._cache) { - this._cache = new Set(util3.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext3(ctx, { - received: ctx.data, - code: ZodIssueCode3.invalid_enum_value, - options: expectedValues - }); - return INVALID3; - } - return OK3(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum3.create = (values, params) => { - return new ZodNativeEnum3({ - values, - typeName: ZodFirstPartyTypeKind3.ZodNativeEnum, - ...processCreateParams3(params) - }); -}; - -class ZodPromise3 extends ZodType3 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType3.promise && ctx.common.async === false) { - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.promise, - received: ctx.parsedType - }); - return INVALID3; - } - const promisified = ctx.parsedType === ZodParsedType3.promise ? ctx.data : Promise.resolve(ctx.data); - return OK3(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -} -ZodPromise3.create = (schema, params) => { - return new ZodPromise3({ - type: schema, - typeName: ZodFirstPartyTypeKind3.ZodPromise, - ...processCreateParams3(params) - }); -}; - -class ZodEffects3 extends ZodType3 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext3(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID3; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID3; - if (result.status === "dirty") - return DIRTY3(result.value); - if (status.value === "dirty") - return DIRTY3(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID3; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID3; - if (result.status === "dirty") - return DIRTY3(result.value); - if (status.value === "dirty") - return DIRTY3(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID3; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID3; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid3(base)) - return INVALID3; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid3(base)) - return INVALID3; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util3.assertNever(effect); - } -} -ZodEffects3.create = (schema, effect, params) => { - return new ZodEffects3({ - schema, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect, - ...processCreateParams3(params) - }); -}; -ZodEffects3.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects3({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - ...processCreateParams3(params) - }); -}; - -class ZodOptional3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType3.undefined) { - return OK3(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional3.create = (type, params) => { - return new ZodOptional3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodOptional, - ...processCreateParams3(params) - }); -}; - -class ZodNullable3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType3.null) { - return OK3(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable3.create = (type, params) => { - return new ZodNullable3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodNullable, - ...processCreateParams3(params) - }); -}; - -class ZodDefault3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType3.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault3.create = (type, params) => { - return new ZodDefault3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams3(params) - }); -}; - -class ZodCatch3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync3(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError3(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError3(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch3.create = (type, params) => { - return new ZodCatch3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams3(params) - }); -}; - -class ZodNaN3 extends ZodType3 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType3.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext3(ctx, { - code: ZodIssueCode3.invalid_type, - expected: ZodParsedType3.nan, - received: ctx.parsedType - }); - return INVALID3; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN3.create = (params) => { - return new ZodNaN3({ - typeName: ZodFirstPartyTypeKind3.ZodNaN, - ...processCreateParams3(params) - }); -}; -var BRAND3 = Symbol("zod_brand"); - -class ZodBranded3 extends ZodType3 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -} - -class ZodPipeline3 extends ZodType3 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID3; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY3(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID3; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new ZodPipeline3({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind3.ZodPipeline - }); - } -} - -class ZodReadonly3 extends ZodType3 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid3(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync3(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly3.create = (type, params) => { - return new ZodReadonly3({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodReadonly, - ...processCreateParams3(params) - }); -}; -function cleanParams3(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom3(check, _params = {}, fatal) { - if (check) - return ZodAny3.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams3(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams3(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny3.create(); -} -var late3 = { - object: ZodObject3.lazycreate -}; -var ZodFirstPartyTypeKind3; -(function(ZodFirstPartyTypeKind22) { - ZodFirstPartyTypeKind22["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind3 || (ZodFirstPartyTypeKind3 = {})); -var instanceOfType3 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom3((data) => data instanceof cls, params); -var stringType3 = ZodString3.create; -var numberType3 = ZodNumber3.create; -var nanType3 = ZodNaN3.create; -var bigIntType3 = ZodBigInt3.create; -var booleanType3 = ZodBoolean3.create; -var dateType3 = ZodDate3.create; -var symbolType3 = ZodSymbol3.create; -var undefinedType3 = ZodUndefined3.create; -var nullType3 = ZodNull3.create; -var anyType3 = ZodAny3.create; -var unknownType3 = ZodUnknown3.create; -var neverType3 = ZodNever3.create; -var voidType3 = ZodVoid3.create; -var arrayType3 = ZodArray3.create; -var objectType3 = ZodObject3.create; -var strictObjectType3 = ZodObject3.strictCreate; -var unionType3 = ZodUnion3.create; -var discriminatedUnionType3 = ZodDiscriminatedUnion3.create; -var intersectionType3 = ZodIntersection3.create; -var tupleType3 = ZodTuple3.create; -var recordType3 = ZodRecord3.create; -var mapType3 = ZodMap3.create; -var setType3 = ZodSet3.create; -var functionType3 = ZodFunction3.create; -var lazyType3 = ZodLazy3.create; -var literalType3 = ZodLiteral3.create; -var enumType3 = ZodEnum3.create; -var nativeEnumType3 = ZodNativeEnum3.create; -var promiseType3 = ZodPromise3.create; -var effectsType3 = ZodEffects3.create; -var optionalType3 = ZodOptional3.create; -var nullableType3 = ZodNullable3.create; -var preprocessType3 = ZodEffects3.createWithPreprocess; -var pipelineType3 = ZodPipeline3.create; -var ostring3 = () => stringType3().optional(); -var onumber3 = () => numberType3().optional(); -var oboolean3 = () => booleanType3().optional(); -var coerce3 = { - string: (arg) => ZodString3.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber3.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean3.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt3.create({ ...arg, coerce: true }), - date: (arg) => ZodDate3.create({ ...arg, coerce: true }) -}; -var NEVER3 = INVALID3; -var SCHEMA_IDS3 = { - actorRef: "hasna.actor_ref.v1", - resourceRef: "hasna.resource_ref.v1", - evidenceRef: "hasna.evidence_ref.v1", - workRun: "hasna.work_run.v1", - decisionEnvelope: "hasna.decision_envelope.v1", - costEstimate: "hasna.cost_estimate.v1", - capabilityCard: "hasna.capability_card.v1", - providerLiveModeStandard: "hasna.provider_live_mode_standard.v1", - contextPack: "hasna.context_pack.v1", - integrationRef: "hasna.integration_ref.v1", - projectManifest: "hasna.project_manifest.v1", - projectPanel: "hasna.project_panel.v1", - projectSnapshot: "hasna.project_snapshot.v1", - renderManifest: "hasna.render_manifest.v1", - agentTrajectory: "hasna.agent_trajectory.v1", - validationPlan: "hasna.validation_plan.v1", - proofBundle: "hasna.proof_bundle.v1", - scaffoldManifest: "hasna.scaffold_manifest.v1", - scaffoldInstallRecord: "hasna.scaffold_install_record.v1", - appCloudManifest: "hasna.app_cloud_manifest.v1", - noCloudEvidencePack: "hasna.no_cloud_evidence_pack.v1", - serviceContract: "hasna.service_contract.v1", - commsEventEnvelope: "hasna.comms_event_envelope.v1", - commsChannelMetadata: "hasna.comms_channel_metadata.v1", - commsMessageMetadata: "hasna.comms_message_metadata.v1", - app: "hasna.app.v1", - release: "hasna.release.v1", - rolloutRecord: "hasna.rollout_record.v1", - announcement: "hasna.announcement.v1", - audience: "hasna.audience.v1" -}; -var SchemaIdSchema3 = exports_external3.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/); -var TimestampSchema3 = exports_external3.string().datetime(); -var NonEmptyStringSchema3 = exports_external3.string().trim().min(1); -var UriSchema3 = NonEmptyStringSchema3.refine((value) => value.startsWith("artifact://") || value.startsWith("repo://") || value.startsWith("project://") || value.startsWith("dashboard://") || value.startsWith("render://") || value.startsWith("integration://") || value.startsWith("task://") || value.startsWith("todo://") || value.startsWith("file://") || value.startsWith("files://") || value.startsWith("mailery://") || value.startsWith("conversation://") || value.startsWith("knowledge://") || value.startsWith("memento://") || value.startsWith("https://") || value.startsWith("http://") || value.startsWith("git+https://"), "URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"); -var Sha256DigestSchema3 = exports_external3.string().regex(/^[a-fA-F0-9]{64}$/); -var HashStringSchema3 = exports_external3.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/); -var MetadataSchema3 = exports_external3.record(exports_external3.unknown()); -var TagsSchema3 = exports_external3.array(exports_external3.string().min(1)).default([]); -var OptionalTimestampSchema3 = TimestampSchema3.nullable().optional(); -var TerminalStatuses3 = new Set(["succeeded", "failed", "cancelled", "blocked", "skipped"]); -var ContractStatusSchema3 = exports_external3.enum([ - "pending", - "running", - "succeeded", - "failed", - "cancelled", - "blocked", - "skipped", - "unknown" -]); -function contractBaseSchema3(schema) { - return exports_external3.object({ - schema: exports_external3.literal(schema), - id: exports_external3.string().min(1), - createdAt: TimestampSchema3, - updatedAt: OptionalTimestampSchema3, - metadata: MetadataSchema3.optional() - }).strict(); -} -var ContractEnvelopeSchema3 = exports_external3.object({ - schema: SchemaIdSchema3, - id: exports_external3.string().min(1), - createdAt: TimestampSchema3, - updatedAt: OptionalTimestampSchema3, - metadata: MetadataSchema3.optional() -}).strict(); -var ActorKindSchema3 = exports_external3.enum([ - "agent", - "human", - "service", - "model", - "workflow", - "system" -]); -var ActorRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.actorRef).extend({ - kind: ActorKindSchema3, - name: exports_external3.string().min(1).optional(), - provider: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - machineId: exports_external3.string().min(1).optional(), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict(); -var ActorPointerSchema3 = exports_external3.object({ - kind: ActorKindSchema3, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - provider: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - machineId: exports_external3.string().min(1).optional() -}).strict(); -var ResourceKindSchema3 = exports_external3.enum([ - "task", - "project", - "repo", - "run", - "loop", - "workflow", - "action", - "event", - "integration", - "session", - "machine", - "model", - "tool", - "file", - "document", - "url", - "artifact", - "knowledge", - "email", - "conversation", - "dashboard", - "render", - "panel", - "report", - "commit", - "branch", - "pull_request", - "issue", - "comment", - "verification", - "finding", - "context_pack", - "proof_bundle", - "memento", - "eval", - "budget", - "cost", - "alert", - "incident", - "app", - "release", - "rollout", - "announcement", - "audience", - "feedback", - "unknown" -]); -var ResourceRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.resourceRef).extend({ - kind: ResourceKindSchema3, - name: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.externalId && value.sourcePackage)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Resource refs require uri or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ResourcePointerSchema3 = exports_external3.object({ - kind: ResourceKindSchema3, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - if (!value.uri && Boolean(value.externalId) !== Boolean(value.sourcePackage)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Resource pointers with external package locators require both sourcePackage and externalId", - path: value.externalId ? ["sourcePackage"] : ["externalId"] - }); - } -}); -var EvidenceKindSchema3 = exports_external3.enum([ - "file", - "command_output", - "screenshot", - "log", - "diff", - "report", - "artifact", - "url", - "video", - "har", - "test_result", - "metric", - "trace", - "other" -]); -var RedactionStateSchema3 = exports_external3.enum(["none", "partial", "full", "unknown"]); -var EvidenceRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.evidenceRef).extend({ - kind: EvidenceKindSchema3, - uri: UriSchema3, - sha256: Sha256DigestSchema3.optional(), - summary: exports_external3.string().min(1).optional(), - contentType: exports_external3.string().min(1).optional(), - sizeBytes: exports_external3.number().int().nonnegative().optional(), - redaction: RedactionStateSchema3.default("unknown"), - producer: ActorPointerSchema3.optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - tags: TagsSchema3 -}).strict(); -var EvidencePointerSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: EvidenceKindSchema3.optional(), - uri: UriSchema3.optional(), - sha256: Sha256DigestSchema3.optional(), - summary: exports_external3.string().min(1).optional() -}).strict(); -var CostEstimateSchema3 = contractBaseSchema3(SCHEMA_IDS3.costEstimate).extend({ - currency: exports_external3.string().regex(/^[A-Z]{3}$/).default("USD"), - amountMicros: exports_external3.number().int().nonnegative(), - provider: exports_external3.string().min(1).optional(), - model: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - promptTokens: exports_external3.number().int().nonnegative().optional(), - completionTokens: exports_external3.number().int().nonnegative().optional(), - totalTokens: exports_external3.number().int().nonnegative().optional(), - basis: exports_external3.enum(["actual", "estimated", "budget", "limit"]).default("estimated"), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.promptTokens !== undefined && value.completionTokens !== undefined && value.totalTokens !== undefined && value.totalTokens !== value.promptTokens + value.completionTokens) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "totalTokens must equal promptTokens plus completionTokens when all are present", - path: ["totalTokens"] - }); - } -}); -var DecisionStatusSchema3 = exports_external3.enum([ - "allowed", - "denied", - "warned", - "approval_required", - "selected", - "skipped", - "unknown" -]); -var DecisionEnvelopeSchema3 = contractBaseSchema3(SCHEMA_IDS3.decisionEnvelope).extend({ - decisionType: exports_external3.enum([ - "guardrail", - "model_route", - "tool_select", - "budget", - "secret_access", - "approval", - "policy", - "other" - ]), - status: DecisionStatusSchema3, - actor: ActorPointerSchema3.optional(), - traceId: exports_external3.string().min(1).optional(), - inputHash: HashStringSchema3.optional(), - policyBundleId: exports_external3.string().min(1).optional(), - selected: exports_external3.array(ResourcePointerSchema3).default([]), - skipped: exports_external3.array(ResourcePointerSchema3).default([]), - reason: exports_external3.string().min(1), - obligations: exports_external3.array(exports_external3.string().min(1)).default([]), - redactions: exports_external3.array(exports_external3.string().min(1)).default([]), - costEstimate: CostEstimateSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "selected" && value.selected.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Selected decisions require at least one selected resource", path: ["selected"] }); - } - if (value.status === "skipped" && value.skipped.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Skipped decisions require at least one skipped resource", path: ["skipped"] }); - } - if (value.status === "denied") { - if (value.selected.length > 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Denied decisions cannot include selected resources", path: ["selected"] }); - } - if (!value.policyBundleId && value.evidenceRefs.length === 0 && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Denied decisions require policy, evidence, or obligations", - path: ["policyBundleId"] - }); - } - } - if (value.status === "approval_required" && value.obligations.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Approval-required decisions require actionable obligations", - path: ["obligations"] - }); - } -}); -var CapabilityCardSchema3 = contractBaseSchema3(SCHEMA_IDS3.capabilityCard).extend({ - kind: exports_external3.enum(["model", "tool", "machine", "agent", "lane", "connector", "service"]), - name: exports_external3.string().min(1), - version: exports_external3.string().min(1).optional(), - status: exports_external3.enum(["available", "unavailable", "degraded", "unknown"]).default("unknown"), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]), - limitations: exports_external3.array(exports_external3.string().min(1)).default([]), - riskLevel: exports_external3.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - costEstimate: CostEstimateSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict(); -var ProviderModeSchema3 = exports_external3.enum(["mock", "fixture", "sandbox", "read_only_live", "live_mutating"]); -var ProviderSideEffectClassSchema3 = exports_external3.enum([ - "none", - "read_only", - "external_notification", - "external_mutation", - "money_movement", - "dns_or_domain_change", - "bulk_message_or_call", - "legal_or_filing", - "compute_or_infra_mutation", - "irreversible" -]); -var CredentialRequirementSchema3 = exports_external3.object({ - refName: NonEmptyStringSchema3, - requiredForModes: exports_external3.array(ProviderModeSchema3).min(1), - allowedSecretInputs: exports_external3.array(exports_external3.enum(["credential_ref", "lease_ref"])).min(1).default(["credential_ref"]), - failClosedDiagnostic: NonEmptyStringSchema3, - revocationCheck: exports_external3.boolean().default(true) -}).strict(); -var ProviderOperationCardSchema3 = exports_external3.object({ - operation: NonEmptyStringSchema3, - supportedModes: exports_external3.array(ProviderModeSchema3).min(1), - sideEffectClass: ProviderSideEffectClassSchema3, - requiresApproval: exports_external3.boolean().default(false), - requiresIdempotencyKey: exports_external3.boolean().default(false), - requiresSandboxEvidence: exports_external3.boolean().default(false), - requiresRollbackOrRevocation: exports_external3.boolean().default(false), - rollbackOrRevocation: NonEmptyStringSchema3.optional(), - noSideEffectSmoke: NonEmptyStringSchema3.optional(), - reconciliation: NonEmptyStringSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (value.supportedModes.includes("live_mutating")) { - if (value.sideEffectClass === "none" || value.sideEffectClass === "read_only") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations must declare a side-effecting class", - path: ["sideEffectClass"] - }); - } - if (!value.requiresApproval) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require approval", - path: ["requiresApproval"] - }); - } - if (!value.requiresIdempotencyKey) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require idempotency keys", - path: ["requiresIdempotencyKey"] - }); - } - if (!value.requiresSandboxEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require sandbox evidence before live proof", - path: ["requiresSandboxEvidence"] - }); - } - if (!value.requiresRollbackOrRevocation || !value.rollbackOrRevocation) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require rollback or revocation instructions", - path: ["rollbackOrRevocation"] - }); - } - if (!value.reconciliation) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating operations require reconciliation behavior", - path: ["reconciliation"] - }); - } - } -}); -var ProviderCapabilityCardSchema3 = exports_external3.object({ - providerId: NonEmptyStringSchema3, - appId: NonEmptyStringSchema3, - adapterId: NonEmptyStringSchema3, - ownerPackage: NonEmptyStringSchema3, - modes: exports_external3.array(ProviderModeSchema3).min(1), - defaultMode: ProviderModeSchema3, - credentialRequirements: exports_external3.array(CredentialRequirementSchema3).default([]), - operations: exports_external3.array(ProviderOperationCardSchema3).min(1), - rateLimitPosture: NonEmptyStringSchema3, - costPosture: NonEmptyStringSchema3.optional(), - auditEvents: exports_external3.array(NonEmptyStringSchema3).default([]), - redactionRules: exports_external3.array(NonEmptyStringSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (!value.modes.includes(value.defaultMode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "defaultMode must be one of modes", - path: ["defaultMode"] - }); - } - const operationModes = new Set(value.operations.flatMap((operation) => operation.supportedModes)); - for (const mode of operationModes) { - if (!value.modes.includes(mode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `operation mode ${mode} is not declared in provider modes`, - path: ["operations"] - }); - } - } - if (operationModes.has("live_mutating")) { - const liveCredential = value.credentialRequirements.some((credential) => credential.requiredForModes.includes("live_mutating")); - if (!liveCredential) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating providers require at least one live credential reference requirement", - path: ["credentialRequirements"] - }); - } - if (value.auditEvents.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "live_mutating providers require audit events", - path: ["auditEvents"] - }); - } - } -}); -var ProviderLiveModeTargetSchema3 = exports_external3.object({ - appId: NonEmptyStringSchema3, - repo: NonEmptyStringSchema3, - priority: exports_external3.enum(["p0", "p1", "p2"]).default("p1"), - requiredEvidence: exports_external3.array(NonEmptyStringSchema3).min(1), - firstOperations: exports_external3.array(NonEmptyStringSchema3).min(1), - blockedUntil: exports_external3.array(NonEmptyStringSchema3).default([]) -}).strict(); -var ProviderLiveModeStandardSchema3 = contractBaseSchema3(SCHEMA_IDS3.providerLiveModeStandard).extend({ - name: NonEmptyStringSchema3, - version: NonEmptyStringSchema3, - modes: exports_external3.array(ProviderModeSchema3).refine((modes) => ["mock", "fixture", "sandbox", "read_only_live", "live_mutating"].every((mode) => modes.includes(mode)), "provider live-mode standard must include every canonical provider mode"), - requiredCapabilityFields: exports_external3.array(NonEmptyStringSchema3).min(1), - liveMutationGate: exports_external3.object({ - requiredMode: exports_external3.literal("live_mutating"), - requiredChecks: exports_external3.array(NonEmptyStringSchema3).min(1), - forbiddenBypassSignals: exports_external3.array(NonEmptyStringSchema3).min(1), - disabledLiveSmoke: NonEmptyStringSchema3 - }).strict(), - noSideEffectSmoke: exports_external3.object({ - requiredForModes: exports_external3.array(ProviderModeSchema3).min(1), - commandEvidence: exports_external3.array(NonEmptyStringSchema3).min(1), - secretOutputScan: exports_external3.boolean().default(true) - }).strict(), - credentialPolicy: exports_external3.object({ - acceptedInputs: exports_external3.array(exports_external3.enum(["credential_ref", "lease_ref"])).min(1), - rawSecretInputsAllowed: exports_external3.literal(false), - missingCredentialBehavior: exports_external3.literal("fail_closed"), - revocationCheckRequired: exports_external3.boolean().default(true) - }).strict(), - operationCards: exports_external3.array(ProviderCapabilityCardSchema3).min(1), - firstAdoptionTargets: exports_external3.array(ProviderLiveModeTargetSchema3).min(1), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const firstTargetApps = new Set(value.firstAdoptionTargets.map((target) => target.appId)); - const operationApps = new Set(value.operationCards.map((card) => card.appId)); - for (const appId of firstTargetApps) { - if (!operationApps.has(appId)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `first adoption target ${appId} requires a provider capability card`, - path: ["firstAdoptionTargets"] - }); - } - } -}); -var ContextPackItemSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1).optional(), - summary: exports_external3.string().min(1), - text: exports_external3.string().optional(), - tokens: exports_external3.number().int().nonnegative().optional(), - source: EvidencePointerSchema3, - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict(); -var ContextPackSchema3 = contractBaseSchema3(SCHEMA_IDS3.contextPack).extend({ - objective: exports_external3.string().min(1), - budget: exports_external3.object({ - maxTokens: exports_external3.number().int().positive().optional(), - maxBytes: exports_external3.number().int().positive().optional() - }).strict().optional(), - items: exports_external3.array(ContextPackItemSchema3).default([]), - citations: exports_external3.array(EvidencePointerSchema3).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - permissions: exports_external3.array(exports_external3.string().min(1)).default([]), - redactions: exports_external3.array(exports_external3.string().min(1)).default([]), - conflicts: exports_external3.array(exports_external3.string().min(1)).default([]), - uncertainty: exports_external3.string().min(1).optional() -}).strict(); -var RelativeProjectPathSchema3 = NonEmptyStringSchema3.refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").includes(".."), "Project paths must be relative and cannot contain parent-directory segments"); -var ProjectSlugSchema3 = exports_external3.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Project slugs must be lowercase dashed identifiers"); -var ProjectClassificationSchema3 = exports_external3.enum(["public", "internal", "private", "sensitive"]); -var ProjectStatusSchema3 = exports_external3.enum(["draft", "active", "paused", "archived"]); -var ProjectIntegrationKindSchema3 = exports_external3.enum([ - "todos", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "render", - "contracts", - "custom" -]); -var IntegrationRefSchema3 = contractBaseSchema3(SCHEMA_IDS3.integrationRef).extend({ - kind: ProjectIntegrationKindSchema3, - name: exports_external3.string().min(1), - projectId: ProjectSlugSchema3.optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - externalId: NonEmptyStringSchema3.optional(), - uri: UriSchema3.optional(), - enabled: exports_external3.boolean().default(true), - readOnly: exports_external3.boolean().default(true), - capabilities: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - resourceRef: ResourcePointerSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - config: MetadataSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (!value.uri && !(value.sourcePackage && value.externalId) && !value.resourceRef) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Integration refs require uri, resourceRef, or both sourcePackage and externalId", - path: ["uri"] - }); - } -}); -var ProjectLayoutSchema3 = exports_external3.object({ - schemaRoot: RelativeProjectPathSchema3.default(".hasna/project"), - dashboardManifest: RelativeProjectPathSchema3.default(".hasna/project/dashboard.render.json"), - snapshotsDir: RelativeProjectPathSchema3.default(".hasna/project/snapshots"), - documentsDir: RelativeProjectPathSchema3.default("documents"), - reportsDir: RelativeProjectPathSchema3.default("reports"), - evidenceDir: RelativeProjectPathSchema3.default(".hasna/project/evidence"), - privateDir: RelativeProjectPathSchema3.default(".hasna/project/private") -}).strict(); -var ProjectManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectManifest).extend({ - projectId: ProjectSlugSchema3, - slug: ProjectSlugSchema3, - name: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - status: ProjectStatusSchema3.default("active"), - classification: ProjectClassificationSchema3.default("private"), - owner: ActorPointerSchema3.optional(), - layout: ProjectLayoutSchema3.default({}), - integrations: exports_external3.array(IntegrationRefSchema3).default([]), - renderManifests: exports_external3.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - const integrationIds = new Set; - const renderManifestIds = new Set; - if (value.projectId !== value.slug) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "projectId and slug must match for canonical project manifests", - path: ["slug"] - }); - } - for (const [index, integration] of value.integrations.entries()) { - if (integrationIds.has(integration.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project manifest integration ids must be unique", - path: ["integrations", index, "id"] - }); - } - integrationIds.add(integration.id); - if (integration.projectId && integration.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Integration projectId must match the manifest projectId", - path: ["integrations", index, "projectId"] - }); - } - } - for (const [index, renderManifest] of value.renderManifests.entries()) { - if (renderManifest.kind !== "render") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project renderManifests must use resource kind render", - path: ["renderManifests", index, "kind"] - }); - } - if (renderManifestIds.has(renderManifest.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project renderManifest refs must be unique", - path: ["renderManifests", index, "id"] - }); - } - renderManifestIds.add(renderManifest.id); - } -}); -var RenderImportKindSchema3 = exports_external3.enum(["local", "package", "provider", "url"]); -var RenderImportSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: RenderImportKindSchema3, - specifier: exports_external3.string().min(1), - path: RelativeProjectPathSchema3.optional(), - packageName: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - provider: ProjectIntegrationKindSchema3.optional(), - schemaId: SchemaIdSchema3.optional(), - integrity: HashStringSchema3.optional(), - resourceRef: ResourcePointerSchema3.optional(), - optional: exports_external3.boolean().default(false) -}).strict().superRefine((value, ctx) => { - if (value.kind === "local" && !value.path) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Local render imports require path", path: ["path"] }); - } - if (value.kind === "package" && !value.packageName) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Package render imports require packageName", path: ["packageName"] }); - } - if (value.kind === "provider" && !value.provider) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Provider render imports require provider", path: ["provider"] }); - } - if (value.kind === "url" && !value.uri) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "URL render imports require uri", path: ["uri"] }); - } -}); -var RenderViewKindSchema3 = exports_external3.enum(["dashboard", "canvas", "panel", "report", "document", "custom"]); -var RenderViewSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1), - kind: RenderViewKindSchema3, - default: exports_external3.boolean().default(false), - entry: RelativeProjectPathSchema3.optional(), - imports: exports_external3.array(RenderImportSchema3).default([]), - panelRefs: exports_external3.array(ResourcePointerSchema3).default([]), - dataRefs: exports_external3.array(ResourcePointerSchema3).default([]), - layout: MetadataSchema3.optional() -}).strict(); -var RenderManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.renderManifest).extend({ - projectId: ProjectSlugSchema3, - name: exports_external3.string().min(1), - version: exports_external3.string().min(1), - manifestPath: RelativeProjectPathSchema3.default(".hasna/project/dashboard.render.json"), - renderer: exports_external3.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - views: exports_external3.array(RenderViewSchema3).min(1), - imports: exports_external3.array(RenderImportSchema3).default([]), - theme: MetadataSchema3.optional(), - compatibility: exports_external3.object({ - minProjectsVersion: exports_external3.string().min(1).optional(), - minContractsVersion: exports_external3.string().min(1).optional() - }).strict().optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const defaults = value.views.filter((view) => view.default); - const viewIds = new Set; - const importIds = new Set; - if (defaults.length > 1) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Render manifests can have at most one default view", path: ["views"] }); - } - for (const [index, importRef] of value.imports.entries()) { - if (importIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render manifest import ids must be unique", - path: ["imports", index, "id"] - }); - } - importIds.add(importRef.id); - } - for (const [viewIndex, view] of value.views.entries()) { - if (viewIds.has(view.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render manifest view ids must be unique", - path: ["views", viewIndex, "id"] - }); - } - viewIds.add(view.id); - const viewImportIds = new Set; - for (const [importIndex, importRef] of view.imports.entries()) { - if (viewImportIds.has(importRef.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render view import ids must be unique", - path: ["views", viewIndex, "imports", importIndex, "id"] - }); - } - viewImportIds.add(importRef.id); - } - for (const [panelIndex, panelRef] of view.panelRefs.entries()) { - if (panelRef.kind !== "panel") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Render view panelRefs must use resource kind panel", - path: ["views", viewIndex, "panelRefs", panelIndex, "kind"] - }); - } - } - } -}); -var ProjectPanelStateSchema3 = exports_external3.enum(["ready", "empty", "loading", "error", "auth_required", "unavailable", "stale"]); -var ProjectPanelKindSchema3 = exports_external3.enum([ - "overview", - "tasks", - "files", - "mailery", - "conversations", - "knowledge", - "mementos", - "reports", - "actions", - "timeline", - "risks", - "documents", - "custom" -]); -var ProjectPanelMetricSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - label: exports_external3.string().min(1), - value: exports_external3.union([exports_external3.string(), exports_external3.number(), exports_external3.boolean()]), - unit: exports_external3.string().min(1).optional(), - status: exports_external3.enum(["good", "warning", "critical", "unknown"]).default("unknown"), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict(); -var ProjectPanelItemSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - title: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - status: exports_external3.string().min(1).optional(), - priority: exports_external3.enum(["low", "medium", "high", "critical", "unknown"]).default("unknown"), - timestamp: TimestampSchema3.optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - metadata: MetadataSchema3.optional() -}).strict(); -var ProjectRenderFragmentSchema3 = exports_external3.object({ - renderer: exports_external3.enum(["json_render", "react_flow", "markdown", "html", "custom"]).default("json_render"), - title: exports_external3.string().min(1).optional(), - entry: RelativeProjectPathSchema3.optional(), - imports: exports_external3.array(RenderImportSchema3).default([]), - spec: MetadataSchema3.default({}) -}).strict(); -var ProjectPanelSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectPanel).extend({ - projectId: ProjectSlugSchema3, - provider: exports_external3.object({ - kind: ProjectIntegrationKindSchema3, - id: exports_external3.string().min(1), - name: exports_external3.string().min(1).optional(), - sourcePackage: NonEmptyStringSchema3.optional(), - externalId: NonEmptyStringSchema3.optional() - }).strict(), - kind: ProjectPanelKindSchema3, - title: exports_external3.string().min(1), - summary: exports_external3.string().min(1).optional(), - state: ProjectPanelStateSchema3.default("ready"), - stateReason: exports_external3.string().min(1).optional(), - generatedAt: TimestampSchema3, - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown"), - metrics: exports_external3.array(ProjectPanelMetricSchema3).default([]), - items: exports_external3.array(ProjectPanelItemSchema3).default([]), - actions: exports_external3.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - renderFragment: ProjectRenderFragmentSchema3.optional(), - warnings: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict().superRefine((value, ctx) => { - const reasonStates = new Set(["error", "auth_required", "unavailable", "stale"]); - const metricIds = new Set; - const itemIds = new Set; - if (reasonStates.has(value.state) && !value.stateReason) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Non-ready provider states require stateReason", - path: ["stateReason"] - }); - } - if (value.state === "ready" && value.metrics.length === 0 && value.items.length === 0 && !value.renderFragment) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels", - path: ["state"] - }); - } - for (const [index, metric] of value.metrics.entries()) { - if (metricIds.has(metric.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel metric ids must be unique", - path: ["metrics", index, "id"] - }); - } - metricIds.add(metric.id); - } - for (const [index, item] of value.items.entries()) { - if (itemIds.has(item.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel item ids must be unique", - path: ["items", index, "id"] - }); - } - itemIds.add(item.id); - } - for (const [index, action] of value.actions.entries()) { - if (action.kind !== "action") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project panel actions must use resource kind action", - path: ["actions", index, "kind"] - }); - } - } -}); -var ProjectSnapshotSchema3 = contractBaseSchema3(SCHEMA_IDS3.projectSnapshot).extend({ - projectId: ProjectSlugSchema3, - generatedAt: TimestampSchema3, - status: ContractStatusSchema3.default("unknown"), - manifestRef: ResourcePointerSchema3, - renderManifestRef: ResourcePointerSchema3.optional(), - panels: exports_external3.array(ProjectPanelSchema3).default([]), - contextPacks: exports_external3.array(ContextPackSchema3).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema3).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - warnings: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - const panelIds = new Set; - const contextPackIds = new Set; - if (value.manifestRef.kind !== "project") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot manifestRef must use resource kind project", - path: ["manifestRef", "kind"] - }); - } - if (value.renderManifestRef && value.renderManifestRef.kind !== "render") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot renderManifestRef must use resource kind render", - path: ["renderManifestRef", "kind"] - }); - } - for (const [index, proofBundleRef] of value.proofBundleRefs.entries()) { - if (proofBundleRef.kind !== "proof_bundle") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot proofBundleRefs must use resource kind proof_bundle", - path: ["proofBundleRefs", index, "kind"] - }); - } - } - for (const [index, panel] of value.panels.entries()) { - if (panel.projectId !== value.projectId) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Panel projectId must match snapshot projectId", - path: ["panels", index, "projectId"] - }); - } - if (panelIds.has(panel.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot panel ids must be unique", - path: ["panels", index, "id"] - }); - } - panelIds.add(panel.id); - } - for (const [index, contextPack] of value.contextPacks.entries()) { - if (contextPackIds.has(contextPack.id)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Project snapshot context pack ids must be unique", - path: ["contextPacks", index, "id"] - }); - } - contextPackIds.add(contextPack.id); - } -}); -var ValidationCheckSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: exports_external3.enum(["command", "test", "typecheck", "lint", "eval", "security", "review", "deploy", "smoke", "manual", "other"]), - required: exports_external3.boolean().default(true), - command: exports_external3.string().min(1).optional(), - expected: exports_external3.string().min(1).optional(), - timeoutMs: exports_external3.number().int().positive().optional(), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const actionableKinds = new Set(["command", "test", "typecheck", "lint", "smoke", "eval"]); - if (actionableKinds.has(value.kind) && !value.command && !value.expected) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Actionable validation checks require command or expected", - path: ["command"] - }); - } -}); -var ValidationPlanSchema3 = contractBaseSchema3(SCHEMA_IDS3.validationPlan).extend({ - objective: exports_external3.string().min(1), - subject: ResourcePointerSchema3.optional(), - checks: exports_external3.array(ValidationCheckSchema3).min(1), - verifier: ActorPointerSchema3.optional(), - requiredEvidenceKinds: exports_external3.array(EvidenceKindSchema3).default([]) -}).strict(); -var ScaffoldTypeSchema3 = exports_external3.enum([ - "open_source", - "internal_app", - "platform", - "app", - "agent", - "content", - "overlay", - "other" -]); -var ScaffoldStatusSchema3 = exports_external3.enum(["draft", "active", "deprecated", "archived"]); -var ScaffoldCapabilitySchema3 = exports_external3.enum([ - "cli", - "mcp", - "library", - "sdk", - "rest_api", - "dashboard", - "database", - "auth", - "billing", - "worker", - "daemon", - "native", - "browser_extension", - "ai_provider", - "media_pipeline", - "data_pipeline", - "tests", - "ci", - "deployment", - "docs", - "other" -]); -var ScaffoldEnvVarSchema3 = exports_external3.object({ - key: exports_external3.string().regex(/^[A-Z][A-Z0-9_]*$/), - description: exports_external3.string().min(1), - required: exports_external3.boolean().default(false), - ["secret"]: exports_external3.boolean().default(false), - group: exports_external3.string().min(1).optional(), - default: exports_external3.string().optional() -}).strict().superRefine((value, ctx) => { - if (value.secret && value.default !== undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Secret scaffold env vars cannot include defaults", - path: ["default"] - }); - } -}); -var ScaffoldScriptSchema3 = exports_external3.object({ - name: exports_external3.string().min(1), - command: exports_external3.string().min(1), - description: exports_external3.string().min(1).optional(), - required: exports_external3.boolean().default(false) -}).strict(); -var ScaffoldOutputShapeSchema3 = exports_external3.object({ - packageManager: exports_external3.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - languages: exports_external3.array(exports_external3.string().min(1)).default([]), - requiredFiles: exports_external3.array(exports_external3.string().min(1)).default([]), - requiredDirectories: exports_external3.array(exports_external3.string().min(1)).default([]), - optionalDirectories: exports_external3.array(exports_external3.string().min(1)).default([]) -}).strict(); -var ScaffoldManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.scaffoldManifest).extend({ - name: exports_external3.string().min(1), - version: exports_external3.string().min(1), - summary: exports_external3.string().min(1), - type: ScaffoldTypeSchema3, - status: ScaffoldStatusSchema3.default("draft"), - capabilities: exports_external3.array(ScaffoldCapabilitySchema3).default([]), - techStack: exports_external3.array(exports_external3.string().min(1)).default([]), - tags: TagsSchema3, - source: ResourcePointerSchema3.optional(), - output: ScaffoldOutputShapeSchema3, - env: exports_external3.array(ScaffoldEnvVarSchema3).default([]), - scripts: exports_external3.array(ScaffoldScriptSchema3).default([]), - validationChecks: exports_external3.array(ValidationCheckSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.source?.uri?.startsWith("file://")) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Public scaffold manifest source refs cannot use local file:// URIs", - path: ["source", "uri"] - }); - } - if (value.status === "active" && value.validationChecks.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Active scaffold manifests require validation checks", - path: ["validationChecks"] - }); - } - if (value.status === "active" && value.output.requiredFiles.length === 0 && value.output.requiredDirectories.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Active scaffold manifests require at least one required file or directory", - path: ["output"] - }); - } -}); -var ScaffoldInstallStatusSchema3 = exports_external3.enum(["installed", "failed", "cancelled", "partial", "unknown"]); -var ScaffoldInstallRecordSchema3 = contractBaseSchema3(SCHEMA_IDS3.scaffoldInstallRecord).extend({ - scaffoldId: exports_external3.string().min(1), - scaffoldVersion: exports_external3.string().min(1).optional(), - manifestRef: ResourcePointerSchema3.optional(), - target: ResourcePointerSchema3, - status: ScaffoldInstallStatusSchema3, - installedAt: TimestampSchema3.optional(), - installer: ActorPointerSchema3.optional(), - packageManager: exports_external3.enum(["bun", "npm", "pnpm", "yarn", "cargo", "pip", "other"]).optional(), - options: MetadataSchema3.optional(), - generatedFiles: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "installed" && !value.installedAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Installed scaffold records require installedAt", - path: ["installedAt"] - }); - } - if (value.status === "installed" && value.generatedFiles.length === 0 && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Installed scaffold records require generated files, evidence, or proof bundle refs", - path: ["generatedFiles"] - }); - } - if ((value.status === "failed" || value.status === "partial") && value.evidenceRefs.length === 0 && value.proofBundleRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed or partial scaffold records require evidence or proof bundle refs", - path: ["evidenceRefs"] - }); - } -}); -var AppIdSchema3 = exports_external3.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "App ids must be lowercase dashed identifiers"); -var NpmPackageNameSchema3 = exports_external3.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "Must be a valid npm package name"); -var SemverSchema3 = exports_external3.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, "Must be a semver version"); -var GitShaSchema3 = exports_external3.string().regex(/^[0-9a-f]{7,40}$/, "Must be a lowercase git sha (7-40 hex chars)"); -var GithubUrlSchema3 = NonEmptyStringSchema3.refine((value) => value.startsWith("https://github.com/") || value.startsWith("git+https://github.com/"), "GitHub URLs must start with https://github.com/ or git+https://github.com/"); -var AppLifecycleSchema3 = exports_external3.enum(["active", "stub", "deprecated", "archived"]); -var ReleaseChannelSchema3 = exports_external3.enum(["stable", "beta", "canary", "internal"]); -var AppMcpSurfaceSchema3 = exports_external3.object({ - transport: exports_external3.enum(["http", "stdio"]).default("http"), - bin: exports_external3.string().min(1).optional(), - url: UriSchema3.optional() -}).strict(); -var AppHttpSurfaceSchema3 = exports_external3.object({ - healthPath: exports_external3.string().min(1).default("/health"), - port: exports_external3.number().int().positive().optional(), - baseUrl: UriSchema3.optional() -}).strict(); -var AppSurfacesSchema3 = exports_external3.object({ - bins: exports_external3.array(exports_external3.string().min(1)).default([]), - mcp: AppMcpSurfaceSchema3.optional(), - http: AppHttpSurfaceSchema3.optional() -}).strict(); -var AppSchema3 = contractBaseSchema3(SCHEMA_IDS3.app).extend({ - appId: AppIdSchema3, - npmName: NpmPackageNameSchema3, - repoFolder: AppIdSchema3, - githubUrl: GithubUrlSchema3, - projectSlug: ProjectSlugSchema3, - surfaces: AppSurfacesSchema3.default({}), - lifecycle: AppLifecycleSchema3, - releaseChannel: ReleaseChannelSchema3.default("stable"), - summary: exports_external3.string().min(1).optional(), - tags: TagsSchema3 -}).strict().superRefine((value, ctx) => { - const seenBins = new Set; - for (const [index, bin] of value.surfaces.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "App surface bins must be unique", - path: ["surfaces", "bins", index] - }); - } - seenBins.add(bin); - } -}); -var PublishPathSchema3 = exports_external3.enum(["skill", "ci", "backfilled"]); -var ReleaseSchema3 = contractBaseSchema3(SCHEMA_IDS3.release).extend({ - appId: AppIdSchema3, - package: NpmPackageNameSchema3, - version: SemverSchema3, - gitSha: GitShaSchema3, - publishedAt: TimestampSchema3, - publishPath: PublishPathSchema3, - changelogRef: ResourcePointerSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.publishPath !== "backfilled" && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "skill and ci releases require publish evidence; only backfilled releases may omit it", - path: ["evidenceRefs"] - }); - } -}); -var RolloutActionSchema3 = exports_external3.enum(["install", "update", "rollback", "freeze-blocked"]); -var RolloutVerificationSchema3 = exports_external3.object({ - cliVersion: exports_external3.string().min(1).optional(), - mcpHealth: exports_external3.enum(["ok", "degraded", "unavailable", "not_checked"]).optional() -}).strict().superRefine((value, ctx) => { - if (!value.cliVersion && value.mcpHealth === undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Rollout verification requires at least one concrete verifier field" - }); - } -}); -var RolloutRecordSchema3 = contractBaseSchema3(SCHEMA_IDS3.rolloutRecord).extend({ - appId: AppIdSchema3, - package: NpmPackageNameSchema3, - version: SemverSchema3, - machine: NonEmptyStringSchema3, - action: RolloutActionSchema3, - result: ContractStatusSchema3, - verifiedBy: RolloutVerificationSchema3.optional(), - at: TimestampSchema3, - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.action === "freeze-blocked" && value.result !== "blocked" && value.result !== "skipped") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "freeze-blocked rollout records must report result blocked or skipped", - path: ["result"] - }); - } - const hasConcreteVerification = Boolean(value.verifiedBy?.cliVersion) || value.verifiedBy?.mcpHealth !== undefined && value.verifiedBy.mcpHealth !== "not_checked"; - const hasVerifierFields = value.verifiedBy ? Object.keys(value.verifiedBy).length > 0 : false; - if ((value.action === "install" || value.action === "update") && value.result === "succeeded" && (!value.verifiedBy || hasVerifierFields && !hasConcreteVerification)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded install/update rollout records require concrete verification", - path: ["verifiedBy"] - }); - } -}); -var AnnouncementChannelKindSchema3 = exports_external3.enum([ - "email", - "telegram", - "slack", - "discord", - "x", - "blog", - "rss", - "webhook", - "github", - "other" -]); -var AnnouncementDeliveryStatusSchema3 = exports_external3.enum([ - "pending", - "queued", - "sent", - "failed", - "skipped", - "suppressed" -]); -var AnnouncementChannelSchema3 = exports_external3.object({ - channel: AnnouncementChannelKindSchema3, - status: AnnouncementDeliveryStatusSchema3, - deliveredAt: TimestampSchema3.optional(), - detail: exports_external3.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if (value.status === "sent" && !value.deliveredAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Sent announcement channels require deliveredAt", - path: ["deliveredAt"] - }); - } - if (value.status === "failed" && !value.detail) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed announcement channels require detail", - path: ["detail"] - }); - } -}); -var AnnouncementSchema3 = contractBaseSchema3(SCHEMA_IDS3.announcement).extend({ - campaignId: NonEmptyStringSchema3, - appId: AppIdSchema3.optional(), - releaseRef: ResourcePointerSchema3.optional(), - channels: exports_external3.array(AnnouncementChannelSchema3).min(1), - audienceRef: ResourcePointerSchema3, - sentAt: TimestampSchema3 -}).strict().superRefine((value, ctx) => { - if (value.releaseRef && value.releaseRef.kind !== "release") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Announcement releaseRef must use resource kind release", - path: ["releaseRef", "kind"] - }); - } - if (value.audienceRef.kind !== "audience") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Announcement audienceRef must use resource kind audience", - path: ["audienceRef", "kind"] - }); - } -}); -var AudiencePredicateKindSchema3 = exports_external3.enum(["tag", "attribute", "group"]); -var AudiencePredicateOpSchema3 = exports_external3.enum(["eq", "neq", "in", "not_in", "exists", "not_exists"]); -var AudiencePredicateValueSchema3 = exports_external3.union([exports_external3.string(), exports_external3.number(), exports_external3.boolean()]); -var AudiencePredicateSchema3 = exports_external3.object({ - kind: AudiencePredicateKindSchema3, - key: exports_external3.string().min(1).optional(), - op: AudiencePredicateOpSchema3.default("eq"), - value: AudiencePredicateValueSchema3.optional(), - values: exports_external3.array(AudiencePredicateValueSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.kind === "attribute" && !value.key) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Attribute predicates require key", - path: ["key"] - }); - } - if ((value.op === "eq" || value.op === "neq") && value.value === undefined) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "eq/neq predicates require value", - path: ["value"] - }); - } - if ((value.op === "in" || value.op === "not_in") && value.values.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "in/not_in predicates require values", - path: ["values"] - }); - } -}); -var AudienceDefinitionSchema3 = exports_external3.object({ - match: exports_external3.enum(["all", "any"]).default("all"), - predicates: exports_external3.array(AudiencePredicateSchema3).min(1) -}).strict(); -var ConsentPolicySchema3 = exports_external3.enum(["opt_in", "opt_out", "transactional", "none"]); -var AudienceSchema3 = contractBaseSchema3(SCHEMA_IDS3.audience).extend({ - audienceId: AppIdSchema3, - name: NonEmptyStringSchema3, - definition: AudienceDefinitionSchema3, - consentPolicy: ConsentPolicySchema3, - suppressionSyncedAt: OptionalTimestampSchema3 -}).strict(); -var FORBIDDEN_SHARED_CLOUD_RUNTIMES3 = ["@hasna/cloud", "open-cloud"]; -var AppCloudProviderSchema3 = exports_external3.enum([ - "aws", - "gcp", - "azure", - "cloudflare", - "vercel", - "neon", - "supabase", - "postgres", - "s3", - "rds", - "other" -]); -var AppCloudResourceSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - provider: AppCloudProviderSchema3, - kind: exports_external3.enum([ - "database", - "bucket", - "queue", - "secret", - "function", - "worker", - "cache", - "topic", - "scheduler", - "object_store", - "other" - ]), - ownerPackage: exports_external3.string().min(1), - region: exports_external3.string().min(1).optional(), - accountId: exports_external3.string().min(1).optional(), - uri: UriSchema3.optional(), - machineScoped: exports_external3.boolean().default(false) -}).strict(); -var AppCloudManifestSchema3 = contractBaseSchema3(SCHEMA_IDS3.appCloudManifest).extend({ - packageName: exports_external3.string().min(1), - packageVersion: exports_external3.string().min(1).optional(), - appId: exports_external3.string().min(1), - repository: ResourcePointerSchema3.optional(), - storageMode: exports_external3.enum(["local_only", "app_owned_cloud", "hybrid_local_cache", "external_service"]), - cloudBoundary: exports_external3.enum(["none", "app_owned", "external_service", "local_cache"]), - cloudResources: exports_external3.array(AppCloudResourceSchema3).default([]), - localCache: exports_external3.object({ - path: exports_external3.string().min(1).optional(), - pullMode: exports_external3.enum(["manual", "daemon", "ci", "none"]).default("manual"), - conflictPolicy: exports_external3.enum(["cloud_wins", "local_wins", "merge", "manual_review"]).default("manual_review") - }).strict().optional(), - forbiddenSharedRuntimes: exports_external3.array(exports_external3.string().min(1)).default([...FORBIDDEN_SHARED_CLOUD_RUNTIMES3]), - dependencies: exports_external3.array(exports_external3.string().min(1)).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const effectiveForbiddenRuntimes = new Set([...FORBIDDEN_SHARED_CLOUD_RUNTIMES3, ...value.forbiddenSharedRuntimes]); - if (effectiveForbiddenRuntimes.has(value.packageName)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "App-owned cloud manifests cannot be for a forbidden runtime", - path: ["packageName"] - }); - } - for (const runtime of FORBIDDEN_SHARED_CLOUD_RUNTIMES3) { - if (!value.forbiddenSharedRuntimes.includes(runtime)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `forbiddenSharedRuntimes must include ${runtime}`, - path: ["forbiddenSharedRuntimes"] - }); - } - } - for (const runtime of effectiveForbiddenRuntimes) { - if (value.dependencies.includes(runtime)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `App-owned cloud manifests cannot depend on ${runtime}`, - path: ["dependencies"] - }); - } - } - if (value.storageMode === "local_only" && value.cloudBoundary !== "none") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "local_only storage requires cloudBoundary none", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "app_owned_cloud" && value.cloudBoundary !== "app_owned") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "app_owned_cloud storage requires cloudBoundary app_owned", - path: ["cloudBoundary"] - }); - } - if (value.storageMode === "hybrid_local_cache") { - if (value.cloudBoundary !== "local_cache") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires cloudBoundary local_cache", - path: ["cloudBoundary"] - }); - } - if (!value.localCache) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "hybrid_local_cache storage requires localCache settings", - path: ["localCache"] - }); - } - } - if (value.storageMode === "external_service") { - if (value.cloudBoundary !== "external_service") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "external_service storage requires cloudBoundary external_service", - path: ["cloudBoundary"] - }); - } - if (value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "external_service storage must not declare app-owned cloudResources", - path: ["cloudResources"] - }); - } - } - if ((value.storageMode === "app_owned_cloud" || value.storageMode === "hybrid_local_cache") && value.cloudResources.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Cloud-backed storage modes require explicit app-owned cloudResources", - path: ["cloudResources"] - }); - } - if (value.cloudBoundary === "none" && value.cloudResources.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "cloudBoundary none cannot declare cloudResources", - path: ["cloudResources"] - }); - } - value.cloudResources.forEach((resource, index) => { - if (resource.ownerPackage !== value.packageName) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Cloud resources must be owned by the app package that declares the manifest", - path: ["cloudResources", index, "ownerPackage"] - }); - } - }); -}); -var NoCloudCheckKindSchema3 = exports_external3.enum([ - "package_manifest", - "lockfile", - "source_import", - "runtime_config", - "packed_artifact", - "published_metadata", - "app_cloud_manifest", - "remote_config", - "boundary_doc", - "other" -]); -var NoCloudFindingSeveritySchema3 = exports_external3.enum(["low", "medium", "high", "critical"]); -var NoCloudFindingSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: NoCloudCheckKindSchema3, - severity: NoCloudFindingSeveritySchema3, - path: exports_external3.string().min(1).optional(), - packageName: exports_external3.string().min(1).optional(), - pattern: exports_external3.string().min(1), - message: exports_external3.string().min(1), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict(); -var NoCloudCheckResultSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: NoCloudCheckKindSchema3, - status: ContractStatusSchema3, - target: exports_external3.string().min(1), - command: exports_external3.string().min(1).optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - findings: exports_external3.array(NoCloudFindingSchema3).default([]) -}).strict(); -var NoCloudEvidencePackSchema3 = contractBaseSchema3(SCHEMA_IDS3.noCloudEvidencePack).extend({ - subject: ResourcePointerSchema3, - packageName: exports_external3.string().min(1).optional(), - packageVersion: exports_external3.string().min(1).optional(), - generatedBy: ActorPointerSchema3.optional(), - scanMode: exports_external3.enum(["source_tree", "packed_artifact", "published_metadata", "runtime_config", "workspace", "ci"]), - status: ContractStatusSchema3, - verdict: exports_external3.enum(["passed", "failed", "warning", "not_run"]), - appCloudManifest: AppCloudManifestSchema3.optional(), - checks: exports_external3.array(NoCloudCheckResultSchema3).min(1), - findings: exports_external3.array(NoCloudFindingSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - const allFindings = [...value.findings, ...value.checks.flatMap((check) => check.findings)]; - const blockingFindings = allFindings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence requires succeeded status", path: ["status"] }); - } - if (blockingFindings.length > 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence cannot include high or critical findings", path: ["findings"] }); - } - if (value.checks.some((check) => check.status !== "succeeded")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Passed no-cloud evidence requires every check to be succeeded", path: ["checks"] }); - } - } - if (value.verdict === "failed" && allFindings.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Failed no-cloud evidence requires findings", path: ["findings"] }); - } - if (value.status === "succeeded" && value.checks.some((check) => check.status === "failed")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Succeeded no-cloud evidence cannot contain failed checks", path: ["checks"] }); - } - value.checks.forEach((check, index) => { - const checkBlockingFindings = check.findings.filter((finding) => finding.severity === "high" || finding.severity === "critical"); - if (check.status === "succeeded" && checkBlockingFindings.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded no-cloud checks cannot contain high or critical findings", - path: ["checks", index, "findings"] - }); - } - }); -}); -var ProofCheckResultSchema3 = exports_external3.object({ - checkId: exports_external3.string().min(1), - status: ContractStatusSchema3, - summary: exports_external3.string().min(1).optional(), - startedAt: OptionalTimestampSchema3, - finishedAt: OptionalTimestampSchema3, - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict(); -var ProofBundleSchema3 = contractBaseSchema3(SCHEMA_IDS3.proofBundle).extend({ - subject: ResourcePointerSchema3, - validationPlanRef: ResourcePointerSchema3.optional(), - status: ContractStatusSchema3, - verdict: exports_external3.enum(["passed", "failed", "inconclusive", "not_run"]).default("inconclusive"), - checks: exports_external3.array(ProofCheckResultSchema3).default([]), - verifier: ActorPointerSchema3.optional(), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - residualRisks: exports_external3.array(exports_external3.string().min(1)).default([]), - freshness: exports_external3.enum(["fresh", "stale", "unknown"]).default("unknown") -}).strict().superRefine((value, ctx) => { - if (value.verdict === "passed") { - if (value.status !== "succeeded") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles must have status succeeded", - path: ["status"] - }); - } - if (value.checks.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require at least one check result", - path: ["checks"] - }); - } - value.checks.forEach((check, index) => { - if (check.status !== "succeeded") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require all checks to have status succeeded", - path: ["checks", index, "status"] - }); - } - }); - const hasEvidence = value.evidenceRefs.length > 0 || value.checks.some((check) => check.evidenceRefs.length > 0); - if (!hasEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require evidence", - path: ["evidenceRefs"] - }); - } - if (!value.verifier) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Passed proof bundles require a verifier", - path: ["verifier"] - }); - } - } - if (value.verdict === "not_run" && value.checks.length > 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Not-run proof bundles cannot include check results", - path: ["checks"] - }); - } - if (value.verdict === "failed" && !value.checks.some((check) => check.status === "failed") && value.evidenceRefs.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed proof bundles require a failed check or evidence", - path: ["checks"] - }); - } -}); -var WorkRunSchema3 = contractBaseSchema3(SCHEMA_IDS3.workRun).extend({ - objective: exports_external3.string().min(1), - status: ContractStatusSchema3, - actor: ActorPointerSchema3, - traceId: exports_external3.string().min(1).optional(), - startedAt: OptionalTimestampSchema3, - finishedAt: OptionalTimestampSchema3, - constraints: exports_external3.array(exports_external3.string().min(1)).default([]), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - decisions: exports_external3.array(DecisionEnvelopeSchema3).default([]), - costEstimates: exports_external3.array(CostEstimateSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - validationPlanRefs: exports_external3.array(ResourcePointerSchema3).default([]), - proofBundleRefs: exports_external3.array(ResourcePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.startedAt && value.finishedAt && Date.parse(value.finishedAt) < Date.parse(value.startedAt)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "finishedAt must be after or equal to startedAt", - path: ["finishedAt"] - }); - } - if (TerminalStatuses3.has(value.status) && !value.finishedAt) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Terminal work runs require finishedAt", - path: ["finishedAt"] - }); - } - const hasEvidence = value.evidenceRefs.length > 0 || value.proofBundleRefs.length > 0; - if (value.status === "succeeded" && !hasEvidence) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Succeeded work runs require evidence or a proof bundle", - path: ["evidenceRefs"] - }); - } - if ((value.status === "failed" || value.status === "blocked") && !hasEvidence && value.decisions.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Failed or blocked work runs require evidence, a proof bundle, or a decision record", - path: ["evidenceRefs"] - }); - } -}); -var TrajectoryEventSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - at: TimestampSchema3, - kind: exports_external3.enum(["message", "tool_call", "command", "file_change", "error", "test", "decision", "verification", "status", "other"]), - summary: exports_external3.string().min(1), - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]), - costEstimate: CostEstimateSchema3.optional() -}).strict(); -var AgentTrajectorySchema3 = contractBaseSchema3(SCHEMA_IDS3.agentTrajectory).extend({ - actor: ActorPointerSchema3, - workRunRef: ResourcePointerSchema3.optional(), - events: exports_external3.array(TrajectoryEventSchema3).default([]), - outcome: exports_external3.enum(["succeeded", "failed", "cancelled", "blocked", "unknown"]).default("unknown"), - proofBundleRef: ResourcePointerSchema3.optional() -}).strict(); -var SERVICE_CONTRACT_VERSION3 = "v1"; -var RepoClassSchema3 = exports_external3.enum(["library", "cli-with-store", "service", "saas"]); -var DEPLOYMENT_MODES3 = ["local", "self-hosted", "cloud"]; -var DeploymentModeSchema3 = exports_external3.enum(DEPLOYMENT_MODES3); -var ServiceSurfaceStatusSchema3 = exports_external3.enum(["supported", "deferred", "unsupported"]); -var ServiceAuthModeSchema3 = exports_external3.enum(["none", "local-only", "api-key", "session", "service-token", "custom"]); -var ServiceEndpointSchema3 = exports_external3.object({ - method: exports_external3.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), - path: exports_external3.string().regex(/^\/[A-Za-z0-9_./:*-]*$/, "Endpoint paths must be absolute HTTP paths"), - public: exports_external3.boolean().default(false), - description: exports_external3.string().min(1).optional() -}).strict(); -var DeploymentReadinessGateSchema3 = exports_external3.object({ - id: exports_external3.string().min(1), - kind: exports_external3.enum(["auth", "storage", "secret-ref", "migration", "health", "readiness", "redaction", "smoke", "operator", "other"]), - required: exports_external3.boolean().default(true), - command: exports_external3.string().min(1).optional(), - evidenceRef: EvidencePointerSchema3.optional(), - status: exports_external3.enum(["pending", "passed", "failed", "blocked", "deferred"]).default("pending"), - summary: exports_external3.string().min(1).optional() -}).strict().superRefine((value, ctx) => { - if ((value.status === "passed" || value.status === "failed" || value.status === "blocked") && !value.command && !value.evidenceRef && !value.summary) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Terminal readiness gates require command, evidenceRef, or summary", - path: ["status"] - }); - } -}); -var ServiceSurfaceSchema3 = exports_external3.object({ - name: exports_external3.string().min(1), - status: ServiceSurfaceStatusSchema3, - bin: exports_external3.string().min(1).optional(), - mcpBin: exports_external3.string().min(1).optional(), - authMode: ServiceAuthModeSchema3, - deploymentModes: exports_external3.array(DeploymentModeSchema3).min(1), - health: ServiceEndpointSchema3.optional(), - readiness: ServiceEndpointSchema3.optional(), - version: ServiceEndpointSchema3.optional(), - apiBasePath: exports_external3.string().regex(/^\/v[0-9]+$/, "Stable API base path must be /vN").optional(), - openApiPath: exports_external3.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(), - deferReason: exports_external3.string().min(1).optional(), - readinessGates: exports_external3.array(DeploymentReadinessGateSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.status === "supported") { - if (!value.bin) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a serve bin", path: ["bin"] }); - } - if (!value.health) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a health endpoint", path: ["health"] }); - } - if (!value.version) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Supported service surfaces require a version endpoint", path: ["version"] }); - } - } - if ((value.status === "deferred" || value.status === "unsupported") && !value.deferReason) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Deferred or unsupported service surfaces require a deferReason", - path: ["deferReason"] - }); - } - if (value.health && value.health.path !== "/health") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Health endpoint must be /health", path: ["health", "path"] }); - } - if (value.readiness && value.readiness.path !== "/ready") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Readiness endpoint must be /ready", path: ["readiness", "path"] }); - } - if (value.version && value.version.path !== "/version") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Version endpoint must be /version", path: ["version", "path"] }); - } -}); -var STORAGE_MODES3 = ["local", "cloud"]; -var StorageModeSchema3 = exports_external3.enum(STORAGE_MODES3); -var DEPRECATED_STORAGE_MODE_ALIASES2 = ["remote", "hybrid", "self_hosted"]; -var AppNameSchema3 = exports_external3.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/, "App names must be lowercase dashed identifiers"); -var ALLOWED_BIN_SUFFIXES3 = [ - "", - "-cli", - "-mcp", - "-serve", - "-worker", - "-runner", - "-daemon", - "-migrate", - "-doctor" -]; -function allowedBinsForName3(name) { - return ALLOWED_BIN_SUFFIXES3.map((suffix) => `${name}${suffix}`); -} -function databaseUrlSecretRefFor3(name) { - return `hasna/oss/${name}/database-url`; -} -var StorageContractSchema3 = exports_external3.object({ - mode: StorageModeSchema3, - envPrefix: exports_external3.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(), - aliasEnvPrefix: exports_external3.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(), - databaseUrlSecretRef: exports_external3.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(), - sqlitePath: exports_external3.string().min(1).optional() -}).strict(); -var ServiceContractManifestSchema3 = exports_external3.object({ - $schema: exports_external3.string().min(1).optional(), - schema: exports_external3.literal(SCHEMA_IDS3.serviceContract), - name: AppNameSchema3, - class: RepoClassSchema3, - contractVersion: exports_external3.literal(SERVICE_CONTRACT_VERSION3), - kitVersion: exports_external3.string().min(1), - description: exports_external3.string().min(1).optional(), - bins: exports_external3.array(exports_external3.string().min(1)).default([]), - storage: StorageContractSchema3.optional(), - deploymentModes: exports_external3.array(DeploymentModeSchema3).default(["local"]), - serviceSurfaces: exports_external3.array(ServiceSurfaceSchema3).default([]), - metadata: MetadataSchema3.optional() -}).strict().superRefine((value, ctx) => { - const allowed = new Set(allowedBinsForName3(value.name)); - const seenBins = new Set; - for (const [index, bin] of value.bins.entries()) { - if (seenBins.has(bin)) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "Duplicate bin declaration", path: ["bins", index] }); + if (body !== undefined) { + headers["Content-Type"] = "application/json"; + init.body = JSON.stringify(body); } - seenBins.add(bin); - if (!allowed.has(bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Bin "${bin}" is not allowlisted for app "${value.name}"; allowed: ${[...allowed].join(", ")}`, - path: ["bins", index] - }); + const controller = new AbortController; + const onAbort = () => controller.abort(); + if (opts.signal) { + if (opts.signal.aborted) + controller.abort(); + else + opts.signal.addEventListener("abort", onAbort, { once: true }); } - } - const hasBin = (suffix) => seenBins.has(`${value.name}${suffix}`); - if (value.storage) { - const upper = value.name.toUpperCase().replace(/-/g, "_"); - if (value.storage.envPrefix && value.storage.envPrefix !== `HASNA_${upper}_`) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `storage.envPrefix must be HASNA_${upper}_`, - path: ["storage", "envPrefix"] - }); + const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? timeoutMs); + init.signal = controller.signal; + let response; + try { + response = await fetchImpl(url, init); + } catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + if (opts.signal?.aborted) + return { ok: false, retryable: false, error: err }; + return { ok: false, retryable: true, error: err }; + } finally { + clearTimeout(timer); + if (opts.signal) + opts.signal.removeEventListener("abort", onAbort); } - if (value.storage.databaseUrlSecretRef && value.storage.databaseUrlSecretRef !== databaseUrlSecretRefFor3(value.name)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `storage.databaseUrlSecretRef must be ${databaseUrlSecretRefFor3(value.name)}`, - path: ["storage", "databaseUrlSecretRef"] - }); + const text = await response.text(); + let parsed = undefined; + if (text.length > 0) { + try { + parsed = JSON.parse(text); + } catch { + parsed = text; + } } - if (value.storage.mode === "cloud" && !value.storage.databaseUrlSecretRef) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)", - path: ["storage", "databaseUrlSecretRef"] - }); + if (!response.ok) { + if (response.status >= 300 && response.status < 400) { + return { + ok: false, + retryable: false, + error: new HasnaHttpError(method, rel, response.status, parsed) + }; + } + if (response.status === 401 || response.status === 403) { + return { + ok: false, + retryable: false, + error: new HasnaHttpError(method, rel, response.status, parsed, { + source: credential.source, + tier: credential.tier, + guidance: authFailureGuidance(credential) + }) + }; + } + const retry = resolveRetry(opts.retry); + const retryable = retry ? retry.retryStatuses.includes(response.status) : false; + return { ok: false, retryable, error: new HasnaHttpError(method, rel, response.status, parsed) }; } + return { ok: true, value: parsed }; } - if (value.class === "library") { - if (value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "library repos must not declare storage", path: ["storage"] }); - } - if (hasBin("-serve") || hasBin("-mcp")) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "library repos must not ship a -serve or -mcp bin", - path: ["bins"] - }); + async function request(method, path, body, opts = {}) { + const upper = method.toUpperCase(); + const rel = appendQuery(path.startsWith("/") ? path : `/${path}`, opts.query); + const url = `${base}${rel}`; + const retry = resolveRetry(opts.retry); + const methodRetryable = IDEMPOTENT_METHODS.has(upper) || Boolean(opts.idempotencyKey); + const maxAttempts = retry && methodRetryable ? retry.retries + 1 : 1; + const credential = currentCredential(options.name, options.apiKey); + let last = null; + for (let attempt = 1;attempt <= maxAttempts; attempt++) { + const result = await once(upper, rel, url, body, opts, credential); + if (result.ok) + return result.value; + last = result; + const canRetry = retry !== null && methodRetryable && result.retryable && attempt < maxAttempts; + if (!canRetry) + break; + const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1)); + const jitter = Math.floor(Math.random() * (backoff / 2 + 1)); + await sleep(backoff + jitter); } + throw last.error; } - if (value.class === "cli-with-store") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "cli-with-store repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode === "local" && !value.storage.sqlitePath) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "local cli-with-store storage requires sqlitePath (~/.hasna/<name>/<name>.db)", - path: ["storage", "sqlitePath"] - }); - } - if (!seenBins.has(value.name)) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `cli-with-store repos must ship the "${value.name}" bin`, path: ["bins"] }); - } + return { + baseUrl: base, + request, + get: (path, opts) => request("GET", path, undefined, opts), + post: (path, body, opts) => request("POST", path, body, opts), + put: (path, body, opts) => request("PUT", path, body, opts), + patch: (path, body, opts) => request("PATCH", path, body, opts), + del: (path, body, opts) => request("DELETE", path, body, opts) + }; +} +function createClientTransport(name, env = process.env, overrides) { + const credentialOptions = overrides?.credentials; + const resolution = resolveClientTransport(name, env, { ...credentialOptions ? { credentials: credentialOptions } : {} }); + if (resolution.misconfigured) { + throw new Error(resolution.warning ?? `Client for '${name}' is misconfigured for the API client.`); } - if (value.class === "service") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "service repos must declare storage", path: ["storage"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `service repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "service repos must declare at least one service surface", - path: ["serviceSurfaces"] - }); - } + if (resolution.transport === "sqlite" || !resolution.baseUrl) { + return { transport: "sqlite", client: null, resolution }; } - if (value.class === "saas") { - if (!value.storage) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must declare storage", path: ["storage"] }); - } else if (value.storage.mode !== "cloud") { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must use cloud storage mode", path: ["storage", "mode"] }); - } - if (!hasBin("-serve")) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: `saas repos must ship the "${value.name}-serve" bin`, path: ["bins"] }); - } - if (value.serviceSurfaces.length === 0) { - ctx.addIssue({ code: exports_external3.ZodIssueCode.custom, message: "saas repos must declare at least one service surface", path: ["serviceSurfaces"] }); + const credentialProvider = () => { + const resolved = resolveCredential(name, env, credentialOptions); + if (!resolved) { + throw new Error(`Client for '${name}' resolved to the http transport but no API key is available any more. ` + `Looked at ${credentialDiskSourcesForMessage(name, env)}, then the environment. ` + `A credential file that was removed after this client was built is the usual cause.`); } + return resolved; + }; + return { + transport: "http", + client: createHasnaHttpTransport({ + name, + baseUrl: resolution.baseUrl, + apiKey: credentialProvider, + ...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {}, + ...overrides?.headers ? { headers: overrides.headers } : {}, + ...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {}, + ...overrides?.retry !== undefined ? { retry: overrides.retry } : {}, + ...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {} + }), + resolution + }; +} +function resourcePath(resource) { + const trimmed = resource.replace(/^\/+|\/+$/g, ""); + if (!trimmed) + throw new Error("resource must be a non-empty path segment"); + return `/${trimmed}`; +} +function entityPath(resource, id) { + if (id === undefined || id === null || `${id}`.length === 0) { + throw new Error("id must be a non-empty string"); } - for (const [index, surface] of value.serviceSurfaces.entries()) { - if (surface.bin && !seenBins.has(surface.bin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface bin "${surface.bin}" must be declared in bins`, - path: ["serviceSurfaces", index, "bin"] - }); - } - if (surface.mcpBin && !seenBins.has(surface.mcpBin)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface MCP bin "${surface.mcpBin}" must be declared in bins`, - path: ["serviceSurfaces", index, "mcpBin"] - }); - } - for (const [modeIndex, deploymentMode] of surface.deploymentModes.entries()) { - if (!value.deploymentModes.includes(deploymentMode)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `Service surface deployment mode "${deploymentMode}" must be declared in deploymentModes`, - path: ["serviceSurfaces", index, "deploymentModes", modeIndex] - }); - } + return `${resourcePath(resource)}/${encodeURIComponent(String(id))}`; +} +function newIdempotencyKey() { + const g = globalThis; + if (g.crypto?.randomUUID) + return g.crypto.randomUUID(); + return `idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`; +} +function extractItems(raw) { + if (Array.isArray(raw)) + return raw; + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["items", "data", "results", "rows", "records"]) { + if (Array.isArray(obj[key])) + return obj[key]; } } -}); -var HealthResponseSchema3 = exports_external3.object({ - status: exports_external3.enum(["ok", "degraded", "unavailable"]), - version: exports_external3.string().min(1), - mode: StorageModeSchema3 -}).strict(); -var ReadyResponseSchema3 = exports_external3.object({ - ready: exports_external3.boolean(), - reason: exports_external3.string().min(1).optional() -}).strict(); -var VersionResponseSchema3 = exports_external3.object({ - version: exports_external3.string().min(1) -}).strict(); -var CommsSeveritySchema3 = exports_external3.enum(["info", "notice", "breaking", "critical"]); -var CommsEventTypeSchema3 = exports_external3.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/, "Comms event types must be 2-4 lowercase dot-separated segments (<source>.<entity>.<action>)"); -var COMMS_SEVERITY_TAGS3 = ["FREEZE", "UNFREEZE", "BREAKING", "CUTOVER", "POLICY", "RELEASE"]; -var CommsSeverityTagSchema3 = exports_external3.enum(COMMS_SEVERITY_TAGS3); -var CommsScopeSchema3 = exports_external3.enum(["fleet", "package", "machine"]); -var CommsEventEnvelopeSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsEventEnvelope).extend({ - type: CommsEventTypeSchema3, - severity: CommsSeveritySchema3, - scope: CommsScopeSchema3, - summary: exports_external3.string().min(1).optional(), - source: ActorPointerSchema3.optional(), - affected_packages: exports_external3.array(NonEmptyStringSchema3).default([]), - affected_machines: exports_external3.array(NonEmptyStringSchema3).default([]), - action_required: exports_external3.boolean().default(false), - ack_by: TimestampSchema3.optional(), - dedupe_key: NonEmptyStringSchema3, - resourceRefs: exports_external3.array(ResourcePointerSchema3).default([]), - evidenceRefs: exports_external3.array(EvidencePointerSchema3).default([]) -}).strict().superRefine((value, ctx) => { - if (value.scope === "package" && value.affected_packages.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Package-scoped comms events require affected_packages", - path: ["affected_packages"] - }); - } - if (value.scope === "machine" && value.affected_machines.length === 0) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Machine-scoped comms events require affected_machines", - path: ["affected_machines"] - }); - } - if (value.ack_by && !value.action_required) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Comms events with an ack_by deadline require action_required", - path: ["action_required"] - }); - } - if (value.type === "fleet.freeze" || value.type === "fleet.unfreeze") { - if (value.severity !== "critical") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events are always critical`, - path: ["severity"] - }); - } - if (value.scope !== "fleet") { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events are always fleet-scoped`, - path: ["scope"] - }); - } - if (!value.action_required) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.type} events require action_required`, - path: ["action_required"] - }); + return []; +} +function extractTotal(raw) { + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["total", "count", "totalCount", "total_count"]) { + if (typeof obj[key] === "number") + return obj[key]; } } -}); -var CommsChannelClassSchema3 = exports_external3.enum(["fleet", "package", "product", "loop-lane", "initiative", "personal"]); -var CommsChannelNoiseSchema3 = exports_external3.enum(["quiet", "work", "firehose"]); -var CommsUntilHorizonSchema3 = NonEmptyStringSchema3.refine((value) => /^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(value), "until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:<todos-id>)"); -var CommsChannelMetadataSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsChannelMetadata).extend({ - class: CommsChannelClassSchema3, - noise: CommsChannelNoiseSchema3.optional(), - owner: NonEmptyStringSchema3.optional(), - until: CommsUntilHorizonSchema3.optional(), - successor: NonEmptyStringSchema3.optional() -}).strict().superRefine((value, ctx) => { - if (value.class === "initiative") { - if (!value.owner) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Initiative channels require an owner", - path: ["owner"] - }); - } - if (!value.until) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: "Initiative channels require an until horizon (date or gate id)", - path: ["until"] - }); + return null; +} +function extractCursor(raw) { + if (raw && typeof raw === "object") { + const obj = raw; + for (const key of ["cursor", "nextCursor", "next_cursor", "next"]) { + if (typeof obj[key] === "string") + return obj[key]; } } -}); -var COMMS_SEVERITY_TAG_INFO3 = { - FREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.freeze" }, - UNFREEZE: { defaultSeverity: "critical", allowedSeverities: ["critical"], requiredEventType: "fleet.unfreeze" }, - BREAKING: { defaultSeverity: "breaking", allowedSeverities: ["breaking"], requiredEventType: null }, - CUTOVER: { defaultSeverity: "notice", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - POLICY: { defaultSeverity: "breaking", allowedSeverities: ["notice", "breaking"], requiredEventType: null }, - RELEASE: { defaultSeverity: "info", allowedSeverities: ["info", "notice"], requiredEventType: null } -}; -var CommsMessageMetadataSchema3 = contractBaseSchema3(SCHEMA_IDS3.commsMessageMetadata).extend({ - tag: CommsSeverityTagSchema3, - envelope: CommsEventEnvelopeSchema3 -}).strict().superRefine((value, ctx) => { - const info = COMMS_SEVERITY_TAG_INFO3[value.tag]; - if (!info.allowedSeverities.includes(value.envelope.severity)) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `[${value.tag}] posts allow severities ${info.allowedSeverities.join(", ")}`, - path: ["envelope", "severity"] - }); - } - if (info.requiredEventType && value.envelope.type !== info.requiredEventType) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `[${value.tag}] posts require event type ${info.requiredEventType}`, - path: ["envelope", "type"] - }); - } - for (const [tag, tagInfo] of Object.entries(COMMS_SEVERITY_TAG_INFO3)) { - if (tagInfo.requiredEventType === value.envelope.type && value.tag !== tag) { - ctx.addIssue({ - code: exports_external3.ZodIssueCode.custom, - message: `${value.envelope.type} events must use the [${tag}] tag`, - path: ["tag"] + return null; +} +function createHasnaStorageClient(name, transport) { + return { + name, + baseUrl: transport.baseUrl, + transport, + async list(resource, options = {}) { + const raw = await transport.get(resourcePath(resource), options); + return { + items: extractItems(raw), + total: extractTotal(raw), + cursor: extractCursor(raw), + raw + }; + }, + async get(resource, id, options = {}) { + try { + return await transport.get(entityPath(resource, id), options); + } catch (error) { + if (error instanceof HasnaHttpError && error.status === 404) + return null; + throw error; + } + }, + async create(resource, body, options = {}) { + const { idempotencyKey, ...rest } = options; + return transport.post(resourcePath(resource), body, { + ...rest, + idempotencyKey: idempotencyKey ?? newIdempotencyKey() }); + }, + async update(resource, id, patch, options = {}) { + const { method = "PATCH", idempotencyKey, ...rest } = options; + const call = method === "PUT" ? transport.put : transport.patch; + return call(entityPath(resource, id), patch, { ...rest, ...idempotencyKey ? { idempotencyKey } : {} }); + }, + async delete(resource, id, options = {}) { + try { + await transport.del(entityPath(resource, id), undefined, options); + } catch (error) { + if (error instanceof HasnaHttpError && error.status === 404) + return; + throw error; + } } + }; +} +function resolveStorageClient(name, env = process.env, overrides) { + const wired = createClientTransport(name, env, overrides); + if (wired.transport === "http") { + return { transport: "http", client: createHasnaStorageClient(name, wired.client) }; } -}); -var ContractSchemaRegistry3 = { - [SCHEMA_IDS3.actorRef]: ActorRefSchema3, - [SCHEMA_IDS3.resourceRef]: ResourceRefSchema3, - [SCHEMA_IDS3.evidenceRef]: EvidenceRefSchema3, - [SCHEMA_IDS3.workRun]: WorkRunSchema3, - [SCHEMA_IDS3.decisionEnvelope]: DecisionEnvelopeSchema3, - [SCHEMA_IDS3.costEstimate]: CostEstimateSchema3, - [SCHEMA_IDS3.capabilityCard]: CapabilityCardSchema3, - [SCHEMA_IDS3.providerLiveModeStandard]: ProviderLiveModeStandardSchema3, - [SCHEMA_IDS3.contextPack]: ContextPackSchema3, - [SCHEMA_IDS3.integrationRef]: IntegrationRefSchema3, - [SCHEMA_IDS3.projectManifest]: ProjectManifestSchema3, - [SCHEMA_IDS3.projectPanel]: ProjectPanelSchema3, - [SCHEMA_IDS3.projectSnapshot]: ProjectSnapshotSchema3, - [SCHEMA_IDS3.renderManifest]: RenderManifestSchema3, - [SCHEMA_IDS3.agentTrajectory]: AgentTrajectorySchema3, - [SCHEMA_IDS3.validationPlan]: ValidationPlanSchema3, - [SCHEMA_IDS3.proofBundle]: ProofBundleSchema3, - [SCHEMA_IDS3.scaffoldManifest]: ScaffoldManifestSchema3, - [SCHEMA_IDS3.scaffoldInstallRecord]: ScaffoldInstallRecordSchema3, - [SCHEMA_IDS3.appCloudManifest]: AppCloudManifestSchema3, - [SCHEMA_IDS3.noCloudEvidencePack]: NoCloudEvidencePackSchema3, - [SCHEMA_IDS3.serviceContract]: ServiceContractManifestSchema3, - [SCHEMA_IDS3.commsEventEnvelope]: CommsEventEnvelopeSchema3, - [SCHEMA_IDS3.commsChannelMetadata]: CommsChannelMetadataSchema3, - [SCHEMA_IDS3.commsMessageMetadata]: CommsMessageMetadataSchema3, - [SCHEMA_IDS3.app]: AppSchema3, - [SCHEMA_IDS3.release]: ReleaseSchema3, - [SCHEMA_IDS3.rolloutRecord]: RolloutRecordSchema3, - [SCHEMA_IDS3.announcement]: AnnouncementSchema3, - [SCHEMA_IDS3.audience]: AudienceSchema3 -}; + return { transport: "sqlite", client: null }; +} + +// node_modules/@hasna/contracts/dist/client/transport.js +function envToken2(name) { + return name.toUpperCase().replace(/-/g, "_"); +} +function clientTransportEnvKeys2(name) { + const envSegment = envToken2(name); + return { + modeKeys: [ + `HASNA_${envSegment}_STORAGE_MODE`, + `HASNA_${envSegment}_MODE`, + `${envSegment}_STORAGE_MODE`, + `${envSegment}_MODE` + ], + apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`], + apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`] + }; +} +var MAX_CREDENTIAL_FILE_BYTES2 = 64 * 1024; +var INSPECT_CUSTOM2 = Symbol.for("nodejs.util.inspect.custom"); +var DEPRECATION_REGISTRY2 = Symbol.for("hasna:contracts:credentialDeprecationNotices"); +var IDEMPOTENT_METHODS2 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]); +var AUTHORITY_OVERRIDE_HEADERS2 = new Set([ + "host", + ":authority", + "forwarded", + "x-forwarded-host", + "x-original-host" +]); + +// node_modules/@hasna/contracts/dist/mode.js function normalizeStorageMode2(value) { const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES2.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); } // src/generated/storage-kit/mode.ts -var DEPRECATED_STORAGE_MODE_ALIASES3 = [ - "remote", - "hybrid", - "self_hosted" -]; function normalizeStorageMode3(value) { const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") - return { mode: "cloud", deprecatedAlias: null }; - if (DEPRECATED_STORAGE_MODE_ALIASES3.includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); + if (normalized === "sqlite") + return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") + return { mode: "postgres" }; + throw new Error(`Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`); } function envToken3(name) { return name.toUpperCase().replace(/-/g, "_"); @@ -18689,21 +1165,17 @@ function resolveStorageMode(name, env = process.env) { const modeHit = firstEnv(env, modeKeys); if (!modeHit) { return { - mode: "local", - source: "default", - deprecatedAlias: null, + mode: databaseUrlPresent ? "postgres" : "sqlite", + source: databaseUrlPresent ? databaseUrlSource : "default", databaseUrlPresent, databaseUrlSource, warning: null }; } - const { mode, deprecatedAlias } = normalizeStorageMode3(modeHit.value); + const { mode } = normalizeStorageMode3(modeHit.value); const warnings = []; - if (deprecatedAlias) { - warnings.push(`Deprecated storage mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Set ${modeKeys[0]}=cloud instead.`); - } - if (mode === "cloud" && !databaseUrlPresent) { - warnings.push(`cloud mode needs ${databaseUrlKeys[0]} (PURE REMOTE: reads and writes go to cloud Postgres).`); + if (mode === "postgres" && !databaseUrlPresent) { + warnings.push(`postgres storage needs ${databaseUrlKeys[0]} (reads and writes go to PostgreSQL).`); } if (modeHit.key !== modeKeys[0]) { warnings.push(`Using alias env ${modeHit.key}; the canonical key is ${modeKeys[0]}.`); @@ -18711,7 +1183,6 @@ function resolveStorageMode(name, env = process.env) { return { mode, source: modeHit.key, - deprecatedAlias, databaseUrlPresent, databaseUrlSource, warning: warnings.length > 0 ? warnings.join(" ") : null @@ -18723,7 +1194,7 @@ function resolveDatabaseUrl(name, env = process.env) { return hit ? hit.value : null; } // src/generated/storage-kit/tls.ts -import { readFileSync as readFileSync2 } from "fs"; +import { readFileSync as readFileSync3 } from "fs"; function sslModeFromConnectionString(connectionString) { const queryStart = connectionString.indexOf("?"); const params = new URLSearchParams(queryStart === -1 ? "" : connectionString.slice(queryStart + 1)); @@ -18753,16 +1224,16 @@ function loadCaBundle(options) { return options.ca; const path = options.caCertPath ?? env.PGSSLROOTCERT ?? env.NODE_EXTRA_CA_CERTS; if (path && path.trim()) - return readFileSync2(path.trim(), "utf8"); + return readFileSync3(path.trim(), "utf8"); return null; } function resolveTlsConfig(connectionString, options = {}) { const mode = sslModeFromConnectionString(connectionString); - if (mode === "disable") { + if (mode === "disable" || mode === "prefer") { return; } const ca = loadCaBundle(options); - if (mode === "prefer" || mode === "require") { + if (mode === "require") { return ca ? { rejectUnauthorized: false, ca } : { rejectUnauthorized: false }; } if (!ca) { @@ -18844,15 +1315,15 @@ function createPgPool(options) { config.application_name = options.applicationName; return new pg.Pool(config); } -function createCloudPoolFromEnv(appName, options = {}) { +function createServerPoolFromEnv(appName, options = {}) { const env = options.env ?? process.env; const resolution = resolveStorageMode(appName, env); - if (resolution.mode !== "cloud") { - throw new Error(`createCloudPoolFromEnv requires ${appName} storage mode 'cloud', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=cloud.`); + if (resolution.mode !== "postgres") { + throw new Error(`createServerPoolFromEnv requires ${appName} storage mode 'postgres', got '${resolution.mode}'. ` + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=postgres.`); } const connectionString = resolveDatabaseUrl(appName, env); if (!connectionString) { - throw new Error(`cloud mode for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); + throw new Error(`postgres storage for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`); } const pool = createPgPool({ connectionString, @@ -18880,9 +1351,6 @@ function checksumSql(sql) { function defineMigration(id, sql) { return Object.freeze({ id, sql: sql.trim(), checksum: checksumSql(sql) }); } -function hasTransaction(client) { - return typeof client.transaction === "function"; -} class MigrationLedger { client; @@ -18947,30 +1415,11 @@ class MigrationLedger { for (const item of plan) { if (item.state === "already_applied") continue; - await this.applyPendingMigration(item.migration); + await this.client.execute(item.migration.sql); + await this.client.execute(`INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, [item.migration.id, item.migration.checksum]); } return { dryRun, applied: await this.readApplied(), plan }; } - async applyPendingMigration(migration) { - const apply = async (client) => { - await client.execute(migration.sql); - await client.execute(`INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, [migration.id, migration.checksum]); - }; - if (hasTransaction(this.client)) { - await this.client.transaction(apply); - return; - } - await this.client.execute("BEGIN"); - try { - await apply(this.client); - await this.client.execute("COMMIT"); - } catch (error) { - try { - await this.client.execute("ROLLBACK"); - } catch {} - throw error; - } - } } function createMigrationLedger(client, migrations, options = {}) { return new MigrationLedger(client, migrations, options); @@ -19007,7 +1456,7 @@ async function checkReady(client, migrations, options = {}) { } // src/generated/storage-kit/index.ts -var KIT_VERSION = "0.4.0"; +var KIT_VERSION = "0.8.5"; // src/net-guard.ts var NETWORK_GUARD_ENV = "NODE_ENV"; @@ -19070,7 +1519,7 @@ function assertOutboundRequestAllowed(input, env = process.env) { } if (isLoopbackHostname(url.hostname)) return; - throw new KnowledgeNetworkGuardError(`knowledge: refused a non-loopback ${url.protocol.replace(":", "")} request while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). This process resolved to the cloud backend under test, which means a " + "read or write was about to leave the machine and reach the live store. Select the mode explicitly " + `(${"HASNA_KNOWLEDGE_STORAGE_MODE"}=local) or point the API URL at 127.0.0.1 for a hermetic test.`, { scheme: url.protocol.replace(":", ""), port: url.port }); + throw new KnowledgeNetworkGuardError(`knowledge: refused a non-loopback ${url.protocol.replace(":", "")} request while ${NETWORK_GUARD_ENV}=test ` + "(target host withheld on purpose). This process resolved to the cloud backend under test, which means a " + "read or write was about to leave the machine and reach the live store. Select the mode explicitly " + `(${"HASNA_KNOWLEDGE_STORAGE_MODE"}=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`, { scheme: url.protocol.replace(":", ""), port: url.port }); } var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); var MAX_GUARDED_REDIRECTS = 5; @@ -19142,33 +1591,30 @@ function resolveKnowledgeModeSelection(env = process.env) { throw new Error(`knowledge: ${name}=${value} is not a valid mode. ${message}`); } const warnings = []; - if (normalized.deprecatedAlias) { - warnings.push(`Deprecated mode '${normalized.deprecatedAlias}' from ${name} is treated as 'cloud'. Prefer ${canonicalModeKey}=cloud.`); - } if (name !== canonicalModeKey) { warnings.push(`Using alias env ${name}; the canonical key is ${canonicalModeKey}.`); } - if (normalized.mode === "local" && pointers.length > 0) { - warnings.push(`${name}=local pins the on-box store; ${pointers.join(", ")} are set but ignored.`); + if (normalized.mode === "sqlite" && pointers.length > 0) { + warnings.push(`${name}=sqlite pins the on-box store; ${pointers.join(", ")} are set but ignored.`); } return { mode: normalized.mode, source: { kind: "env", name, value }, pointer_env_present: pointers, - pointer_ignored: normalized.mode === "local" && pointers.length > 0, + pointer_ignored: normalized.mode === "sqlite" && pointers.length > 0, warning: warnings.length > 0 ? warnings.join(" ") : null }; } return { - mode: "local", + mode: "sqlite", source: { kind: "default", name: null, value: null }, pointer_env_present: pointers, pointer_ignored: pointers.length > 0, - warning: pointers.length > 0 ? `${pointers.join(", ")} are set but do NOT select a backend: mode is local by default. ` + `Set ${canonicalModeKey}=cloud to route reads and writes to the API, or unset those vars to silence this note.` : null + warning: pointers.length > 0 ? `${pointers.join(", ")} are set but do NOT select a backend: mode is sqlite by default. ` + `Set ${canonicalModeKey}=postgres to route reads and writes to the API, or unset those vars to silence this note.` : null }; } -var SERVER_MODE_CANDIDATES = ["postgres", "cloud", "self_hosted"]; -var LOCAL_MODE_CANDIDATES = ["sqlite", "local"]; +var SERVER_MODE_CANDIDATES = ["postgres"]; +var LOCAL_MODE_CANDIDATES = ["sqlite"]; var derivedTokenCache = new Map; function deriveToken(candidates, normalize, constantName) { const useCache = normalize === normalizeStorageMode2; @@ -19194,7 +1640,7 @@ function localStorageMode(normalize = normalizeStorageMode2) { return deriveToken(LOCAL_MODE_CANDIDATES, normalize, "LOCAL_MODE_CANDIDATES"); } function contractsStorageModeFor(mode2, normalize = normalizeStorageMode2) { - return mode2 === "cloud" ? serverStorageMode(normalize) : localStorageMode(normalize); + return mode2 === "postgres" ? serverStorageMode(normalize) : localStorageMode(normalize); } function pinnedTransportEnv(env, mode2) { return { ...env, [KNOWLEDGE_MODE_ENV_KEYS[0]]: contractsStorageModeFor(mode2) }; @@ -19203,7 +1649,7 @@ function knowledgeModeReport(env = process.env) { const resolution = resolveKnowledgeModeSelection(env); return { ...resolution, - store_transport: resolution.mode === "cloud" ? "api" : "local", + store_transport: resolution.mode === "postgres" ? "api" : "local", api_key_present: presentEnvNames(env, KNOWLEDGE_API_KEY_ENV_KEYS).length > 0, network_guard_active: isNetworkGuardActive(env) }; @@ -19334,17 +1780,17 @@ function isNotFound(error) { return Boolean(error && typeof error === "object" && error.status === 404); } function resolveKnowledgeCloudStore(env = process.env) { - if (resolveKnowledgeModeSelection(env).mode !== "cloud") + if (resolveKnowledgeModeSelection(env).mode !== "postgres") return null; - const resolved = resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "cloud"), transportOverrides(env)); - if (resolved.transport !== "cloud-http") + const resolved = resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "postgres"), transportOverrides(env)); + if (resolved.transport !== "http") return null; return wrap(resolved.client); } function isKnowledgeApiMode(env = process.env) { - if (resolveKnowledgeModeSelection(env).mode !== "cloud") + if (resolveKnowledgeModeSelection(env).mode !== "postgres") return false; - return resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "cloud"), transportOverrides(env)).transport === "cloud-http"; + return resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, "postgres"), transportOverrides(env)).transport === "http"; } async function fetchAllCloudItems(store) { const pageSize = 200; @@ -20032,7 +2478,6 @@ var STORAGE_TABLES = [ "knowledge_sync_imports" ]; var KNOWLEDGE_STORAGE_TABLES = STORAGE_TABLES; -var DEPRECATED_CLOUD_ALIASES = ["remote", "hybrid", "self_hosted"]; var KNOWLEDGE_STORAGE_MODE_ENV = "HASNA_KNOWLEDGE_STORAGE_MODE"; var KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV = "KNOWLEDGE_STORAGE_MODE"; var STORAGE_MODE_ENV = [KNOWLEDGE_STORAGE_MODE_ENV, KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV]; @@ -20042,12 +2487,10 @@ function readEnv(name) { } function normalizeStorageMode4(value) { const normalized = value?.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") - return "local"; - if (normalized === "cloud") - return "cloud"; - if (normalized && DEPRECATED_CLOUD_ALIASES.includes(normalized)) - return "cloud"; + if (normalized === "sqlite") + return "sqlite"; + if (normalized === "postgres" || normalized === "postgresql") + return "postgres"; return; } function openScopedDb(options = {}) { @@ -20063,7 +2506,7 @@ function getStorageMode() { const mode2 = normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_ENV)) ?? normalizeStorageMode4(readEnv(KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV)); if (mode2) return mode2; - return "local"; + return "sqlite"; } function getSyncMetaAll(options = {}) { const local = openScopedDb(options); @@ -20119,7 +2562,7 @@ function ensureSyncMetaTable(db) { // src/db/remote-storage.ts var KNOWLEDGE_APP_NAME = "knowledge"; function createKnowledgeCloudClient() { - return createCloudPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; + return createServerPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: "@hasna/knowledge" }).client; } // src/db/pg-migrations.ts var PG_MIGRATIONS = [ @@ -20585,6 +3028,7 @@ export { resolveStorageMode, resolveDatabaseUrl, parseStorageTables, + normalizeStorageMode3 as normalizeStorageMode, normalizeStorageMode3 as normalizeCloudStorageMode, getSyncMetaAll, getStorageStatus, diff --git a/hasna.contract.json b/hasna.contract.json index d99bdd4..46e921d 100644 --- a/hasna.contract.json +++ b/hasna.contract.json @@ -3,11 +3,15 @@ "name": "knowledge", "class": "service", "contractVersion": "v1", - "kitVersion": "0.4.1", - "description": "Agent-friendly knowledge store. CLI + MCP + HTTP API (knowledge-serve) + generated SDK. Local mode uses SQLite at ~/.hasna/knowledge/knowledge.db; cloud mode (HASNA_KNOWLEDGE_STORAGE_MODE=cloud) is PURE REMOTE per Amendment A1: the serve process reads/writes the shared cloud Postgres directly and stores artifacts in S3, with API-key auth via @hasna/contracts.", - "bins": ["knowledge", "knowledge-mcp", "knowledge-serve"], + "kitVersion": "0.8.5", + "description": "Agent-friendly knowledge store. CLI + MCP + HTTP API (knowledge-serve) + generated SDK. SQLite backend uses ~/.hasna/knowledge/knowledge.db; postgres backend (HASNA_KNOWLEDGE_STORAGE_MODE=postgres) routes clients through the HTTP API and lets knowledge-serve read/write the shared Postgres directly, with API-key auth via @hasna/contracts.", + "bins": [ + "knowledge", + "knowledge-mcp", + "knowledge-serve" + ], "storage": { - "mode": "local", + "mode": "sqlite", "envPrefix": "HASNA_KNOWLEDGE_", "aliasEnvPrefix": "KNOWLEDGE_", "databaseUrlSecretRef": "hasna/oss/knowledge/database-url", @@ -23,7 +27,10 @@ "apiVersion": "v1", "auth": "api-key", "signingSecretSecretRef": "hasna/oss/knowledge/api-key-signing-secret", - "migrationCommand": ["bun", "scripts/apply-cloud-migrations.mjs"], + "migrationCommand": [ + "bun", + "scripts/apply-cloud-migrations.mjs" + ], "ownerDatabaseUrlSecretRef": "hasna/oss/knowledge/database-url-owner" }, "client": { diff --git a/package.json b/package.json index 4f0c573..c74834f 100644 --- a/package.json +++ b/package.json @@ -101,7 +101,7 @@ }, "devDependencies": { "@electric-sql/pglite": "^0.5.4", - "@hasna/contracts": "0.5.2", + "@hasna/contracts": "0.8.5", "@types/bun": "^1.3.14", "@types/pg": "^8.15.6" } diff --git a/scripts/apply-cloud-migrations.mjs b/scripts/apply-cloud-migrations.mjs index 2e7f957..a043e16 100644 --- a/scripts/apply-cloud-migrations.mjs +++ b/scripts/apply-cloud-migrations.mjs @@ -4,7 +4,7 @@ * storage kit's MigrationLedger (checksum ledger + drift/downgrade guards). * * PURE REMOTE (Amendment A1): runs against the cloud Postgres only. Requires: - * HASNA_KNOWLEDGE_STORAGE_MODE=cloud + * HASNA_KNOWLEDGE_STORAGE_MODE=postgres * HASNA_KNOWLEDGE_DATABASE_URL=postgres://... (never logged) * * Usage: diff --git a/src/agent.ts b/src/agent.ts index 165bfd5..3c75df9 100644 --- a/src/agent.ts +++ b/src/agent.ts @@ -372,7 +372,7 @@ export interface KnowledgePromptOverItemsOptions /** * Run an `ask`/`build` prompt against an in-memory knowledge-item corpus — the - * api (self_hosted / cloud) path. Retrieval reads the shared cloud items (fetched + * postgres/API path. Retrieval reads the shared API items (fetched * through the item Store); the LLM runs client-side with the caller's provider * key. There is no local sqlite catalog, so run telemetry is not persisted to a * local db (it would be split-brain); the run id is still returned for the shape. diff --git a/src/cli.ts b/src/cli.ts index 30694ce..35689ef 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -489,7 +489,7 @@ function printCommandHelp(command: string): void { if (command === 'inventory') { console.log('Usage: knowledge inventory [--scope local|global|project] [--limit <n>] [--include-archived] [--verbose] [--json]'); return; } if (command === 'project-panel') { console.log('Usage: knowledge project-panel --project <id|name|slug> [--scope project|local|global] [--limit <n>] [--include-archived] [--json|--contract]'); return; } if (command === 'paths') { console.log('Usage: knowledge paths [--scope local|global|project] [--verbose] [--json]'); return; } - if (command === 'mode') { console.log(`Usage: knowledge mode [--json]\n Reports which backend this process would use — local (on-box store) or cloud (HTTP /v1) — and\n which env var selected it. Reads the environment only: no store is opened, no config file is read,\n and no request is made, so it is safe on a machine with no config and no network.\n Selection is EXPLICIT-ONLY: set ${KNOWLEDGE_MODE_ENV_KEYS[0]}=local|cloud. Setting only\n ${KNOWLEDGE_API_URL_ENV_KEYS[0]} / ${KNOWLEDGE_API_KEY_ENV_KEYS[0]} does NOT switch backends;\n those are reported as present-but-ignored pointers. Env var NAMES are printed, never values.`); return; } + if (command === 'mode') { console.log(`Usage: knowledge mode [--json]\n Reports which backend this process would use — sqlite (on-box store) or postgres (HTTP /v1) — and\n which env var selected it. Reads the environment only: no store is opened, no config file is read,\n and no request is made, so it is safe on a machine with no config and no network.\n Selection is EXPLICIT-ONLY: set ${KNOWLEDGE_MODE_ENV_KEYS[0]}=sqlite|postgres. Setting only\n ${KNOWLEDGE_API_URL_ENV_KEYS[0]} / ${KNOWLEDGE_API_KEY_ENV_KEYS[0]} does NOT switch backends;\n those are reported as present-but-ignored pointers. Env var NAMES are printed, never values.`); return; } if (command === 'setup') { console.log('Usage: knowledge setup --mode local|hosted [--api-url https://...] [--canonical-example] [--scope local|global|project] [--json]'); return; } if (command === 'auth') { console.log('Usage: knowledge auth login|whoami|logout [--api-key <key>] [--email <email>] [--org <slug>] [--api-url https://...] [--scope local|global|project] [--json]'); return; } if (command === 'storage') { console.log('Usage: knowledge storage status|validate|repair-artifact-keys|migrate-legacy-path|merge-legacy-path [--approve-write --approved-by <name>] [--scope local|global|project] [--json]\n knowledge storage import-legacy [--dry-run] [--scope global] [--json]'); return; } @@ -559,10 +559,10 @@ function compactObjectFallback(data: unknown): string { * those variables holds an API key and another holds a URL. */ function formatMode(report: KnowledgeModeReport): string { - const backend = report.mode === 'cloud' ? 'cloud (HTTP /v1 API)' : 'local (on-box store)'; + const backend = report.mode === 'postgres' ? 'postgres (HTTP /v1 API)' : 'sqlite (on-box store)'; const chose = report.source.kind === 'env' ? `selected by ${report.source.name}=${report.source.value}` - : `default (no mode var set; set ${KNOWLEDGE_MODE_ENV_KEYS[0]}=cloud to use the API)`; + : `default (no mode var set; set ${KNOWLEDGE_MODE_ENV_KEYS[0]}=postgres to use the API)`; const lines = [`Knowledge mode: ${backend}`, ` ${chose}`]; if (report.pointer_env_present.length > 0) { const verb = report.pointer_ignored ? 'present but IGNORED for mode selection' : 'present'; diff --git a/src/cloud-store.ts b/src/cloud-store.ts index aa6fcde..199631d 100644 --- a/src/cloud-store.ts +++ b/src/cloud-store.ts @@ -265,17 +265,22 @@ function isNotFound(error: unknown): boolean { /** * Resolve the cloud knowledge store from the environment. Returns a ready - * {@link KnowledgeCloudStore} when the mode is explicitly cloud, else `null` so - * the caller uses the local db.json store. Throws if cloud was requested but + * {@link KnowledgeCloudStore} when the backend is explicitly postgres, else + * `null` so the caller uses the local db.json store. Throws if postgres was + * requested but * misconfigured (never silent local drift). * * On the local path the contracts resolver is not called at all: no transport is * built, no key is read, and there is nothing for a second layer to infer from. */ export function resolveKnowledgeCloudStore(env: NodeJS.ProcessEnv = process.env): KnowledgeCloudStore | null { - if (resolveKnowledgeModeSelection(env).mode !== 'cloud') return null; - const resolved = resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, 'cloud'), transportOverrides(env)); - if (resolved.transport !== 'cloud-http') return null; + if (resolveKnowledgeModeSelection(env).mode !== 'postgres') return null; + const resolved = resolveStorageClient( + KNOWLEDGE_APP_SLUG, + pinnedTransportEnv(env, 'postgres'), + transportOverrides(env), + ); + if (resolved.transport !== 'http') return null; return wrap(resolved.client); } @@ -284,14 +289,14 @@ export function resolveKnowledgeCloudStore(env: NodeJS.ProcessEnv = process.env) * The single mode signal the whole client uses: item commands route to the * ApiStore, and the local sqlite catalog is refused (never a silent split-brain * write). Local — the default, and the answer whenever no mode var says - * otherwise — returns false. Throws only when cloud was explicitly requested + * otherwise — returns false. Throws only when postgres was explicitly requested * but misconfigured, matching the item Store: never silent drift. */ export function isKnowledgeApiMode(env: NodeJS.ProcessEnv = process.env): boolean { - if (resolveKnowledgeModeSelection(env).mode !== 'cloud') return false; + if (resolveKnowledgeModeSelection(env).mode !== 'postgres') return false; return ( - resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, 'cloud'), transportOverrides(env)).transport - === 'cloud-http' + resolveStorageClient(KNOWLEDGE_APP_SLUG, pinnedTransportEnv(env, 'postgres'), transportOverrides(env)).transport + === 'http' ); } diff --git a/src/db/remote-storage.ts b/src/db/remote-storage.ts index 1e597f6..e8ce5d2 100644 --- a/src/db/remote-storage.ts +++ b/src/db/remote-storage.ts @@ -1,5 +1,5 @@ import { - createCloudPoolFromEnv, + createServerPoolFromEnv, type PoolQueryClient, } from '../generated/storage-kit/index.js'; @@ -18,10 +18,10 @@ export const KNOWLEDGE_APP_NAME = 'knowledge'; * `PgAdapterAsync` client adapter — a DSN-on-client sync engine — has been * removed to eliminate that forbidden path. * - * Requires `HASNA_KNOWLEDGE_STORAGE_MODE=cloud` and + * Requires `HASNA_KNOWLEDGE_STORAGE_MODE=postgres` and * `HASNA_KNOWLEDGE_DATABASE_URL`. Throws (without logging the URL) when the - * mode is not `cloud` or the URL is missing. + * mode is not `postgres` or the URL is missing. */ export function createKnowledgeCloudClient(): PoolQueryClient { - return createCloudPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: '@hasna/knowledge' }).client; + return createServerPoolFromEnv(KNOWLEDGE_APP_NAME, { applicationName: '@hasna/knowledge' }).client; } diff --git a/src/db/storage-sync.ts b/src/db/storage-sync.ts index 894f76a..b4588a1 100644 --- a/src/db/storage-sync.ts +++ b/src/db/storage-sync.ts @@ -44,15 +44,13 @@ export const KNOWLEDGE_STORAGE_TABLES = STORAGE_TABLES; type StorageTable = (typeof STORAGE_TABLES)[number]; /** - * Runtime storage mode per Amendment A1 (PURE REMOTE): - * - `local`: SQLite knowledge.db is authoritative. - * - `cloud`: the shared store is reached through the HTTP ApiStore. - * The legacy words `hybrid`, `remote`, and `self_hosted` are accepted only as - * deprecated aliases that normalize to `cloud`. + * Runtime storage backend: + * - `sqlite`: on-box SQLite knowledge.db is authoritative. + * - `postgres`: the shared store is reached through the HTTP ApiStore. + * The removed runtime-placement words (`local`, `cloud`, `hybrid`, `remote`, + * and `self_hosted`) are not accepted here. */ -export type StorageMode = 'local' | 'cloud'; - -const DEPRECATED_CLOUD_ALIASES = ['remote', 'hybrid', 'self_hosted'] as const; +export type StorageMode = 'sqlite' | 'postgres'; export interface StorageSyncOptions { tables?: string[]; @@ -98,9 +96,8 @@ function readEnv(name: string): string | undefined { function normalizeStorageMode(value: string | undefined): StorageMode | undefined { const normalized = value?.trim().toLowerCase().replace(/-/g, '_'); - if (normalized === 'local') return 'local'; - if (normalized === 'cloud') return 'cloud'; - if (normalized && (DEPRECATED_CLOUD_ALIASES as readonly string[]).includes(normalized)) return 'cloud'; + if (normalized === 'sqlite') return 'sqlite'; + if (normalized === 'postgres' || normalized === 'postgresql') return 'postgres'; return undefined; } @@ -118,9 +115,9 @@ export function getStorageMode(): StorageMode { const mode = normalizeStorageMode(readEnv(KNOWLEDGE_STORAGE_MODE_ENV)) ?? normalizeStorageMode(readEnv(KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV)); if (mode) return mode; - // Presence of a DATABASE_URL no longer auto-enables cloud. Cloud mode must be - // requested explicitly; default is local. - return 'local'; + // Presence of a DATABASE_URL no longer selects a backend. Postgres must be + // requested explicitly; default is sqlite. + return 'sqlite'; } export function getSyncMetaAll(options: StorageStatusOptions = {}): SyncMeta[] { diff --git a/src/generated/storage-kit/.storage-kit-manifest.json b/src/generated/storage-kit/.storage-kit-manifest.json index cad4527..9d9782d 100644 --- a/src/generated/storage-kit/.storage-kit-manifest.json +++ b/src/generated/storage-kit/.storage-kit-manifest.json @@ -1,14 +1,14 @@ { "generator": "@hasna/contracts vendor-kit", - "kitVersion": "0.4.0", + "kitVersion": "0.8.5", "files": { - "mode.ts": "sha256:24db73d98eda82e4ebe8b63f28e606b265de119556111314628c3cef2ed9540d", - "tls.ts": "sha256:d17c60447cd1a5e58b9c5b29173a44a0150f58c52302bad3253428c9d299cbee", - "query.ts": "sha256:0bd08fdd37bc10a6cc81546fd656123030b2dcd932e531413a91ff7abb6de6e2", - "pool.ts": "sha256:11cd2184db87629e854409a52ce54be2d1ea8320e7655a57b16c6c9ee33c8275", - "migrations.ts": "sha256:c748c77d0d13f7f6915e774ad01ff4d2af46db47f130ec3c5d8c00c6279ade09", - "health.ts": "sha256:630410b1c871bf9e030fc4b1ab1b8c0bc4b2ed4ecfc23d37055fe31cff07df26", - "index.ts": "sha256:1908605c70ec23d2084332b58844011a587920a217a69c9f4b028c3e6a7b0cde", + "mode.ts": "sha256:91822faf87dc03701a2e74d9cfc8ab18b000fc6f749f80dd3a2198dc31182a62", + "tls.ts": "sha256:8c11e27ff44b832c06a40d01da8bc4d23095ad3aacc8c806f36483448075ba30", + "query.ts": "sha256:a86a9810c1d8a928f68d4b96b9f0453c0efe67b06192850a27a5b38af510a7c6", + "pool.ts": "sha256:b8e39280d111bc8e5fc0ef6292ad22dc7c5ac9cfd18de686b53bd930025ef124", + "migrations.ts": "sha256:eca739920d392872b9051c727c2ebd239ff03fcf92b3e6229f9db21fb8585dbd", + "health.ts": "sha256:4afb410db7c516da5bee2174770bc3a31d8afa7efb27992e147c3e611b461777", + "index.ts": "sha256:75e9b19e1fd25bee25eec185f472792cd5e3806b6194b8485a8ccb07d40e9689", "README.md": "sha256:0886dbdf751597bfc8f23d2e72f233d6c3516b478925c8118b93d9d06a4eaa66" } } diff --git a/src/generated/storage-kit/health.ts b/src/generated/storage-kit/health.ts index b99c227..082f7a1 100644 --- a/src/generated/storage-kit/health.ts +++ b/src/generated/storage-kit/health.ts @@ -1,5 +1,5 @@ // @generated by @hasna/contracts vendor-kit — DO NOT EDIT. -// KIT_VERSION: 0.4.0 +// KIT_VERSION: 0.8.5 // Regenerate: bunx @hasna/contracts vendor-kit Verify (CI): contracts vendor-kit --check // Health / readiness helpers for the vendored Hasna storage kit. diff --git a/src/generated/storage-kit/index.ts b/src/generated/storage-kit/index.ts index e04b4d0..15d6935 100644 --- a/src/generated/storage-kit/index.ts +++ b/src/generated/storage-kit/index.ts @@ -1,5 +1,5 @@ // @generated by @hasna/contracts vendor-kit — DO NOT EDIT. -// KIT_VERSION: 0.4.0 +// KIT_VERSION: 0.8.5 // Regenerate: bunx @hasna/contracts vendor-kit Verify (CI): contracts vendor-kit --check // Public surface of the vendored Hasna storage kit. @@ -13,7 +13,7 @@ // generator with `contracts vendor-kit --check`. Regenerate with // `bunx @hasna/contracts vendor-kit`. -export const KIT_VERSION = "0.4.0"; +export const KIT_VERSION = "0.8.5"; export * from "./mode.js"; export * from "./tls.js"; diff --git a/src/generated/storage-kit/migrations.ts b/src/generated/storage-kit/migrations.ts index 4508b2e..6fbd0a6 100644 --- a/src/generated/storage-kit/migrations.ts +++ b/src/generated/storage-kit/migrations.ts @@ -1,5 +1,5 @@ // @generated by @hasna/contracts vendor-kit — DO NOT EDIT. -// KIT_VERSION: 0.4.0 +// KIT_VERSION: 0.8.5 // Regenerate: bunx @hasna/contracts vendor-kit Verify (CI): contracts vendor-kit --check // Migration-ledger helper for the vendored Hasna storage kit. @@ -64,18 +64,10 @@ interface LedgerRow { applied_at: string | Date; } -interface TransactionalQueryClient extends TypedQueryClient { - transaction<T>(fn: (client: TypedQueryClient) => Promise<T>): Promise<T>; -} - export interface MigrationRunnerOptions { ledgerTable?: string; } -function hasTransaction(client: TypedQueryClient): client is TransactionalQueryClient { - return typeof (client as { transaction?: unknown }).transaction === "function"; -} - export class MigrationLedger { private readonly ledgerTable: string; @@ -151,37 +143,13 @@ export class MigrationLedger { for (const item of plan) { if (item.state === "already_applied") continue; - await this.applyPendingMigration(item.migration); - } - return { dryRun, applied: await this.readApplied(), plan }; - } - - private async applyPendingMigration(migration: Migration): Promise<void> { - const apply = async (client: TypedQueryClient): Promise<void> => { - await client.execute(migration.sql); - await client.execute( + await this.client.execute(item.migration.sql); + await this.client.execute( `INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, - [migration.id, migration.checksum], + [item.migration.id, item.migration.checksum], ); - }; - - if (hasTransaction(this.client)) { - await this.client.transaction(apply); - return; - } - - await this.client.execute("BEGIN"); - try { - await apply(this.client); - await this.client.execute("COMMIT"); - } catch (error) { - try { - await this.client.execute("ROLLBACK"); - } catch { - // Surface the migration failure; rollback failure is secondary. - } - throw error; } + return { dryRun, applied: await this.readApplied(), plan }; } } diff --git a/src/generated/storage-kit/mode.ts b/src/generated/storage-kit/mode.ts index e62d885..f348861 100644 --- a/src/generated/storage-kit/mode.ts +++ b/src/generated/storage-kit/mode.ts @@ -1,50 +1,42 @@ // @generated by @hasna/contracts vendor-kit — DO NOT EDIT. -// KIT_VERSION: 0.4.0 +// KIT_VERSION: 0.8.5 // Regenerate: bunx @hasna/contracts vendor-kit Verify (CI): contracts vendor-kit --check -// Storage-mode resolution for the vendored Hasna storage kit. +// Storage-backend resolution for the vendored Hasna storage kit. // // Self-contained copy of the @hasna/contracts `mode.ts` contract so the // generated kit has zero runtime dependency on the contracts package. Keep // this in lockstep with the contract; regenerate the kit to pick up changes. // -// Amendment A1 (PURE REMOTE): there are exactly two runtime modes. -// - `local` : SQLite at ~/.hasna/<name>/<name>.db is authoritative. -// - `cloud` : reads AND writes go directly to the app's cloud Postgres. -// There is NO sync engine, NO cache-as-mode, and NO hybrid/remote/self_hosted -// runtime. The legacy words `remote`, `hybrid`, and `self_hosted` are accepted -// only as deprecated *aliases* that normalize to `cloud`. - -export const STORAGE_MODES = ["local", "cloud"] as const; +// The runtime-placement axis was removed entirely (owner directive +// 2026-07-29). The only switch is the server's DATA BACKEND: +// - `sqlite` : SQLite at ~/.hasna/<name>/<name>.db is authoritative. +// - `postgres` : reads AND writes go to a PostgreSQL server (DATABASE_URL). +// The long spelling `postgresql` normalizes to `postgres`; everything else — +// including every removed placement word — throws. Nothing is silently mapped. + +export const STORAGE_MODES = ["sqlite", "postgres"] as const; export type StorageMode = (typeof STORAGE_MODES)[number]; -export const DEPRECATED_STORAGE_MODE_ALIASES = [ - "remote", - "hybrid", - "self_hosted", -] as const; - export type Env = Record<string, string | undefined>; export interface StorageModeNormalization { mode: StorageMode; - /** The deprecated alias that was normalized to `cloud`, if any. */ - deprecatedAlias: string | null; } /** - * Normalize a raw storage-mode string to the `local | cloud` runtime enum. - * Accepts deprecated aliases (`remote`, `hybrid`, `self_hosted`) and maps them - * to `cloud`. Throws on any other value. + * Normalize a raw storage-backend string to the `sqlite | postgres` enum. + * `postgresql` is accepted as the long spelling of `postgres`. Throws on any + * other value with a migration hint. */ export function normalizeStorageMode(value: string): StorageModeNormalization { const normalized = value.trim().toLowerCase().replace(/-/g, "_"); - if (normalized === "local") return { mode: "local", deprecatedAlias: null }; - if (normalized === "cloud") return { mode: "cloud", deprecatedAlias: null }; - if ((DEPRECATED_STORAGE_MODE_ALIASES as readonly string[]).includes(normalized)) { - return { mode: "cloud", deprecatedAlias: normalized }; - } - throw new Error(`Unknown storage mode: ${value}. Use local or cloud.`); + if (normalized === "sqlite") return { mode: "sqlite" }; + if (normalized === "postgres" || normalized === "postgresql") return { mode: "postgres" }; + throw new Error( + `Unknown storage mode '${value}'. The runtime-placement axis was removed; ` + + `set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`, + ); } /** Upper-snake env token for an app name, e.g. `todos` -> `TODOS`. */ @@ -78,9 +70,8 @@ function firstEnv(env: Env, keys: readonly string[]): { key: string; value: stri export interface StorageModeResolution { mode: StorageMode; - /** Env key the mode came from, or `"default"`. */ + /** Env key the backend came from, or `"default"`. */ source: string; - deprecatedAlias: string | null; databaseUrlPresent: boolean; /** Env key the database URL came from, or `null`. */ databaseUrlSource: string | null; @@ -88,9 +79,10 @@ export interface StorageModeResolution { } /** - * Resolve an app's storage mode from the environment per the contract env spec. - * Precedence: `HASNA_<NAME>_STORAGE_MODE`, then `<NAME>_STORAGE_MODE`, else - * `local`. Never reads secret values — only detects DATABASE_URL presence. + * Resolve an app's storage backend from the environment per the contract env + * spec. Precedence: `HASNA_<NAME>_STORAGE_MODE`, then `<NAME>_STORAGE_MODE`; + * absent both, a present `DATABASE_URL` selects `postgres`, else `sqlite`. + * Never reads secret values — only detects DATABASE_URL presence. */ export function resolveStorageMode(name: string, env: Env = process.env): StorageModeResolution { const { modeKeys, databaseUrlKeys } = storageEnvKeys(name); @@ -101,24 +93,18 @@ export function resolveStorageMode(name: string, env: Env = process.env): Storag const modeHit = firstEnv(env, modeKeys); if (!modeHit) { return { - mode: "local", - source: "default", - deprecatedAlias: null, + mode: databaseUrlPresent ? "postgres" : "sqlite", + source: databaseUrlPresent ? databaseUrlSource! : "default", databaseUrlPresent, databaseUrlSource, warning: null, }; } - const { mode, deprecatedAlias } = normalizeStorageMode(modeHit.value); + const { mode } = normalizeStorageMode(modeHit.value); const warnings: string[] = []; - if (deprecatedAlias) { - warnings.push( - `Deprecated storage mode '${deprecatedAlias}' from ${modeHit.key} is treated as 'cloud'. Set ${modeKeys[0]}=cloud instead.`, - ); - } - if (mode === "cloud" && !databaseUrlPresent) { - warnings.push(`cloud mode needs ${databaseUrlKeys[0]} (PURE REMOTE: reads and writes go to cloud Postgres).`); + if (mode === "postgres" && !databaseUrlPresent) { + warnings.push(`postgres storage needs ${databaseUrlKeys[0]} (reads and writes go to PostgreSQL).`); } if (modeHit.key !== modeKeys[0]) { warnings.push(`Using alias env ${modeHit.key}; the canonical key is ${modeKeys[0]}.`); @@ -127,7 +113,6 @@ export function resolveStorageMode(name: string, env: Env = process.env): Storag return { mode, source: modeHit.key, - deprecatedAlias, databaseUrlPresent, databaseUrlSource, warning: warnings.length > 0 ? warnings.join(" ") : null, diff --git a/src/generated/storage-kit/pool.ts b/src/generated/storage-kit/pool.ts index d09ec59..63bf81b 100644 --- a/src/generated/storage-kit/pool.ts +++ b/src/generated/storage-kit/pool.ts @@ -1,13 +1,13 @@ // @generated by @hasna/contracts vendor-kit — DO NOT EDIT. -// KIT_VERSION: 0.4.0 +// KIT_VERSION: 0.8.5 // Regenerate: bunx @hasna/contracts vendor-kit Verify (CI): contracts vendor-kit --check // Postgres pool factory for the vendored Hasna storage kit. // -// The single sanctioned way to open a cloud Postgres connection. TLS is -// resolved through `tls.ts` (one correct approach), and env/mode resolution -// runs through `mode.ts` (the contract). PURE REMOTE (Amendment A1): a Pool is -// only ever built for `cloud` mode; there is no local/hybrid Postgres path. +// The single sanctioned way for a SERVER to open its PostgreSQL connection. +// TLS is resolved through `tls.ts` (one correct approach), and env resolution +// runs through `mode.ts` (the contract). A Pool is only ever built for the +// `postgres` backend; clients never open PostgreSQL directly (sqlite-or-http). import pg from "pg"; import type { Pool, PoolConfig } from "pg"; @@ -45,40 +45,41 @@ export function createPgPool(options: CreatePgPoolOptions): Pool { return new pg.Pool(config); } -export interface CreateCloudPoolFromEnvOptions extends TlsResolveOptions { +export interface CreateServerPoolFromEnvOptions extends TlsResolveOptions { max?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; applicationName?: string; } -export interface CloudPoolFromEnv { +export interface ServerPoolFromEnv { client: PoolQueryClient; connectionSource: string; } /** - * Resolve mode + database URL from the environment and build a cloud pool. + * Resolve backend + database URL from the environment and build the server's + * PostgreSQL pool. * - * Throws when the resolved mode is not `cloud` (PURE REMOTE has no Postgres in - * `local` mode) or when the database URL is missing. Never logs the URL. + * Throws when the resolved backend is not `postgres` (the sqlite backend has + * no Postgres pool) or when the database URL is missing. Never logs the URL. */ -export function createCloudPoolFromEnv( +export function createServerPoolFromEnv( appName: string, - options: CreateCloudPoolFromEnvOptions = {}, -): CloudPoolFromEnv { + options: CreateServerPoolFromEnvOptions = {}, +): ServerPoolFromEnv { const env = options.env ?? process.env; const resolution = resolveStorageMode(appName, env); - if (resolution.mode !== "cloud") { + if (resolution.mode !== "postgres") { throw new Error( - `createCloudPoolFromEnv requires ${appName} storage mode 'cloud', got '${resolution.mode}'. ` + - `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=cloud.`, + `createServerPoolFromEnv requires ${appName} storage mode 'postgres', got '${resolution.mode}'. ` + + `Set HASNA_${appName.toUpperCase().replace(/-/g, "_")}_STORAGE_MODE=postgres.`, ); } const connectionString = resolveDatabaseUrl(appName, env); if (!connectionString) { throw new Error( - `cloud mode for ${appName} needs a database URL. Set ` + + `postgres storage for ${appName} needs a database URL. Set ` + `HASNA_${appName.toUpperCase().replace(/-/g, "_")}_DATABASE_URL.`, ); } diff --git a/src/generated/storage-kit/query.ts b/src/generated/storage-kit/query.ts index 8674b90..d886547 100644 --- a/src/generated/storage-kit/query.ts +++ b/src/generated/storage-kit/query.ts @@ -1,5 +1,5 @@ // @generated by @hasna/contracts vendor-kit — DO NOT EDIT. -// KIT_VERSION: 0.4.0 +// KIT_VERSION: 0.8.5 // Regenerate: bunx @hasna/contracts vendor-kit Verify (CI): contracts vendor-kit --check // Typed query wrapper for the vendored Hasna storage kit. diff --git a/src/generated/storage-kit/tls.ts b/src/generated/storage-kit/tls.ts index f1733c7..6264f98 100644 --- a/src/generated/storage-kit/tls.ts +++ b/src/generated/storage-kit/tls.ts @@ -1,5 +1,5 @@ // @generated by @hasna/contracts vendor-kit — DO NOT EDIT. -// KIT_VERSION: 0.4.0 +// KIT_VERSION: 0.8.5 // Regenerate: bunx @hasna/contracts vendor-kit Verify (CI): contracts vendor-kit --check // TLS resolution for the vendored Hasna storage kit. @@ -12,7 +12,7 @@ // // The rule here follows libpq `sslmode` semantics exactly: // - disable / (no ssl param) -> no TLS (ssl: undefined) -// - allow / prefer / require -> encrypt, do NOT verify the server cert +// - prefer / require -> encrypt, do NOT verify the server cert // (rejectUnauthorized: false) — this matches // what libpq `require` means and is the AWS // RDS default when no CA bundle is supplied. @@ -95,16 +95,19 @@ export function resolveTlsConfig( ): PgSslConfig | undefined { const mode = sslModeFromConnectionString(connectionString); - if (mode === "disable") { + if (mode === "disable" || mode === "prefer") { + // `prefer` still lets pg negotiate TLS opportunistically without a config, + // but we only force TLS at `require` and above. Treat both as no explicit + // ssl config so a plain local Postgres keeps working. return undefined; } const ca = loadCaBundle(options); - if (mode === "prefer" || mode === "require") { + if (mode === "require") { // Encrypt but do not verify — libpq `require` semantics. If a CA bundle is // available we still pin it (strictly better) while keeping verification - // relaxed so a rotated/regional RDS cert cannot hard-fail a non-verifying DSN. + // relaxed so a rotated/regional RDS cert cannot hard-fail a `require` DSN. return ca ? { rejectUnauthorized: false, ca } : { rejectUnauthorized: false }; } diff --git a/src/item-store.ts b/src/item-store.ts index 83f73ca..198de37 100644 --- a/src/item-store.ts +++ b/src/item-store.ts @@ -5,18 +5,16 @@ * * ONE interface, two transports: * - LocalItemStore -> on-box JSON store (db.json) behind a file lock. - * - ApiItemStore -> HTTP `/v1` + bearer key (self_hosted / cloud) via + * - ApiItemStore -> HTTP `/v1` + bearer key (postgres backend) via * @hasna/contracts client transport. * - * Mode resolver: an EXPLICIT mode var (`HASNA_KNOWLEDGE_STORAGE_MODE=cloud` and - * its aliases, see knowledge-mode.ts) selects the api transport; everything else + * Mode resolver: an EXPLICIT mode var (`HASNA_KNOWLEDGE_STORAGE_MODE=postgres`) + * selects the api transport; everything else * — including a machine whose shell exports HASNA_KNOWLEDGE_API_URL and * HASNA_KNOWLEDGE_API_KEY — is local. Presence of a URL or key is a pointer, not - * a selection: it says where the cloud is, not that this process should write to - * it. `self_hosted` normalizes to `cloud` and uses ApiItemStore (identical - * client code; only URL/key differ — that distinction is server-side tenancy, - * not client). An explicit `--store` path override always pins to the local - * transport (fully reversible). + * a selection: it says where the API is, not that this process should write to + * it. An explicit `--store` path override always pins to the local transport + * (fully reversible). * * EVERY knowledge-item CLI command routes through this Store. No item command * touches the JSON file or the HTTP client directly — that is the split-brain @@ -89,7 +87,7 @@ export class VersionHistoryUnsupportedError extends Error { 'Version history is not kept by the local JSON knowledge store ' + `(${location}). It has no version line, so an empty history here would be a claim, not a measurement. ` + 'Entry versioning lives in the Postgres-backed store: point this CLI at it ' - + '(HASNA_KNOWLEDGE_STORAGE_MODE=cloud plus the API url/key) and re-run.', + + '(HASNA_KNOWLEDGE_STORAGE_MODE=postgres plus the API url/key) and re-run.', ); this.name = 'VersionHistoryUnsupportedError'; } @@ -294,7 +292,7 @@ export interface ResolveItemStoreOptions { /** * Resolve the single item Store for this invocation. Returns the ApiItemStore - * only when the mode is explicitly cloud, otherwise the LocalItemStore. An + * only when the mode is explicitly postgres, otherwise the LocalItemStore. An * explicit `--store` override always yields the local transport so the flip * stays fully reversible. */ diff --git a/src/knowledge-mode.ts b/src/knowledge-mode.ts index 20edf04..adddece 100644 --- a/src/knowledge-mode.ts +++ b/src/knowledge-mode.ts @@ -3,12 +3,12 @@ * Copyright 2026 Hasna Inc. * Licensed under the Apache License, Version 2.0 * - * ONE question, answered in ONE place: does this process read and write the - * on-box store, or the app's HTTP API? + * ONE question, answered in ONE place: does this process use the on-box sqlite + * backend, or the app's postgres backend reached by clients over HTTP? * * The rule is EXPLICIT-ONLY. A mode env var selects the mode; the presence of an * API URL or an API key never does. Those two are *pointers* — they say where - * the cloud is and how to authenticate to it, not that we should be talking to + * the server is and how to authenticate to it, not that we should be talking to * it. Selection by presence is what made an ambient `HASNA_KNOWLEDGE_API_URL` + * `HASNA_KNOWLEDGE_API_KEY` exported in a login shell silently route a test * suite's writes to the live store: every pane inherited the variables from the @@ -18,7 +18,7 @@ * Two layers used to infer cloud from presence, and BOTH had to be closed: * 1. this package's own resolver (deleted — it lived in cloud-store.ts), and * 2. `resolveClientTransport` in @hasna/contracts, which independently maps - * "url and key are both set" to cloud. + * "url and key are both set" to postgres. * So callers must not hand the raw environment to the contracts resolver. They * pass {@link pinnedTransportEnv}, which stamps the mode WE resolved over * whatever the ambient environment says, in both directions. With the mode @@ -49,12 +49,12 @@ const ENV_KEYS = clientTransportEnvKeys(KNOWLEDGE_APP_SLUG); * transport underneath us. */ export const KNOWLEDGE_MODE_ENV_KEYS: readonly string[] = ENV_KEYS.modeKeys; -/** Pointer keys: where the cloud is. Never a mode selector. */ +/** Pointer keys: where the server is. Never a mode selector. */ export const KNOWLEDGE_API_URL_ENV_KEYS: readonly string[] = ENV_KEYS.apiUrlKeys; /** Pointer keys: how to authenticate. Never a mode selector, never logged. */ export const KNOWLEDGE_API_KEY_ENV_KEYS: readonly string[] = ENV_KEYS.apiKeyKeys; -/** `local` = on-box store. `cloud` = the app's HTTP `/v1` API. */ +/** `sqlite` = on-box store. `postgres` = server data reached by clients over HTTP. */ export type KnowledgeMode = StorageMode; export interface KnowledgeModeSource { @@ -62,7 +62,7 @@ export interface KnowledgeModeSource { kind: 'env' | 'default'; /** The env key that selected the mode, or null for the default. */ name: string | null; - /** The mode var's own value (`local` / `cloud` / a deprecated alias). Never a pointer value. */ + /** The mode var's own value (`sqlite` / `postgres` / `postgresql`). Never a pointer value. */ value: string | null; } @@ -94,8 +94,8 @@ function presentEnvNames(env: NodeJS.ProcessEnv, keys: readonly string[]): strin * * Precedence: the first mode key that carries a value wins and RETURNS — the * pointer keys are not even read on that path, which is what makes an explicit - * `KNOWLEDGE_MODE=local` authoritative on a machine whose shell exports a URL - * and a key. With no mode key set the answer is `local`, the safe default, + * `KNOWLEDGE_MODE=sqlite` authoritative on a machine whose shell exports a URL + * and a key. With no mode key set the answer is `sqlite`, the safe default, * regardless of what pointers exist. * * Throws only on an unusable mode value (never on pointer state) so a typo in @@ -117,71 +117,49 @@ export function resolveKnowledgeModeSelection(env: NodeJS.ProcessEnv = process.e let normalized: ReturnType<typeof normalizeVendoredMode>; try { // The VENDORED normalizer, deliberately: this validates what an OPERATOR - // typed, and `local`/`cloud` is the operator-facing vocabulary. The live - // contracts token is derived separately, at the boundary — see - // {@link contractsStorageModeFor}. + // typed. Regenerating the kit is what moves the operator vocabulary, so + // there is no second hand-maintained enum here. normalized = normalizeVendoredMode(value); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error(`knowledge: ${name}=${value} is not a valid mode. ${message}`); } const warnings: string[] = []; - if (normalized.deprecatedAlias) { - warnings.push( - `Deprecated mode '${normalized.deprecatedAlias}' from ${name} is treated as 'cloud'. Prefer ${canonicalModeKey}=cloud.`, - ); - } if (name !== canonicalModeKey) { warnings.push(`Using alias env ${name}; the canonical key is ${canonicalModeKey}.`); } - if (normalized.mode === 'local' && pointers.length > 0) { - warnings.push(`${name}=local pins the on-box store; ${pointers.join(', ')} are set but ignored.`); + if (normalized.mode === 'sqlite' && pointers.length > 0) { + warnings.push(`${name}=sqlite pins the on-box store; ${pointers.join(', ')} are set but ignored.`); } return { mode: normalized.mode, source: { kind: 'env', name, value }, pointer_env_present: pointers, - pointer_ignored: normalized.mode === 'local' && pointers.length > 0, + pointer_ignored: normalized.mode === 'sqlite' && pointers.length > 0, warning: warnings.length > 0 ? warnings.join(' ') : null, }; } return { - mode: 'local', + mode: 'sqlite', source: { kind: 'default', name: null, value: null }, pointer_env_present: pointers, pointer_ignored: pointers.length > 0, warning: pointers.length > 0 - ? `${pointers.join(', ')} are set but do NOT select a backend: mode is local by default. ` - + `Set ${canonicalModeKey}=cloud to route reads and writes to the API, or unset those vars to silence this note.` + ? `${pointers.join(', ')} are set but do NOT select a backend: mode is sqlite by default. ` + + `Set ${canonicalModeKey}=postgres to route reads and writes to the API, or unset those vars to silence this note.` : null, }; } /** - * Server-side tokens, in probe order. The order is load-bearing, and it is - * NEWEST-GENERATION FIRST, THEN CANONICAL BEFORE DEPRECATED: - * - * postgres the current canonical server token - * cloud the previous canonical server token - * self_hosted a DEPRECATED alias of `cloud`, last resort only - * - * Both halves matter. Newest-first is what stops a transitional contracts - * release — one that still honours the old words — from pinning us to the old - * generation. Canonical-before-deprecated is what stops us pinning - * `self_hosted` on the enum where `cloud` is the real answer: both are accepted - * there, but only one is the token this package already injects, and switching - * to the alias would be a live behaviour change dressed up as a refactor. - * - * (Sibling repos list `self_hosted` ahead of `cloud` for exactly the same - * reason inverted — `self_hosted` is the literal THEY replace. The rule is - * "derive what this repo already injects on the installed generation", not - * "copy the other repo's array".) + * Server-side tokens, in probe order. Kept as a small derivation seam so a + * future contracts enum change fails loudly instead of guessing a backend. */ -export const SERVER_MODE_CANDIDATES = ['postgres', 'cloud', 'self_hosted'] as const; -/** On-box tokens, same rule: newest generation first. */ -export const LOCAL_MODE_CANDIDATES = ['sqlite', 'local'] as const; +export const SERVER_MODE_CANDIDATES = ['postgres'] as const; +/** On-box tokens. */ +export const LOCAL_MODE_CANDIDATES = ['sqlite'] as const; /** Accepts a mode token or throws. Injectable so both enum generations are testable. */ export type ModeNormalizer = (value: string) => unknown; @@ -230,62 +208,25 @@ export function localStorageMode(normalize: ModeNormalizer = normalizeContractsM } /** - * Translate OUR semantic mode into the token the INSTALLED @hasna/contracts - * accepts. - * - * THIS FUNCTION IS A TRANSLATION, NOT A PASS-THROUGH, AND THAT IS THE WHOLE - * POINT — do not "simplify" it back. This module holds two independent - * validators, and they are allowed to disagree: - * - * - {@link normalizeVendoredMode}, from the vendored `src/generated/storage-kit`, - * validates what an OPERATOR typed. Its vocabulary is `local | cloud` and - * that is the vocabulary in the docs, the `knowledge mode` report, and the - * env vars people set. {@link KnowledgeMode} is that type. - * - the LIVE `@hasna/contracts` validates the token we hand its resolver. - * After the placement axis was removed it accepts ONLY `sqlite | postgres` - * and THROWS on `local`/`cloud`. - * - * Post-removal those two sets are DISJOINT, which reads at first like an - * impossible constraint: the token that satisfies the type is the token the - * resolver rejects. It is not impossible, because they never had to be the same - * value. {@link KnowledgeMode} types the INTERNAL semantic mode; what reaches - * the resolver is an ENV STRING, and `NodeJS.ProcessEnv` values are - * `string | undefined` — nothing ever forced the stamped token to satisfy the - * vendored type. The two vocabularies meet in exactly one place, here, so - * translating here keeps the vendored kit, the operator vocabulary, and the - * explicit-only no-inference guarantee all untouched. Re-vendoring the kit is - * NOT required to make this forward-compatible. - * - * The tokens are DERIVED by probing the installed `normalizeStorageMode` rather - * than hardcoded, because a literal is a bet on which contracts generation a - * given machine has, and the bet loses on one side or the other. `normalize` is - * injectable because only one generation can be installed at a time, so - * forward-compatibility would otherwise be an assertion rather than a test. - * - * BOUNDARY: the returned token is for the contracts resolver ONLY. Do not feed - * a pinned env back into {@link resolveKnowledgeModeSelection} — that validates - * with the VENDORED normalizer, which will reject the live token once the two - * enums diverge. + * Validate and return the installed-contracts token for a semantic backend. */ export function contractsStorageModeFor( mode: KnowledgeMode, normalize: ModeNormalizer = normalizeContractsMode, ): string { - return mode === 'cloud' ? serverStorageMode(normalize) : localStorageMode(normalize); + return mode === 'postgres' ? serverStorageMode(normalize) : localStorageMode(normalize); } /** * The env to hand @hasna/contracts, with the mode we resolved stamped on top. * * Load-bearing in BOTH directions. Stamping the server token keeps the - * transport from refusing a mode we deliberately chose; stamping the local + * transport from refusing a mode we deliberately chose; stamping the sqlite * token is what stops `resolveClientTransport` from re-deriving the server out * of the ambient pointer vars we just decided to ignore. Handing it the raw * environment instead would put the backend choice back in a second layer. * - * The stamped VALUE is the live-contracts token, not our `KnowledgeMode` — see - * {@link contractsStorageModeFor} for why those are deliberately different - * things. + * The stamped VALUE is the live-contracts token. */ export function pinnedTransportEnv(env: NodeJS.ProcessEnv, mode: KnowledgeMode): NodeJS.ProcessEnv { return { ...env, [KNOWLEDGE_MODE_ENV_KEYS[0]]: contractsStorageModeFor(mode) }; @@ -304,7 +245,7 @@ export class HalfConfiguredKnowledgeClientError extends Error { super( `knowledge: ${urlKeysPresent.join(', ')} names an API store, but no mode variable says to use it, ` + 'so this command would silently read and write the on-box store instead. ' - + `Set ${canonical}=cloud to use the API, or ${canonical}=local to confirm you want the on-box store. ` + + `Set ${canonical}=postgres to use the API, or ${canonical}=sqlite to confirm you want the on-box store. ` + `Run 'knowledge mode' to see the full resolution.`, ); this.name = 'HalfConfiguredKnowledgeClientError'; @@ -315,7 +256,7 @@ export class HalfConfiguredKnowledgeClientError extends Error { * Gate a store-touching command on an UNAMBIGUOUS environment. * * Deliberately separate from {@link resolveKnowledgeModeSelection}, which stays - * total and non-throwing. The resolver has to keep answering `local` in exactly + * total and non-throwing. The resolver has to keep answering `sqlite` in exactly * the environment this rejects, because `knowledge mode` — the command whose * whole job is explaining the situation — resolves through it. A guard fused * into the resolver would kill the diagnostic along with the defect. @@ -325,8 +266,8 @@ export class HalfConfiguredKnowledgeClientError extends Error { * fire on machines that could never have routed anywhere, and a check that * cries wolf is a check somebody turns off. * - * `storePathOverridden` (an explicit `--store <path>`) is an explicit local - * choice and passes for the same reason `MODE=local` does: the operator said + * `storePathOverridden` (an explicit `--store <path>`) is an explicit sqlite + * choice and passes for the same reason `MODE=sqlite` does: the operator said * which store they meant. */ export function assertKnowledgeModeSelected( @@ -342,7 +283,7 @@ export function assertKnowledgeModeSelected( } export interface KnowledgeModeReport extends KnowledgeModeResolution { - /** `local` -> the on-box store; `api` -> the HTTP `/v1` transport. */ + /** `sqlite` -> the on-box store; `api` -> the HTTP `/v1` transport. */ store_transport: 'local' | 'api'; /** Whether an API key is available at all. Presence only — never the value. */ api_key_present: boolean; @@ -361,7 +302,7 @@ export function knowledgeModeReport(env: NodeJS.ProcessEnv = process.env): Knowl const resolution = resolveKnowledgeModeSelection(env); return { ...resolution, - store_transport: resolution.mode === 'cloud' ? 'api' : 'local', + store_transport: resolution.mode === 'postgres' ? 'api' : 'local', api_key_present: presentEnvNames(env, KNOWLEDGE_API_KEY_ENV_KEYS).length > 0, network_guard_active: isNetworkGuardActive(env), }; diff --git a/src/net-guard.ts b/src/net-guard.ts index 8061bb3..47a6910 100644 --- a/src/net-guard.ts +++ b/src/net-guard.ts @@ -136,7 +136,7 @@ export function assertOutboundRequestAllowed( `knowledge: refused a non-loopback ${url.protocol.replace(':', '')} request while ${NETWORK_GUARD_ENV}=test ` + '(target host withheld on purpose). This process resolved to the cloud backend under test, which means a ' + 'read or write was about to leave the machine and reach the live store. Select the mode explicitly ' - + `(${'HASNA_KNOWLEDGE_STORAGE_MODE'}=local) or point the API URL at 127.0.0.1 for a hermetic test.`, + + `(${'HASNA_KNOWLEDGE_STORAGE_MODE'}=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`, { scheme: url.protocol.replace(':', ''), port: url.port }, ); } diff --git a/src/sdk.ts b/src/sdk.ts index 304c54c..6f5da87 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -13,9 +13,10 @@ import type { /** * The unified knowledge-item Store surface, mirrored on the SDK so app code - * routes item CRUD through the SAME Store as the CLI and MCP in all three modes - * (local db.json, self_hosted, cloud). No SDK item method touches sqlite or the - * raw HTTP client — the mode is resolved from the environment by the Store. + * routes item CRUD through the SAME Store as the CLI and MCP: sqlite uses the + * local db.json store, postgres uses the HTTP API transport. No SDK item method + * touches sqlite or the raw HTTP client directly — the mode is resolved from + * the environment by the Store. */ export interface KnowledgeItemsSdk { /** The resolved Store for this scope (`kind: 'local' | 'api'`). */ @@ -116,9 +117,9 @@ export interface KnowledgeClient { */ readonly items: KnowledgeItemsSdk; /** - * Inventory of the knowledge corpus. Routes to the shared cloud item corpus in - * api mode (self_hosted/cloud) and the local sqlite/JSON catalog otherwise, so - * the SDK never diverges from the CLI/MCP. Always async. + * Inventory of the knowledge corpus. Routes to the shared API item corpus in + * postgres mode and the local sqlite/JSON catalog otherwise, so the SDK never + * diverges from the CLI/MCP. Always async. */ readonly inventory: (options?: KnowledgeInventoryOptions) => ReturnType<KnowledgeService['resolveInventory']>; readonly db: { diff --git a/src/serve-entry.ts b/src/serve-entry.ts index c0f39ba..34cb457 100644 --- a/src/serve-entry.ts +++ b/src/serve-entry.ts @@ -2,8 +2,8 @@ /** * @hasna/knowledge — knowledge-serve entrypoint. * - * Boots the HTTP API (PURE REMOTE / Amendment A1). Requires cloud-mode env: - * HASNA_KNOWLEDGE_STORAGE_MODE=cloud + * Boots the HTTP API. Requires postgres backend env: + * HASNA_KNOWLEDGE_STORAGE_MODE=postgres * HASNA_KNOWLEDGE_DATABASE_URL=postgres://... (never logged) * HASNA_KNOWLEDGE_API_SIGNING_KEY=... (or API_KEY_SIGNING_SECRET) * PORT=8080 (optional; default 8080) diff --git a/src/serve.ts b/src/serve.ts index 7e8850b..168eb46 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -734,7 +734,7 @@ export interface ServeDeps { export function createServeHandler(deps: ServeDeps): (req: Request) => Promise<Response> { const repo = new NoteRepo(deps.client); - const mode = 'cloud'; + const mode = 'postgres'; const authOrThrow = async ( req: Request, @@ -938,7 +938,7 @@ export async function startKnowledgeServe(options: StartServeOptions = {}): Prom throw new Error('knowledge-serve requires the Bun runtime (Bun.serve unavailable).'); } const server = BunGlobal.serve({ port, hostname, fetch: handler }); - console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=cloud, version=${version})`); + console.log(`[knowledge-serve] listening on http://${hostname}:${server.port} (mode=postgres, version=${version})`); return { port: server.port, diff --git a/src/service.ts b/src/service.ts index 2e3f4d1..68736c5 100644 --- a/src/service.ts +++ b/src/service.ts @@ -1652,8 +1652,8 @@ export class KnowledgeService { /** * The single knowledge-item Store for this scope. One interface, two * transports resolved from the environment: LocalItemStore (on-box db.json) - * in local mode, ApiItemStore (HTTP `/v1` + bearer key) in self_hosted/cloud - * mode. EVERY item read/write — CLI, MCP, and SDK — routes through this one + * in sqlite mode, ApiItemStore (HTTP `/v1` + bearer key) in postgres mode. + * EVERY item read/write — CLI, MCP, and SDK — routes through this one * surface, so no path touches sqlite or the raw HTTP client directly. */ itemStore(): ItemStore { @@ -1695,8 +1695,8 @@ export class KnowledgeService { } /** - * Unified inventory dispatch: the shared cloud knowledge-item corpus in api - * mode (self_hosted/cloud), the local sqlite/JSON catalog otherwise. CLI, MCP, + * Unified inventory dispatch: the shared API knowledge-item corpus in + * postgres mode, the local sqlite/JSON catalog otherwise. CLI, MCP, * and SDK all call this so no surface reads a divergent store. */ async resolveInventory(options: KnowledgeInventoryOptions = {}): Promise<KnowledgeInventoryResult> { diff --git a/src/storage.ts b/src/storage.ts index 387fef3..a0c85c2 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -38,6 +38,7 @@ export { resolveStorageMode, resolveDatabaseUrl, resolveTlsConfig, + normalizeStorageMode, normalizeStorageMode as normalizeCloudStorageMode, storageEnvKeys, MigrationLedger, diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 8fc091f..bdd9d22 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -26,16 +26,17 @@ const packageJson = JSON.parse(readFileSync(join(__dirname, '..', 'package.json' }; /** - * The env every spawned CLI gets: the parent's, minus the cloud pointer vars, - * plus the caller's overrides. + * The env every spawned CLI gets: the parent's, minus the knowledge mode and + * pointer vars, plus the caller's overrides. * * Those two variables are exported in a login shell on developer machines and * inherited by every pane from the tmux server, so a child that gets the parent * environment verbatim is configured differently from one run in CI. That is not * hypothetical: `auth whoami` reports `authenticated: true` purely from the - * presence of an API key, so this suite's hosted-auth contract test measured the - * developer's shell rather than the temp auth dir it had just created, and - * failed for a reason that had nothing to do with the code under test. + * presence of an API key, and an old ambient storage mode can now be an + * intentionally rejected placement word. Without this stripping, the suite + * measures the developer's shell rather than the temp auth dir or mode it just + * created. * * This is DEFENCE IN DEPTH, not the control. The control is the outbound request * guard in src/net-guard.ts, which refuses non-loopback traffic under @@ -46,7 +47,7 @@ const packageJson = JSON.parse(readFileSync(join(__dirname, '..', 'package.json' */ function childEnv(env?: Record<string, string>): Record<string, string> { const inherited = { ...process.env } as Record<string, string>; - for (const key of [...KNOWLEDGE_API_URL_ENV_KEYS, ...KNOWLEDGE_API_KEY_ENV_KEYS]) delete inherited[key]; + for (const key of [...KNOWLEDGE_API_URL_ENV_KEYS, ...KNOWLEDGE_API_KEY_ENV_KEYS, ...KNOWLEDGE_MODE_ENV_KEYS]) delete inherited[key]; return { ...inherited, ...(env ?? {}) }; } @@ -2395,7 +2396,7 @@ describe('knowledge cli', () => { expect(storage.exitCode).toBe(0); const storageOut = JSON.parse(new TextDecoder().decode(storage.stdout)); expect(storageOut.service).toBe('knowledge'); - expect(storageOut.mode).toBe('local'); + expect(storageOut.mode).toBe('sqlite'); expect(storageOut.tables).toContain('sources'); expect(storageOut.tables).not.toContain('chunks_fts'); }); @@ -3711,15 +3712,15 @@ describe('a half-configured CLI fails loudly instead of reading the wrong store' expect(result.exitCode).toBe(0); const report = JSON.parse(decode(result.stdout)) as { ok: boolean; mode: string; pointer_ignored: boolean }; expect(report.ok).toBe(true); - expect(report.mode).toBe('local'); + expect(report.mode).toBe('sqlite'); expect(report.pointer_ignored).toBe(true); }); - test('an explicit local mode alongside the URL still lists, and stays local', () => { + test('an explicit sqlite mode alongside the URL still lists, and stays local', () => { const result = runCliNoMode(['list', '--json'], { ...sandboxHome(), HASNA_KNOWLEDGE_API_URL: FAKE_API_URL, - HASNA_KNOWLEDGE_STORAGE_MODE: 'local', + HASNA_KNOWLEDGE_STORAGE_MODE: 'sqlite', }); expect(result.exitCode).toBe(0); const payload = JSON.parse(decode(result.stdout)) as { ok: boolean; total: number }; diff --git a/tests/cloud-inventory.test.ts b/tests/cloud-inventory.test.ts index 9cdac26..5b64546 100644 --- a/tests/cloud-inventory.test.ts +++ b/tests/cloud-inventory.test.ts @@ -2,11 +2,11 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { createKnowledgeService } from '../src/service'; /** - * Cloud (self_hosted / api) mode `inventory` must route through the cloud item - * transport and report the shared corpus — NOT read the local db.json and NOT + * Postgres/API mode `inventory` must route through the API item transport and + * report the shared corpus — NOT read the local db.json and NOT * open the local sqlite catalog (which would throw the local-catalog guard on a * flipped fleet machine that still has a leftover knowledge.db). This proves the - * command routes to the cloud like every other item command. + * command routes to the API like every other item command. */ const now = new Date().toISOString(); const NOTES = [ @@ -38,9 +38,9 @@ beforeAll(() => { process.env.HASNA_KNOWLEDGE_API_KEY = 'k_fake_test_key'; // Explicit, because presence of the URL + key no longer selects a backend. // The endpoint is 127.0.0.1, so the outbound guard permits these requests — - // this test doubles as the positive control that hermetic cloud-mode traffic + // this test doubles as the positive control that hermetic postgres/API traffic // still flows while the guard is armed. - process.env.HASNA_KNOWLEDGE_STORAGE_MODE = 'cloud'; + process.env.HASNA_KNOWLEDGE_STORAGE_MODE = 'postgres'; }); afterAll(() => { @@ -50,8 +50,8 @@ afterAll(() => { } }); -describe('cloud-mode inventory over the shared item corpus', () => { - test('cloudInventory reports cloud items with empty local catalog sections', async () => { +describe('postgres/API inventory over the shared item corpus', () => { + test('cloudInventory reports API items with empty local catalog sections', async () => { const service = createKnowledgeService({ scope: 'global' }); const inv = await service.cloudInventory({}); expect(inv.ok).toBe(true); @@ -66,7 +66,7 @@ describe('cloud-mode inventory over the shared item corpus', () => { expect(inv.chunks).toEqual([]); expect(inv.wiki_pages).toEqual([]); // The `paths` block reports the real on-box workspace layout and MUST agree - // with the `paths` command even in cloud mode — it is NOT the item transport + // with the `paths` command even in postgres/API mode — it is NOT the item transport // location. The cloud source is surfaced via `legacy_store` instead. const paths = service.paths(); expect(inv.paths.json_store_path).toBe(paths.json_store_path); diff --git a/tests/cloud-storage-kit.test.ts b/tests/cloud-storage-kit.test.ts index 1a976fd..c9aaa55 100644 --- a/tests/cloud-storage-kit.test.ts +++ b/tests/cloud-storage-kit.test.ts @@ -3,7 +3,7 @@ import { KIT_VERSION, createKnowledgeCloudClient, defineMigration, - normalizeCloudStorageMode, + normalizeStorageMode, MigrationLedger, resolveTlsConfig, resolveStorageMode, @@ -87,25 +87,24 @@ describe('vendored cloud storage kit surface', () => { expect(keys.modeKeys[0]).toBe('HASNA_KNOWLEDGE_STORAGE_MODE'); expect(keys.databaseUrlKeys[0]).toBe('HASNA_KNOWLEDGE_DATABASE_URL'); - expect(resolveStorageMode('knowledge', {}).mode).toBe('local'); + expect(resolveStorageMode('knowledge', {}).mode).toBe('sqlite'); expect( resolveStorageMode('knowledge', { - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_DATABASE_URL: 'postgres://x/y', }).mode, - ).toBe('cloud'); + ).toBe('postgres'); + expect(resolveStorageMode('knowledge', { HASNA_KNOWLEDGE_DATABASE_URL: 'postgres://x/y' }).mode).toBe( + 'postgres', + ); }); - test('maps sslmode prefer and allow to encrypted pg connections', () => { + test('maps sslmode according to the generated TLS contract', () => { const env = {}; expect(resolveTlsConfig('postgres://user:pass@example.test/db', { env })).toBeUndefined(); expect(resolveTlsConfig('postgres://user:pass@example.test/db?sslmode=disable', { env })).toBeUndefined(); - expect(resolveTlsConfig('postgres://user:pass@example.test/db?sslmode=prefer', { env })).toEqual({ - rejectUnauthorized: false, - }); - expect(resolveTlsConfig('postgres://user:pass@example.test/db?sslmode=allow', { env })).toEqual({ - rejectUnauthorized: false, - }); + expect(resolveTlsConfig('postgres://user:pass@example.test/db?sslmode=prefer', { env })).toBeUndefined(); + expect(resolveTlsConfig('postgres://user:pass@example.test/db?sslmode=allow', { env })).toBeUndefined(); expect(resolveTlsConfig('postgres://user:pass@example.test/db?sslmode=require', { env })).toEqual({ rejectUnauthorized: false, }); @@ -114,7 +113,7 @@ describe('vendored cloud storage kit surface', () => { ); }); - test('applies migration SQL and ledger writes in one transaction', async () => { + test('applies migration SQL and ledger writes through the generated ledger', async () => { const client = new FakeMigrationClient(); const ledger = new MigrationLedger(client, [ defineMigration('001_init', 'CREATE TABLE example (id TEXT PRIMARY KEY)'), @@ -122,30 +121,31 @@ describe('vendored cloud storage kit surface', () => { await ledger.migrate(); - expect(client.transactionCount).toBe(1); + expect(client.transactionCount).toBe(0); expect(client.executed).toEqual([ expect.stringContaining('CREATE TABLE IF NOT EXISTS schema_migrations'), - 'BEGIN', 'CREATE TABLE example (id TEXT PRIMARY KEY)', expect.stringContaining('INSERT INTO schema_migrations'), - 'COMMIT', ]); }); - test('normalizes deprecated aliases to cloud', () => { - expect(normalizeCloudStorageMode('remote').mode).toBe('cloud'); - expect(normalizeCloudStorageMode('hybrid').mode).toBe('cloud'); - expect(normalizeCloudStorageMode('self_hosted').mode).toBe('cloud'); - expect(normalizeCloudStorageMode('local').mode).toBe('local'); + test('normalizes backend spellings and rejects removed placement aliases', () => { + expect(normalizeStorageMode('sqlite').mode).toBe('sqlite'); + expect(normalizeStorageMode('postgres').mode).toBe('postgres'); + expect(normalizeStorageMode('postgresql').mode).toBe('postgres'); + expect(() => normalizeStorageMode('remote')).toThrow(/runtime-placement axis was removed/); + expect(() => normalizeStorageMode('hybrid')).toThrow(/runtime-placement axis was removed/); + expect(() => normalizeStorageMode('self_hosted')).toThrow(/runtime-placement axis was removed/); + expect(() => normalizeStorageMode('local')).toThrow(/runtime-placement axis was removed/); }); - test('createKnowledgeCloudClient refuses non-cloud mode without leaking the URL', () => { + test('createKnowledgeCloudClient refuses non-postgres mode without leaking the URL', () => { const priorMode = process.env.HASNA_KNOWLEDGE_STORAGE_MODE; const priorUrl = process.env.HASNA_KNOWLEDGE_DATABASE_URL; try { - delete process.env.HASNA_KNOWLEDGE_STORAGE_MODE; + process.env.HASNA_KNOWLEDGE_STORAGE_MODE = 'sqlite'; process.env.HASNA_KNOWLEDGE_DATABASE_URL = 'postgres://secret:secret@host/db'; - expect(() => createKnowledgeCloudClient()).toThrow(/storage mode 'cloud'/); + expect(() => createKnowledgeCloudClient()).toThrow(/storage mode 'postgres'/); try { createKnowledgeCloudClient(); } catch (error) { diff --git a/tests/cloud-store.test.ts b/tests/cloud-store.test.ts index 452b697..cc025b4 100644 --- a/tests/cloud-store.test.ts +++ b/tests/cloud-store.test.ts @@ -7,7 +7,7 @@ import { const CLEAN_ENV = {} as NodeJS.ProcessEnv; -describe('knowledge cloud-store resolver (self_hosted client flip)', () => { +describe('knowledge cloud-store resolver (postgres client flip)', () => { test('resource + slug are the contract-stable values', () => { expect(KNOWLEDGE_APP_SLUG).toBe('knowledge'); expect(KNOWLEDGE_RESOURCE).toBe('notes'); @@ -17,27 +17,27 @@ describe('knowledge cloud-store resolver (self_hosted client flip)', () => { expect(resolveKnowledgeCloudStore(CLEAN_ENV)).toBeNull(); }); - test('returns null (local) when mode=local even with API url+key present', () => { + test('returns null (local) when mode=sqlite even with API url+key present', () => { const store = resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'local', + HASNA_KNOWLEDGE_STORAGE_MODE: 'sqlite', HASNA_KNOWLEDGE_API_URL: 'https://knowledge.md', HASNA_KNOWLEDGE_API_KEY: 'k_fake_test_key', } as NodeJS.ProcessEnv); expect(store).toBeNull(); }); - test('throws (never silent local drift) when self_hosted requested but API key missing', () => { + test('throws (never silent local drift) when postgres is requested but API key is missing', () => { expect(() => resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'self_hosted', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_URL: 'https://knowledge.md', } as NodeJS.ProcessEnv), ).toThrow(); }); - test('resolves a cloud-http store pointed at the configured URL when self_hosted + url + key', () => { + test('resolves an http store pointed at the configured URL when postgres + url + key', () => { const store = resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'self_hosted', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_URL: 'https://knowledge.md', HASNA_KNOWLEDGE_API_KEY: 'k_fake_test_key', } as NodeJS.ProcessEnv); @@ -62,11 +62,11 @@ describe('knowledge cloud-store resolver (self_hosted client flip)', () => { expect(store).toBeNull(); }); - test('the same pointers WITH an explicit cloud mode do route to cloud', () => { + test('the same pointers WITH an explicit postgres backend do route to the API', () => { // The other half of the inverted case above: nothing about reaching the // cloud got harder, it just has to be asked for. const store = resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_URL: 'https://knowledge.md', HASNA_KNOWLEDGE_API_KEY: 'k_fake_test_key', } as NodeJS.ProcessEnv); @@ -90,16 +90,16 @@ describe('knowledge cloud-store resolver (self_hosted client flip)', () => { ).toBeNull(); }); - test('defaults the base URL to the @hasna/contracts host template when only mode+key set', () => { + test('derives the base URL from the @hasna/contracts fleet domain when no API URL is set', () => { // NOTE: this default is NOT sourced from this package's DEFAULT_KNOWLEDGE_API_URL. - // It comes from `defaultCloudBaseUrl()` in the @hasna/contracts dependency, - // which still templates `https://<app>.hasna.xyz`. That default needs its own - // fix in the @hasna/contracts package; tracked separately from this repo. + // It comes from the @hasna/contracts dependency and now requires an explicit + // fleet domain instead of silently assuming Hasna's SaaS hostname. const store = resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'self_hosted', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_KEY: 'k_fake_test_key', + HASNA_FLEET_API_DOMAIN: 'example.test', } as NodeJS.ProcessEnv); expect(store).not.toBeNull(); - expect(store!.baseUrl).toBe('https://knowledge.hasna.xyz/v1'); + expect(store!.baseUrl).toBe('https://knowledge.example.test/v1'); }); }); diff --git a/tests/entry-versioning-client.test.ts b/tests/entry-versioning-client.test.ts index 95f8697..cba4750 100644 --- a/tests/entry-versioning-client.test.ts +++ b/tests/entry-versioning-client.test.ts @@ -40,7 +40,8 @@ beforeAll(async () => { server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: handler }); cloudEnv = { - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HOME: mkdtempSync(join(tmpdir(), 'ok-versions-home-')), + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_URL: `http://127.0.0.1:${server.port}`, HASNA_KNOWLEDGE_API_KEY: mintApiKey({ app: 'knowledge', @@ -48,6 +49,7 @@ beforeAll(async () => { signingSecret: SIGNING, }).token, }; + cloudEnv.USERPROFILE = cloudEnv.HOME; }); afterAll(async () => { @@ -290,6 +292,6 @@ describe('ItemStore (local transport) — a store with no history says so', () = message = (error as Error).message; } expect(message).toContain('db.json'); - expect(message).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=cloud'); + expect(message).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=postgres'); }); }); diff --git a/tests/knowledge-mode.test.ts b/tests/knowledge-mode.test.ts index 8c16746..69eb395 100644 --- a/tests/knowledge-mode.test.ts +++ b/tests/knowledge-mode.test.ts @@ -54,92 +54,98 @@ describe('knowledge mode selection is explicit, never inferred from a pointer', expect([...KNOWLEDGE_API_KEY_ENV_KEYS]).toEqual(['HASNA_KNOWLEDGE_API_KEY', 'KNOWLEDGE_API_KEY']); }); - test('an empty environment is local by default', () => { + test('an empty environment is sqlite by default', () => { const resolved = resolveKnowledgeModeSelection({} as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); expect(resolved.source).toEqual({ kind: 'default', name: null, value: null }); expect(resolved.pointer_env_present).toEqual([]); expect(resolved.pointer_ignored).toBe(false); expect(resolved.warning).toBeNull(); }); - test('REGRESSION: url + key with no mode var stays LOCAL and says the pointers were ignored', () => { + test('REGRESSION: url + key with no mode var stays sqlite and says the pointers were ignored', () => { // The defect. Under the old resolver this environment — which is what an // ambient exported pair looks like — selected the cloud backend, so a test // suite that believed it was isolated wrote to the live store. const resolved = resolveKnowledgeModeSelection(POINTER_ONLY); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); expect(resolved.source.kind).toBe('default'); expect(resolved.pointer_ignored).toBe(true); expect(resolved.pointer_env_present).toEqual(['HASNA_KNOWLEDGE_API_URL', 'HASNA_KNOWLEDGE_API_KEY']); // The note has to name the variable the operator must set, or "it went // local" is just as mysterious as "it went cloud" used to be. - expect(resolved.warning).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=cloud'); + expect(resolved.warning).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=postgres'); expect(resolved.warning).toContain('HASNA_KNOWLEDGE_API_URL'); }); - test('REGRESSION: the alias pointer keys do not select cloud either', () => { + test('REGRESSION: the alias pointer keys do not select postgres either', () => { const resolved = resolveKnowledgeModeSelection({ KNOWLEDGE_API_URL: FAKE_URL, KNOWLEDGE_API_KEY: FAKE_KEY, } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); expect(resolved.pointer_env_present).toEqual(['KNOWLEDGE_API_URL', 'KNOWLEDGE_API_KEY']); }); - test('an explicit cloud mode selects cloud and names the key that did it', () => { + test('an explicit postgres backend selects the API and names the key that did it', () => { const resolved = resolveKnowledgeModeSelection({ ...POINTER_ONLY, - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('cloud'); - expect(resolved.source).toEqual({ kind: 'env', name: 'HASNA_KNOWLEDGE_STORAGE_MODE', value: 'cloud' }); + expect(resolved.mode).toBe('postgres'); + expect(resolved.source).toEqual({ kind: 'env', name: 'HASNA_KNOWLEDGE_STORAGE_MODE', value: 'postgres' }); expect(resolved.pointer_ignored).toBe(false); expect(resolved.warning).toBeNull(); }); - test('an explicit local mode outranks the pointers', () => { + test('an explicit sqlite backend outranks the pointers', () => { const resolved = resolveKnowledgeModeSelection({ ...POINTER_ONLY, - HASNA_KNOWLEDGE_STORAGE_MODE: 'local', + HASNA_KNOWLEDGE_STORAGE_MODE: 'sqlite', } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); expect(resolved.source.name).toBe('HASNA_KNOWLEDGE_STORAGE_MODE'); expect(resolved.pointer_ignored).toBe(true); }); test('the first mode key wins and the later ones are not consulted', () => { const resolved = resolveKnowledgeModeSelection({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'local', - HASNA_KNOWLEDGE_MODE: 'cloud', - KNOWLEDGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'sqlite', + HASNA_KNOWLEDGE_MODE: 'postgres', + KNOWLEDGE_MODE: 'postgres', } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); expect(resolved.source.name).toBe('HASNA_KNOWLEDGE_STORAGE_MODE'); }); test('an alias mode key still selects, and says it is an alias', () => { - const resolved = resolveKnowledgeModeSelection({ KNOWLEDGE_MODE: 'cloud' } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('cloud'); + const resolved = resolveKnowledgeModeSelection({ KNOWLEDGE_MODE: 'postgres' } as NodeJS.ProcessEnv); + expect(resolved.mode).toBe('postgres'); expect(resolved.source.name).toBe('KNOWLEDGE_MODE'); expect(resolved.warning).toContain('canonical key is HASNA_KNOWLEDGE_STORAGE_MODE'); }); - test("the deprecated 'self_hosted' value normalizes to cloud with a note", () => { - const resolved = resolveKnowledgeModeSelection({ - ...POINTER_ONLY, - HASNA_KNOWLEDGE_STORAGE_MODE: 'self_hosted', - } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('cloud'); - expect(resolved.warning).toContain("Deprecated mode 'self_hosted'"); + test('removed placement words are rejected instead of normalized', () => { + expect(() => + resolveKnowledgeModeSelection({ + ...POINTER_ONLY, + HASNA_KNOWLEDGE_STORAGE_MODE: 'self_hosted', + } as NodeJS.ProcessEnv), + ).toThrow(/runtime-placement axis was removed/); + expect(() => + resolveKnowledgeModeSelection({ HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud' } as NodeJS.ProcessEnv), + ).toThrow(/runtime-placement axis was removed/); + expect(() => + resolveKnowledgeModeSelection({ HASNA_KNOWLEDGE_STORAGE_MODE: 'local' } as NodeJS.ProcessEnv), + ).toThrow(/runtime-placement axis was removed/); }); test('whitespace-only mode vars are treated as unset, not as an error', () => { const resolved = resolveKnowledgeModeSelection({ HASNA_KNOWLEDGE_STORAGE_MODE: ' ', - KNOWLEDGE_MODE: 'cloud', + KNOWLEDGE_MODE: 'postgres', } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('cloud'); + expect(resolved.mode).toBe('postgres'); expect(resolved.source.name).toBe('KNOWLEDGE_MODE'); }); @@ -163,11 +169,11 @@ describe('the resolved mode reaches the real store resolvers', () => { expect(store.location).not.toMatch(/^https?:/); }); - test('resolveItemStore returns the API transport when the mode is explicitly cloud', () => { + test('resolveItemStore returns the API transport when the backend is explicitly postgres', () => { const store = resolveItemStore({ storePath: '/tmp/knowledge-mode-test-does-not-exist/db.json', storePathOverridden: false, - env: { ...POINTER_ONLY, HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud' } as NodeJS.ProcessEnv, + env: { ...POINTER_ONLY, HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres' } as NodeJS.ProcessEnv, }); expect(store.kind).toBe('api'); expect(store.location).toBe(`${FAKE_URL}/v1`); @@ -176,9 +182,9 @@ describe('the resolved mode reaches the real store resolvers', () => { test('isKnowledgeApiMode and resolveKnowledgeCloudStore agree with the selection', () => { expect(isKnowledgeApiMode(POINTER_ONLY)).toBe(false); expect(resolveKnowledgeCloudStore(POINTER_ONLY)).toBeNull(); - const cloudEnv = { ...POINTER_ONLY, HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud' } as NodeJS.ProcessEnv; - expect(isKnowledgeApiMode(cloudEnv)).toBe(true); - expect(resolveKnowledgeCloudStore(cloudEnv)).not.toBeNull(); + const postgresEnv = { ...POINTER_ONLY, HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres' } as NodeJS.ProcessEnv; + expect(isKnowledgeApiMode(postgresEnv)).toBe(true); + expect(resolveKnowledgeCloudStore(postgresEnv)).not.toBeNull(); }); test('pinnedTransportEnv overwrites an ambient mode var in both directions', () => { @@ -189,14 +195,14 @@ describe('the resolved mode reaches the real store resolvers', () => { // 'cloud' this test used to hardcode. Those literals are only correct on one // generation of @hasna/contracts, so asserting them would have turned this // test into a second place the enum change has to be edited. - expect(pinnedTransportEnv(POINTER_ONLY, 'local').HASNA_KNOWLEDGE_STORAGE_MODE).toBe( + expect(pinnedTransportEnv(POINTER_ONLY, 'sqlite').HASNA_KNOWLEDGE_STORAGE_MODE).toBe( localStorageMode(), ); expect( - pinnedTransportEnv({ HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud' } as NodeJS.ProcessEnv, 'local') + pinnedTransportEnv({ HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres' } as NodeJS.ProcessEnv, 'sqlite') .HASNA_KNOWLEDGE_STORAGE_MODE, ).toBe(localStorageMode()); - expect(pinnedTransportEnv(POINTER_ONLY, 'cloud').HASNA_KNOWLEDGE_STORAGE_MODE).toBe( + expect(pinnedTransportEnv(POINTER_ONLY, 'postgres').HASNA_KNOWLEDGE_STORAGE_MODE).toBe( serverStorageMode(), ); // The overwrite is real in both directions: local and server must not @@ -208,7 +214,7 @@ describe('the resolved mode reaches the real store resolvers', () => { describe('the mode report is safe to print', () => { test('reports the resolved backend, the guard state, and pointer NAMES only', () => { const report = knowledgeModeReport({ ...POINTER_ONLY, NODE_ENV: 'test' } as NodeJS.ProcessEnv); - expect(report.mode).toBe('local'); + expect(report.mode).toBe('sqlite'); expect(report.store_transport).toBe('local'); expect(report.api_key_present).toBe(true); expect(report.network_guard_active).toBe(true); @@ -221,13 +227,13 @@ describe('the mode report is safe to print', () => { expect(serialized).toContain('HASNA_KNOWLEDGE_API_KEY'); }); - test('reports cloud when cloud is selected, and no guard outside test', () => { + test('reports api transport when postgres is selected, and no guard outside test', () => { const report = knowledgeModeReport({ ...POINTER_ONLY, - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', NODE_ENV: 'production', } as NodeJS.ProcessEnv); - expect(report.mode).toBe('cloud'); + expect(report.mode).toBe('postgres'); expect(report.store_transport).toBe('api'); expect(report.network_guard_active).toBe(false); }); @@ -270,11 +276,11 @@ describe('a half-configured client refuses to guess which store it is on', () => const message = (caught as Error).message; // The URL var that provoked it, so the operator knows which config is live. expect(message).toContain('HASNA_KNOWLEDGE_API_URL'); - // Both remedies. An error that only offers `=cloud` reads as "you must go - // cloud", and an operator who wanted the on-box store would unset a + // Both remedies. An error that only offers `=postgres` reads as "you must go + // to the API", and an operator who wanted the on-box store would unset a // variable they need for other tools instead of pinning the mode. - expect(message).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=cloud'); - expect(message).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=local'); + expect(message).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=postgres'); + expect(message).toContain('HASNA_KNOWLEDGE_STORAGE_MODE=sqlite'); expect((caught as { code?: string }).code).toBe('knowledge_mode_unset_with_api_url'); }); @@ -301,22 +307,22 @@ describe('a half-configured client refuses to guess which store it is on', () => expect(message).toContain('KNOWLEDGE_API_URL'); }); - test('an explicit cloud mode is unambiguous and passes', () => { + test('an explicit postgres backend is unambiguous and passes', () => { const resolved = assertKnowledgeModeSelected({ ...POINTER_ONLY, - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('cloud'); + expect(resolved.mode).toBe('postgres'); }); - test('an explicit local mode is unambiguous and passes — the pointer stays ignored', () => { + test('an explicit sqlite backend is unambiguous and passes — the pointer stays ignored', () => { // The escape hatch for a machine whose shell exports the URL for other // tooling. Saying `local` out loud is cheap; being guessed at is not. const resolved = assertKnowledgeModeSelected({ ...POINTER_ONLY, - HASNA_KNOWLEDGE_STORAGE_MODE: 'local', + HASNA_KNOWLEDGE_STORAGE_MODE: 'sqlite', } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); }); test('an API key with no URL is NOT ambiguous — there is no second store named', () => { @@ -324,45 +330,33 @@ describe('a half-configured client refuses to guess which store it is on', () => // that can never have routed anywhere, which is how a loud check gets // switched off. const resolved = assertKnowledgeModeSelected({ HASNA_KNOWLEDGE_API_KEY: FAKE_KEY } as NodeJS.ProcessEnv); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); }); test('an explicit --store override is an explicit local choice and passes', () => { const resolved = assertKnowledgeModeSelected(POINTER_ONLY, { storePathOverridden: true }); - expect(resolved.mode).toBe('local'); + expect(resolved.mode).toBe('sqlite'); }); test('an empty environment is still fine', () => { - expect(assertKnowledgeModeSelected({} as NodeJS.ProcessEnv).mode).toBe('local'); + expect(assertKnowledgeModeSelected({} as NodeJS.ProcessEnv).mode).toBe('sqlite'); }); test('the pure resolver is UNCHANGED — it still answers local without throwing', () => { // The guard is a separate gate on top of the resolution, deliberately. The // `mode` reporter has to keep working in exactly the environment the guard // rejects, or the command that explains the problem dies with it. - expect(resolveKnowledgeModeSelection(POINTER_ONLY).mode).toBe('local'); + expect(resolveKnowledgeModeSelection(POINTER_ONLY).mode).toBe('sqlite'); expect(knowledgeModeReport(URL_ONLY).pointer_ignored).toBe(true); }); }); -// -- The translation boundary ------------------------------------------------- -// -// This module holds TWO independent validators and they are allowed to disagree: -// the vendored storage-kit validates what an OPERATOR typed (`local | cloud`), -// while the live @hasna/contracts validates the token we hand its resolver. -// After the placement axis was removed the live enum accepts ONLY -// `sqlite | postgres` and THROWS on `local`/`cloud` — so the two valid sets are -// DISJOINT. -// -// That is survivable because they were never required to be the same value: -// `KnowledgeMode` types the INTERNAL semantic mode, while what reaches the -// resolver is an env STRING. `pinnedTransportEnv` is the one place they meet, so -// it translates. These tests exist to stop that translation being "simplified" -// back into a pass-through, which would reintroduce the break. +// -- The backend token boundary ---------------------------------------------- // -// `normalize` is injectable because only one contracts generation can be -// installed at a time — without the seam, forward compatibility would be an -// assertion rather than a test. +// The vendored kit and the live contracts package now share the same +// sqlite|postgres backend vocabulary. These tests keep the tiny derivation seam +// honest: the accepted tokens are checked against the installed normalizer, and +// an unrecognized future enum fails loudly instead of guessing. describe('the live-contracts token is derived, never hardcoded', () => { const acceptOnly = (accepted: readonly string[]) => (value: string) => { @@ -370,49 +364,15 @@ describe('the live-contracts token is derived, never hardcoded', () => { return value; }; - const PRE_REMOVAL = ['local', 'cloud', 'self_hosted', 'remote', 'hybrid']; - const POST_REMOVAL = ['sqlite', 'postgres', 'postgresql']; + const CURRENT = ['sqlite', 'postgres', 'postgresql']; // Widened so `toContain` compares strings rather than narrowing to the tuple. const SERVER: readonly string[] = SERVER_MODE_CANDIDATES; const LOCAL: readonly string[] = LOCAL_MODE_CANDIDATES; - test('derives the pre-removal tokens on the old contracts enum', () => { - expect(serverStorageMode(acceptOnly(PRE_REMOVAL))).toBe('cloud'); - expect(localStorageMode(acceptOnly(PRE_REMOVAL))).toBe('local'); - }); - - test('derives the post-removal tokens on the new contracts enum', () => { - // The whole point: after the bump, `cloud` and `local` both throw at the - // resolver, and these are the tokens that do not. - expect(serverStorageMode(acceptOnly(POST_REMOVAL))).toBe('postgres'); - expect(localStorageMode(acceptOnly(POST_REMOVAL))).toBe('sqlite'); - }); - - test('prefers the newest accepted token when several are valid', () => { - // A transitional release that still honours the aliases must not pin a - // deprecated one. - const transitional = acceptOnly(['sqlite', 'postgres', 'local', 'cloud', 'self_hosted']); - - expect(serverStorageMode(transitional)).toBe('postgres'); - expect(localStorageMode(transitional)).toBe('sqlite'); - }); - - test('never prefers a deprecated alias over the canonical token of the same generation', () => { - // `self_hosted` and `cloud` are BOTH accepted on the pre-removal enum, and - // `self_hosted` is the deprecated one. Picking it would be a live behaviour - // change — this package injects `cloud` today — disguised as a refactor. - // This is the assertion that caught exactly that mistake while writing this. - expect(serverStorageMode(acceptOnly(['self_hosted', 'cloud']))).toBe('cloud'); - expect(SERVER_MODE_CANDIDATES.indexOf('cloud')).toBeLessThan( - SERVER_MODE_CANDIDATES.indexOf('self_hosted'), - ); - }); - - test('the alias still works when it is the only server token on offer', () => { - // Canonical-before-deprecated is a preference, not a refusal: a generation - // that only understands the alias must still resolve rather than throw. - expect(serverStorageMode(acceptOnly(['self_hosted']))).toBe('self_hosted'); + test('derives the current backend tokens', () => { + expect(serverStorageMode(acceptOnly(CURRENT))).toBe('postgres'); + expect(localStorageMode(acceptOnly(CURRENT))).toBe('sqlite'); }); test('throws with an actionable message when the enum changes again', () => { @@ -433,8 +393,8 @@ describe('the live-contracts token is derived, never hardcoded', () => { const realServer = serverStorageMode(); const realLocal = localStorageMode(); - expect(serverStorageMode(acceptOnly(POST_REMOVAL))).toBe('postgres'); - expect(localStorageMode(acceptOnly(POST_REMOVAL))).toBe('sqlite'); + expect(serverStorageMode(acceptOnly(CURRENT))).toBe('postgres'); + expect(localStorageMode(acceptOnly(CURRENT))).toBe('sqlite'); expect(serverStorageMode()).toBe(realServer); expect(localStorageMode()).toBe(realLocal); @@ -448,27 +408,21 @@ describe('the live-contracts token is derived, never hardcoded', () => { }); test('contractsStorageModeFor maps the semantic mode, not the literal', () => { - expect(contractsStorageModeFor('cloud')).toBe(serverStorageMode()); - expect(contractsStorageModeFor('local')).toBe(localStorageMode()); - - // Across the change, both directions still translate — this is the property - // that a pass-through would lose. - expect(contractsStorageModeFor('cloud', acceptOnly(POST_REMOVAL))).toBe('postgres'); - expect(contractsStorageModeFor('local', acceptOnly(POST_REMOVAL))).toBe('sqlite'); + expect(contractsStorageModeFor('postgres')).toBe(serverStorageMode()); + expect(contractsStorageModeFor('sqlite')).toBe(localStorageMode()); + expect(contractsStorageModeFor('postgres', acceptOnly(CURRENT))).toBe('postgres'); + expect(contractsStorageModeFor('sqlite', acceptOnly(CURRENT))).toBe('sqlite'); }); - test('the operator vocabulary is untouched by the translation', () => { - // The vendored kit still validates what a person types, and `cloud` stays - // the word in the docs and the env var. Translating at the boundary must not - // leak the live token into the operator surface. + test('the operator vocabulary is the generated backend vocabulary', () => { const resolution = resolveKnowledgeModeSelection({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', } as NodeJS.ProcessEnv); - expect(resolution.mode).toBe('cloud'); - expect(resolution.source.value).toBe('cloud'); - expect(knowledgeModeReport({ HASNA_KNOWLEDGE_STORAGE_MODE: 'local' } as NodeJS.ProcessEnv).mode).toBe( - 'local', + expect(resolution.mode).toBe('postgres'); + expect(resolution.source.value).toBe('postgres'); + expect(knowledgeModeReport({ HASNA_KNOWLEDGE_STORAGE_MODE: 'sqlite' } as NodeJS.ProcessEnv).mode).toBe( + 'sqlite', ); }); }); diff --git a/tests/mcp.test.ts b/tests/mcp.test.ts index fe17523..71bf8c9 100644 --- a/tests/mcp.test.ts +++ b/tests/mcp.test.ts @@ -608,7 +608,7 @@ describe('knowledge MCP', () => { arguments: { scope: 'project' }, })); expect(databaseStorage.service).toBe('knowledge'); - expect(databaseStorage.mode).toBe('local'); + expect(databaseStorage.mode).toBe('sqlite'); expect(databaseStorage.tables).toContain('sources'); expect(databaseStorage.tables).not.toContain('chunks_fts'); @@ -857,7 +857,11 @@ describe('knowledge MCP', () => { } finally { await client.close(); } - }, 10000); + // Windows CI measured this full stdio integration at 10025.10ms while the + // matrix job itself runs `bun test --timeout 20000`; keep the test aligned + // with that required gate instead of letting this file's older 10s override + // fail a passing end-to-end run on slower Windows hosts. + }, 20_000); // ok_untag had no MCP-side coverage at all, which is how it kept returning `ok: true` on // `removed: 0` through two PRs that fixed the same defect on the CLI side. Every assertion diff --git a/tests/net-guard.test.ts b/tests/net-guard.test.ts index 367070f..781950b 100644 --- a/tests/net-guard.test.ts +++ b/tests/net-guard.test.ts @@ -126,12 +126,12 @@ describe('assertOutboundRequestAllowed', () => { describe('the guard sits at the cloud transport boundary', () => { test('a cloud read against a non-loopback endpoint is refused, not attempted', async () => { - // Explicit cloud mode, so nothing about the mode fix is doing the work here: + // Explicit postgres backend, so nothing about the mode fix is doing the work here: // this is the transport refusing to emit the request. The failure must be // the guard, NOT an HTTP status and NOT a DNS error — either of those would // mean a socket was opened. const store = resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_URL: NON_LOOPBACK, HASNA_KNOWLEDGE_API_KEY: FAKE_KEY, NODE_ENV: 'test', @@ -151,7 +151,7 @@ describe('the guard sits at the cloud transport boundary', () => { test('a cloud write against a non-loopback endpoint is refused too', async () => { const store = resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_URL: NON_LOOPBACK, HASNA_KNOWLEDGE_API_KEY: FAKE_KEY, NODE_ENV: 'test', @@ -268,7 +268,7 @@ describe('loopback cloud traffic still works (positive control)', () => { test('the real HTTP transport reaches a 127.0.0.1 server while the guard is armed', async () => { const store = resolveKnowledgeCloudStore({ - HASNA_KNOWLEDGE_STORAGE_MODE: 'cloud', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', HASNA_KNOWLEDGE_API_URL: `http://127.0.0.1:${server.port}`, HASNA_KNOWLEDGE_API_KEY: FAKE_KEY, NODE_ENV: 'test', diff --git a/tests/serve.test.ts b/tests/serve.test.ts index 8179521..3be30ce 100644 --- a/tests/serve.test.ts +++ b/tests/serve.test.ts @@ -130,7 +130,7 @@ describe('knowledge-serve', () => { expect(res.status).toBe(200); const body = (await res.json()) as { status: string; version: string; mode: string }; expect(body.version).toBe('9.9.9'); - expect(body.mode).toBe('cloud'); + expect(body.mode).toBe('postgres'); expect(typeof body.status).toBe('string'); } }); diff --git a/tests/storage.test.ts b/tests/storage.test.ts index 8f2835b..5ee6de4 100644 --- a/tests/storage.test.ts +++ b/tests/storage.test.ts @@ -24,20 +24,18 @@ afterEach(() => { describe('knowledge database storage status (local, read-only)', () => { test('resolves the storage mode from the mode env only (no client DSN surface)', () => { for (const key of ENV_KEYS) delete process.env[key]; - // Default is local; the client has NO DATABASE_URL/DSN surface at all. - expect(getStorageMode()).toBe('local'); + // Default is sqlite; the client has NO DATABASE_URL/DSN surface at all. + expect(getStorageMode()).toBe('sqlite'); - // Canonical cloud mode, plus deprecated aliases that normalize to cloud. - process.env[KNOWLEDGE_STORAGE_MODE_ENV] = 'cloud'; - expect(getStorageMode()).toBe('cloud'); - process.env[KNOWLEDGE_STORAGE_MODE_ENV] = 'remote'; - expect(getStorageMode()).toBe('cloud'); - process.env[KNOWLEDGE_STORAGE_MODE_ENV] = 'hybrid'; - expect(getStorageMode()).toBe('cloud'); + // Canonical postgres mode, plus the long spelling that normalizes to it. + process.env[KNOWLEDGE_STORAGE_MODE_ENV] = 'postgres'; + expect(getStorageMode()).toBe('postgres'); + process.env[KNOWLEDGE_STORAGE_MODE_ENV] = 'postgresql'; + expect(getStorageMode()).toBe('postgres'); process.env[KNOWLEDGE_STORAGE_MODE_ENV] = 'invalid'; - process.env[KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV] = 'local'; - expect(getStorageMode()).toBe('local'); + process.env[KNOWLEDGE_STORAGE_MODE_FALLBACK_ENV] = 'sqlite'; + expect(getStorageMode()).toBe('sqlite'); }); test('exposes durable knowledge tables and excludes local FTS indexes', () => { @@ -61,7 +59,7 @@ describe('knowledge database storage status (local, read-only)', () => { const status = getStorageStatus({ scope: 'project', cwd: dir }); expect(status).toMatchObject({ - mode: 'local', + mode: 'sqlite', service: 'knowledge', scope: 'project', sync: [],