omo-ai 5.1.19 → 5.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- // omo:4hSxbr1d_SgSeAij9pWskPBns3dyO3gonjf5Cy2cDlE:R0OC11lokvcJufZCbFm4ov_rrUH7I5W1DfFQLXHuo5M
1
+ // omo:jus4MRkMXwd5ysFZBDWdBqduBLYRaV99q-XKSQo5XW0:R0OC11lokvcJufZCbFm4ov_rrUH7I5W1DfFQLXHuo5M
2
2
  import{createHash as e}from"node:crypto";import{Buffer as t}from"node:buffer";import*as n from"node:fs";import*as r from"node:fs/promises";function i(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}async function o(e){for(let t=0;;t+=1)try{return await e()}catch(e){if("EINTR"!==i(e)||t>=128)throw e}}function a(e){for(let t=0;;t+=1)try{return e()}catch(e){if("EINTR"!==i(e)||t>=128)throw e}}var s=new Set(["EPERM","EBUSY","EACCES"]),u=[10,25,50,100,200,400],l=e=>new Promise(t=>setTimeout(t,e));import{Buffer as c}from"node:buffer";import{constants as d}from"node:fs";import*as f from"node:fs/promises";function p(e){return"number"==typeof e?0!==(e&d.O_EXCL):"string"==typeof e&&e.toLowerCase().includes("x")}async function h(e,t,n,r){let i="string"==typeof t?c.from(t,n??"utf8"):t,a=0;for(;a<i.length;){r?.throwIfAborted();let{bytesWritten:t}=await o(()=>e.write(i,a));if(t<=0)throw Error(`fs write made no progress at offset ${a}`);a+=t}}function m(e){return"function"==typeof e}function y(e){return(...t)=>o(async()=>e(...t))}function v(e){return(...t)=>a(()=>e(...t))}function g(e,t){let n="async"===t?y:v,r=new Map;return new Proxy(e,{get(e,t){if(r.has(t))return r.get(t);let i=Reflect.get(e,t);if(!m(i))return i;let o=n(i),a=Reflect.get(i,"native");return m(a)&&Object.assign(o,{native:n(a)}),r.set(t,o),o}})}var w=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]);var _=g(r,"async");function b(e,t){return async function(e,t,n){let r="win32"===n.platform?n.delaysMs??u:[],o=n.sleep??l;for(let a=0;;a+=1)try{return void await n.rename(e,t)}catch(e){let t=r[a],n=i(e);if(void 0===t||void 0===n||!s.has(n))throw e;await o(t)}}(e,t,{rename:_.rename,platform:process.platform})}var k=g(n,"sync"),{access:$,chmod:z,copyFile:S,cp:O,link:E,lstat:x,mkdir:I,mkdtemp:A,readFile:P,readdir:N,realpath:j,rm:T,rmdir:Z,stat:F,unlink:D}=_,{accessSync:R,chmodSync:M,fsyncSync:C,linkSync:U,lstatSync:J,mkdirSync:L,readFileSync:B,readdirSync:W,realpathSync:K,statSync:V,unlinkSync:G,writeFileSync:q,writeSync:H}=k,Y=async(...e)=>{let t=()=>r.open(...e);return function(e){return new Proxy(e,{get(e,t){let n=Reflect.get(e,t);if(!m(n))return n;let r=t=>Reflect.apply(n,e,[...t]);return"close"===t||t===Symbol.asyncDispose?(...e)=>{let t=r(e);return t instanceof Promise?t.catch(e=>{if("EINTR"!==i(e))throw e}):t}:"string"==typeof t&&w.has(t)?(...e)=>{let t=r(e);return t instanceof Promise?t.catch(t=>{if("EINTR"!==i(t))throw t;return o(async()=>r(e))}):t}:(...e)=>r(e)}})}(await(p(e[1]??"r")?t():o(t)))};var X=async(e,n,a)=>{if("string"!=typeof n&&!(n instanceof Uint8Array))return r.writeFile(e,n,a);if("object"==typeof(s=e)&&!(s instanceof URL)&&!t.isBuffer(s)&&"fd"in s){let t="string"==typeof a?{encoding:a}:a??{};return t.signal?.throwIfAborted(),await h(e,n,t.encoding??void 0,t.signal),void(!0===t.flush&&await o(()=>e.sync()))}var s;return async function(e,t,n,r){let a="string"==typeof n?{encoding:n}:n??{};a.signal?.throwIfAborted();let s=a.flag??r,u=()=>f.open(e,s,a.mode),l=await(p(s)?u():o(u));try{await h(l,t,a.encoding??"utf8",a.signal),!0===a.flush&&await o(()=>l.sync())}finally{await l.close().catch(e=>{if("EINTR"!==i(e))throw e})}}(e,n,a??void 0,"w")};function Q(e){try{return a(()=>n.statSync(e)),!0}catch{return!1}}import{hostname as ee}from"node:os";import{join as te}from"node:path";class ne extends Error{constructor(e,t){super(e,t),this.name=new.target.name}}class re extends ne{argv;timeoutMs;constructor(e,t){super(`git ${e.join(" ")} timed out after ${t}ms`),this.argv=e,this.timeoutMs=t}}class ie extends ne{constructor(e){super("Git is required for memory storage but was not found on PATH.",e)}}import{spawn as oe}from"node:child_process";import{win32 as ae}from"node:path";var se=[["ProgramFiles",["Git","cmd","git.exe"]],["ProgramW6432",["Git","cmd","git.exe"]],["ProgramFiles(x86)",["Git","cmd","git.exe"]],["LOCALAPPDATA",["Programs","Git","cmd","git.exe"]]];function ue(e,t){for(let[n,r]of Object.entries(e)){if(n.toLowerCase()!==t.toLowerCase()||void 0===r)continue;let e=r.trim();if(e.length>0)return e}}function le(e){return e instanceof ie&&e.cause instanceof Error&&"ENOENT"===e.cause.code}function ce(e,t,n,r){return new Promise((i,o)=>{let a=void 0!==n.stdin,s=oe(e,[...t],{cwd:n.cwd,env:r,shell:!1,stdio:[a?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),u=[],l=[],c=!1,d=!1,f=setTimeout(()=>{d=!0,s.kill("SIGKILL")},n.timeoutMs);s.stdout.on("data",e=>u.push(e)),s.stderr.on("data",e=>l.push(e)),a&&s.stdin.end(n.stdin),s.on("error",e=>{if(!c)if(c=!0,clearTimeout(f),"ENOENT"===e.code){if(!Q(n.cwd))return void i({code:128,stdout:"",stderr:`fatal: cannot change to '${n.cwd}': No such file or directory`});o(new ie({cause:e}))}else o(e)}),s.on("close",e=>{if(c)return;if(c=!0,clearTimeout(f),d)return void o(new re(t,n.timeoutMs));let r=Buffer.concat(u);i({code:e??1,stdout:r.toString("utf8"),stderr:Buffer.concat(l).toString("utf8"),stdoutBytes:r})})})}function de(e={}){let t=e.platform??process.platform,n=e.runCommand??ce;return{async run(e,r){let i=r.env??process.env;try{return await n("git",e,r,i)}catch(o){if("win32"!==t||!le(o))throw o;for(let t of function(e){let t=new Set,n=[];for(let[r,i]of se){let o=ue(e,r);if(void 0===o||!/^[A-Za-z]:[\\/]/.test(o))continue;let a=ae.join(o,...i),s=ae.normalize(a).toLowerCase();t.has(s)||(t.add(s),n.push(a))}return n}(i))try{return await n(t,e,r,i)}catch(e){if(le(e))continue;throw e}throw o}}}}import{randomUUID as fe}from"node:crypto";import{hostname as pe}from"node:os";import he from"node:path";import me from"node:path";var ye=new Set;function ve(e){ye.add(e)}function ge(e){ye.delete(e)}var we=/\.candidate-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _e(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}function be(e,t){try{e.onFailure?.(t)}catch{}}function ke(e){if("win32"!==process.platform)return!1;let t=_e(e);return"EBUSY"===t||"EPERM"===t||"EACCES"===t}import{randomUUID as $e}from"node:crypto";import{hostname as ze}from"node:os";import{execFile as Se}from"node:child_process";var Oe=null;function Ee(){return Oe??=async function(){if("darwin"!==process.platform)return null;try{let{dlopen:e,FFIType:t}=await(import("bun:ffi")),n=e("/usr/lib/libSystem.B.dylib",{proc_pidinfo:{args:[t.i32,t.i32,t.u64,t.ptr,t.i32],returns:t.i32}});return(e,t,r,i,o)=>Number(n.symbols.proc_pidinfo(e,t,r,i,o))}catch{return null}}(),Oe}var xe=null;async function Ie(e){if("win32"!==process.platform)return null;if(!Number.isSafeInteger(e)||e<=0)return null;xe??=async function(){if("win32"!==process.platform)return null;try{let{dlopen:e,FFIType:t}=await(import("bun:ffi"));return e("kernel32.dll",{OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.ptr},GetProcessTimes:{args:[t.ptr,t.ptr,t.ptr,t.ptr,t.ptr],returns:t.i32},CloseHandle:{args:[t.ptr],returns:t.i32}}).symbols}catch{return null}}();let t=await xe;if(null===t)return null;let n=t.OpenProcess(4096,0,e);if(null===n||0===n||0n===n)return null;try{let e=new BigUint64Array(1),r=t.GetProcessTimes(n,e,new BigUint64Array(1),new BigUint64Array(1),new BigUint64Array(1)),i=e[0]??0n;return 0===r||0n===i?null:i}finally{t.CloseHandle(n)}}async function Ae(e,t){return await new Promise(n=>{Se(e,t,{encoding:"utf8",timeout:2e3,windowsHide:!0},(e,t)=>{if(null!==e)return void n(null);let r=t.trim();n(r.length>0?r:null)})})}var Pe=function(e,t){let n;return r=>r!==t?e(r):(n??=e(r).then(e=>(null===e&&(n=void 0),e),e=>{throw n=void 0,e}),n)}(async function(e){if("linux"===process.platform)return await async function(e){try{let t=await P(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let r=t.slice(n+2).trim().split(/\s+/)[19];return void 0===r?null:`linux-proc-start-ticks:${r}`}catch{return null}}(e);if("darwin"===process.platform||"freebsd"===process.platform){if("dead"===je(e))return null;let t=await async function(e){if("darwin"!==process.platform)return null;if(!Number.isSafeInteger(e)||e<=0)return null;let t=await Ee();if(null===t)return null;let n=new Uint8Array(136),r=0;try{r=t(e,3,0n,n,136)}catch{return null}if(136!==r)return null;let i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=Number(i.getBigUint64(120,!0));return o>0?o:null}(e);if(null!==t)return`proc-start-epoch:${t}`;let n=await Ae("/bin/ps",["-o","lstart=","-p",String(e)]);return null===n?null:`ps-lstart:${n.replace(/\s+/g," ")}`}return"win32"===process.platform?await async function(e){if("dead"===je(e))return null;let t=await Ie(e);if(null!==t)return`win32-creation-filetime:${t}`;let n=await Ae("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${e} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`]);return null===n?null:`win32-creation-date:${n}`}(e):null},process.pid);function Ne(e){let t=e.indexOf(":");return t<=0?null:e.slice(0,t)}function je(e){try{return process.kill(e,0),"alive"}catch(e){let t=function(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return"ESRCH"===t?"dead":"EPERM"===t?"alive":"unknown"}}function Te(e){return"string"==typeof e&&e.length>0}function Ze(e){let t;try{t=JSON.parse(e)}catch{return null}if("object"!=typeof t||null===t||Array.isArray(t))return null;let n=t;return!Number.isInteger(n.pid)||Number(n.pid)<=0?null:Te(n.process_start)&&Te(n.hostname)&&Te(n.nonce)?!Te(n.created_at)||Number.isNaN(Date.parse(n.created_at))?null:Te(n.purpose)&&(void 0===n.run_id||Te(n.run_id))?{pid:Number(n.pid),process_start:n.process_start,hostname:n.hostname,nonce:n.nonce,created_at:n.created_at,purpose:n.purpose,...void 0===n.run_id?{}:{run_id:n.run_id}}:null:null}var Fe=new Set(["EACCES","EPERM","ENOTSUP"]);class De extends Error{lockPath;owner;retriable=!0;constructor(e,t){super(`Lock is held: ${e}`),this.lockPath=e,this.owner=t,this.name="LockContentionError"}}function Re(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}function Me(e,t){if(void 0!==t)return t(e);if("win32"!==process.platform)return!1;let n=Re(e);return"EBUSY"===n||"EPERM"===n||"EACCES"===n}async function Ce(e){for(let t=0;t<3;t+=1)try{return await(We.unlink??D)(e),ge(e),!0}catch(n){if("ENOENT"===Re(n))return ge(e),!0;if(!Me(n,We.isSharingError))throw ve(e),Ke(he.dirname(e)),n;if(t+1===3)return ve(e),Ke(he.dirname(e)),!1}return!1}function Ue(e,t){return t?.throwIfAborted(),new Promise((n,r)=>{let i=setTimeout(a,e),o=()=>a(t?.reason??new DOMException("The operation was aborted","AbortError"));function a(e){clearTimeout(i),t?.removeEventListener("abort",o),void 0===e?n():r(e)}t?.addEventListener("abort",o,{once:!0})})}async function Je(e){try{let t=await P(e,"utf8"),n=await F(e,{bigint:!0});return{raw:t,record:Ze(t),dev:n.dev,ino:n.ino,mtimeMs:Number(n.mtimeMs)}}catch(e){let t=Re(e);if("ENOENT"===t)return null;if("\\"===he.sep&&"EPERM"===t)return{raw:"",record:null,dev:0,ino:0,mtimeMs:Date.now()};throw e}}async function Le(e,t){await I(he.dirname(e),{recursive:!0,mode:448});let{candidatePath:n,handle:r}=await async function(e){for(let t=0;;t+=1){let n=`${e}.candidate-${fe()}`;try{return{candidatePath:n,handle:await Y(n,"wx",384)}}catch(r){if(await Ce(n)||Ke(he.dirname(e)),"EINTR"!==Re(r)||t>=128)throw r}}}(e);try{try{await h(r,`${JSON.stringify(t)}\n`,"utf8"),await r.sync()}finally{await r.close()}try{return await(We.link??E)(n,e),!0}catch(n){if(function(e){let t=Re(e);return"EEXIST"===t||"ENOENT"===t}(n))return!1;if(Fe.has(Re(n)??""))return await async function(e,t){let n;try{n=await Y(e,"wx",384)}catch(e){if("EEXIST"===Re(e))return!1;throw e}try{return await(We.writeFallback??h)(n,`${JSON.stringify(t)}\n`,"utf8"),await n.sync(),!0}finally{await n.close()}}(e,t);throw n}}finally{await Ce(n)||Ke(he.dirname(e))}}var Be=new Set,We={};function Ke(e){Be.delete(e)}async function Ve(e){if(e.hostname!==pe())return!1;let t=je(e.pid);if("dead"===t)return!0;if("unknown"===t)return!1;let n=await Pe(e.pid);return null!==n&&"unavailable"!==e.process_start&&function(e,t){let n=Ne(e);return null!==n&&n===Ne(t)&&e!==t}(e.process_start,n)}function Ge(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mtimeMs===t.mtimeMs&&e.raw===t.raw}async function qe(e,t,n){return null!==e.record?Ve(e.record):t-e.mtimeMs>n}async function He(e,t,n){let r=await Je(e);if(null===r||!await qe(r,t,n))return!1;let i=`${e}.reaping-${fe()}`;try{await b(e,i)}catch(e){if("ENOENT"===Re(e))return!1;if(Me(e))return!1;throw e}let o=await Je(i);if(null!==o&&Ge(o,r))return await D(i),!0;try{await E(i,e)}catch(e){if("EEXIST"!==Re(e))throw e}return await D(i),!1}async function Ye(e,t,n,r,i){if(!await qe(t,r,i))return!1;let o=`${e}.recovery`,a={...n,nonce:fe(),created_at:(new Date).toISOString(),purpose:`${n.purpose}:recovery`};for(let e=0;!await Le(o,a);e+=1)if(e>0||!await He(o,r,i))return!1;try{let n=await Je(e);if(null===n)return!0;if(!Ge(n,t))return!1;if(!await qe(n,r,i))return!1;let s=await Je(o);return null!==s&&s.record?.nonce===a.nonce&&(await D(e),!0)}finally{await Qe(o,a)}}async function Xe(e,t,n={}){let r=n.waitTimeoutMs??0,i=n.retryDelayMs??25,o=n.incompleteLockGraceMs??5e3,a=n.now??Date.now;if(r<0||i<=0||o<0)throw Error("lock wait options must be positive");let s=he.dirname(e);Be.has(s)||(Be.add(s),await async function(e,t=Date.now,n={}){let r;try{r=await N(e)}catch(t){if("ENOENT"===_e(t)){for(let t of ye)me.dirname(t)===e&&ge(t);return 0}throw t}let i=0;for(let o of r){if(!we.test(o))continue;let r=me.join(e,o);try{let e=await F(r);if(!ye.has(r)&&t()-e.mtimeMs<=36e5)continue;let o=!1;for(let e=0;e<3;e+=1)try{await(n.unlink??D)(r),ge(r),o=!0;break}catch(t){if("ENOENT"===_e(t)){ge(r),o=!0;break}if(!(n.isSharingError?.(t)??ke(t)))throw t;e+1===3&&be(n,r)}o&&(i+=1)}catch(e){"ENOENT"===_e(e)&&ge(r),be(n,r)}}return i}(s,Date.now,{...void 0===We.unlink?{}:{unlink:We.unlink},...void 0===We.isSharingError?{}:{isSharingError:We.isSharingError},onFailure:()=>Ke(s)}).catch(()=>{Ke(s)}));let u=a()+r;for(;;){n.signal?.throwIfAborted();let r=await Je(e);if(null===r){if(await Le(e,t))return;if(n.signal?.throwIfAborted(),r=await Je(e),null===r)continue}if(!await Ye(e,r,t,a(),o)){if(n.signal?.throwIfAborted(),a()>=u)throw new De(e,r.record);await Ue(Math.min(i,Math.max(1,u-a())),n.signal)}}}async function Qe(e,t){let n=await Je(e);if(null===n||n.record?.nonce!==t.nonce)return!1;try{return await D(e),!0}catch(e){if("ENOENT"===Re(e))return!1;throw e}}import et from"node:path";Promise.resolve();var tt=[["\\bAKIA[0-9A-Z]{16}\\b",""],["\\b(?:bearer|token|api[_-]?key|secret|password|passwd|pwd)\\s*[=:]\\s*\\S{1,256}","i"],["\\bAuthorization\\s*:\\s*Bearer\\s+\\S{1,256}","i"],["\\bsk-(?:proj-)?[-_A-Za-z0-9]+\\b",""],["\\b(?:ghp|github_pat|glpat|xox[baprs])-[-_A-Za-z0-9]+\\b",""]];tt.map(([e,t])=>new RegExp(e,t)),tt.map(([e,t])=>new RegExp(e,`${t}g`));var nt=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,rt=/^"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"$/,it=/^'(?:[^']|'')*'$/;function ot(e){return function(e){if(rt.test(e))try{let t=JSON.parse(e);return"string"==typeof t?t:void 0}catch{return}if(it.test(e))return e.slice(1,-1).replace(/''/g,"'")}(e)??e}class at extends Error{name="FrontmatterError"}var st=/^[A-Za-z0-9_-]+$/;function ut(e){let t=e.match(nt);if(!t)throw new at("frontmatter: target file is missing required frontmatter");let n,r,i,o,a=t[1]??"",s=t[2]??"",u={};for(let e of a.split(/\r?\n/)){let t=e.indexOf(":");if(t<=0)continue;let a=e.slice(0,t).trim(),s=e.slice(t+1).trim();"description"===a?n=ot(s):"read_only"===a?r=s:"kind"===a?i=ot(s):"aliases"===a?o=lt(s,e):"limit"!==a&&st.test(a)&&(u[a]=s)}if(!n||!n.trim())throw new at("frontmatter: target file frontmatter is missing 'description'");return{frontmatter:{description:n,...void 0!==r?{read_only:r}:{},...void 0!==i?{kind:i}:{},...void 0!==o?{aliases:o}:{},...Object.keys(u).length>0?{extra:u}:{}},body:s}}function lt(e,t){let n,r=e.trim();if(!r.startsWith("["))throw new at(`frontmatter: 'aliases' must be a JSON array of non-empty strings (line: ${t})`);try{n=JSON.parse(r)}catch{throw new at(`frontmatter: 'aliases' is not valid JSON (line: ${t})`)}if(!Array.isArray(n))throw new at(`frontmatter: 'aliases' must be a JSON array, not ${typeof n} (line: ${t})`);for(let e of n)if("string"!=typeof e||""===e.trim())throw new at(`frontmatter: 'aliases' array must contain only non-empty strings (line: ${t})`);return n}var ct=/^(?:memory\/)?(?:(?:system|reference|people)\/.*\.md|skills\/.+\/SKILL\.md)$/;function dt(e){return ct.test(e.replace(/\\/g,"/"))}new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});import{dirname as ft}from"node:path";import{fileURLToPath as pt}from"node:url";ft(pt(import.meta.url));import{createHash as ht}from"node:crypto";import{join as mt}from"node:path";function yt(e,t){return ht("sha256").update(e).digest("hex").slice(0,t)}function vt(e){let t=e.factsQueue,n=mt(t,"cursor");return{queueDir:t,cursorDir:n,consumedPath:mt(t,"consumed.json"),failuresPath:mt(t,"failures.json"),cursorPath:e=>mt(n,`${yt(e,12)}.json`),entryPath:(e,n,r)=>mt(t,`${function(e){return e.toISOString().replaceAll("-","").replaceAll(":","").replace(".","")}(r)}-${yt(e,12)}-${yt(n,8)}.json`)}}var gt=["quick_category_unavailable","child_exit","deadline_exceeded","invalid_extraction","memory_write_lock_exhausted","parent_dirty","unknown_liveness","payload_envelope_oversize","payload_entry_oversize","other"];class wt extends Error{name="FactsFailuresCorruptError";constructor(e){super(`facts failures file is unusable: ${e}`)}}function _t(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function bt(e,t){if("string"!=typeof e||0===e.length)throw new wt(`${t} must be a non-empty string`);return e}function kt(e,t){let n=bt(e,t),r=new Date(n);if(Number.isNaN(r.getTime())||r.toISOString()!==n)throw new wt(`${t} must be an ISO-8601 instant`);return n}function $t(e,t){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw new wt(`${t} must be a non-negative integer`);return e}function zt(e){if("string"!=typeof e||!gt.includes(e))throw new wt(`lastReason "${String(e)}" is not a known reason`);return e}function St(e){if(!_t(e))throw new wt("entries must contain objects");let t=function(e){if("backoff"!==e&&"parked"!==e)throw new wt(`state "${String(e)}" is not backoff or parked`);return e}(e.state),n=null===e.nextEligibleAt?null:kt(e.nextEligibleAt,"nextEligibleAt"),r=void 0===e.parkedAt?void 0:kt(e.parkedAt,"parkedAt");if("parked"===t&&(null!==n||void 0===r))throw new wt("a parked record needs parkedAt and a null nextEligibleAt");if("backoff"===t&&(null===n||void 0!==r))throw new wt("a backoff record needs nextEligibleAt and no parkedAt");let i=$t(e.streak,"streak");if(i<1)throw new wt("streak must be at least 1");let o={conversationId:bt(e.conversationId,"conversationId"),end_message_id:bt(e.end_message_id,"end_message_id"),end_snapshot_line:$t(e.end_snapshot_line,"end_snapshot_line"),state:t,streak:i,firstFailureAt:kt(e.firstFailureAt,"firstFailureAt"),lastFailureAt:kt(e.lastFailureAt,"lastFailureAt"),lastReason:zt(e.lastReason),lastFailureId:bt(e.lastFailureId,"lastFailureId"),nextEligibleAt:n},a=function(e,t){if(void 0!==e)return bt(e,t)}(e.lastDetail,"lastDetail");return{...o,...void 0===a?{}:{lastDetail:a},...void 0===r?{}:{parkedAt:r}}}function Ot(e){return[...e].sort((e,t)=>e.conversationId!==t.conversationId?e.conversationId<t.conversationId?-1:1:e.end_snapshot_line!==t.end_snapshot_line?e.end_snapshot_line-t.end_snapshot_line:e.end_message_id===t.end_message_id?0:e.end_message_id<t.end_message_id?-1:1)}var Et=[6e4,3e5,18e5,72e5];function xt(e,t){return`${e}\0${t}`}function It(e){return xt(e.conversationId,e.end_message_id)}function At(e){return xt(e.conversationId,e.endMessageId)}function Pt(e){let t=e.replace(/[\u0000-\u001f\u007f]+/g," ").trim();if(0!==t.length)return function(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n=0,r=0;for(let i of e){let e=Buffer.byteLength(i,"utf8");if(n+e>t)break;n+=e,r+=i.length}return e.slice(0,r)}(t,512)}function Nt(e,t,n,r){let i=n.now.toISOString(),o=(e?.streak??0)+1,a="parked"===e?.state||"payload_entry_oversize"===n.reason||o>=5;return{conversationId:t.conversationId,end_message_id:t.endMessageId,end_snapshot_line:t.endSnapshotLine,state:a?"parked":"backoff",streak:o,firstFailureAt:e?.firstFailureAt??i,lastFailureAt:i,lastReason:n.reason,lastFailureId:n.failureId,nextEligibleAt:a?null:new Date(n.now.getTime()+jt(o)).toISOString(),...void 0===r?{}:{lastDetail:r},...a?{parkedAt:e?.parkedAt??i}:{}}}function jt(e){return Et[Math.min(e,Et.length)-1]??0}import{randomUUID as Tt}from"node:crypto";import{dirname as Zt,join as Ft}from"node:path";var Dt=new Set(["ENOENT","EISDIR","EPERM","EACCES","EINVAL"]);function Rt(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}class Mt{layout;lockPath;lockWaitMs;now;constructor(e){var t;this.layout=vt(e.identityPaths),this.lockPath=(t=e.identityPaths.locks,et.join(t,"facts-queue.lock")),this.lockWaitMs=e.lockWaitMs??2e3,this.now=e.now??(()=>new Date)}async readFailures(){return this.locked(()=>this.readUnlocked())}async recordFailure(e){return this.mutate((t,n)=>function(e){let t=void 0===e.detail?void 0:Pt(e.detail),n=new Map(e.entries.map(e=>[It(e),e]));for(let r of e.targets){let i=n.get(At(r));i?.lastFailureId!==e.failureId&&n.set(At(r),Nt(i,r,e,t))}return Ot([...n.values()])}({entries:t,targets:e.targets,failureId:e.failureId,reason:e.reason,...void 0===e.detail?{}:{detail:e.detail},now:n}))}async clearOnSuccess(e){return this.mutate(t=>function(e,t){let n=new Set(t.map(e=>At(e)));return e.filter(e=>!n.has(It(e)))}(t,e))}async clearForRetry(e){let t=0;return await this.mutate(n=>{let r=function(e,t){return e.filter(e=>void 0!==t.conversationId&&e.conversationId!==t.conversationId||void 0!==t.endMessageId&&e.end_message_id!==t.endMessageId)}(n,e);return t=n.length-r.length,r}),t}async mutate(e){return this.locked(async()=>{let t=await this.readUnlocked(),n=this.now(),r=e(t.entries,n),i={version:t.version,updatedAt:n.toISOString(),entries:r};return await this.writeAtomically(function(e,t){let n={version:1,updatedAt:t,entries:Ot(e)};return`${JSON.stringify(n,null,2)}\n`}(r,i.updatedAt)),i})}async readUnlocked(){let e=await P(this.layout.failuresPath,"utf8").catch(e=>{if("ENOENT"!==Rt(e))throw e});return void 0===e?{version:1,updatedAt:this.now().toISOString(),entries:[]}:function(e){let t;try{t=JSON.parse(e)}catch(e){throw new wt(e instanceof Error?e.message:"unreadable JSON")}if(!_t(t))throw new wt("root must be an object");if(1!==t.version)throw new wt(`unsupported version ${String(t.version)}`);if(!Array.isArray(t.entries))throw new wt("entries must be an array");let n=t.entries.map(e=>St(e));return{version:1,updatedAt:kt(t.updatedAt,"updatedAt"),entries:Ot(n)}}(e)}async writeAtomically(e){let t=Zt(this.layout.failuresPath);await I(t,{recursive:!0});let n=Ft(t,`.failures-${process.pid}-${Tt()}.tmp`),r=await Y(n,"wx",384);try{await h(r,e,"utf8"),await r.sync()}catch(e){throw await r.close(),await T(n,{force:!0}),e}await r.close();try{await b(n,this.layout.failuresPath)}catch(e){throw await T(n,{force:!0}),e}await async function(e){let t;try{t=await Y(e,"r")}catch(e){if(Dt.has(Rt(e)??""))return;throw e}try{await t.sync()}catch(e){if(!Dt.has(Rt(e)??""))throw e}finally{await t.close()}}(t)}async locked(e){await I(this.layout.queueDir,{recursive:!0}),await I(Zt(this.lockPath),{recursive:!0});let t=await async function(e,t={}){if(0===e.length)throw Error("lock purpose must not be empty");let n=await Pe(process.pid);return{pid:process.pid,process_start:n??"unavailable",hostname:ze(),nonce:$e(),created_at:(new Date).toISOString(),purpose:e,...void 0===t.runId?{}:{run_id:t.runId}}}("facts-queue");return async function(e,t,n,r){await Xe(e,t,r);try{return await n()}finally{await Qe(e,t)}}(this.lockPath,t,e,{waitTimeoutMs:this.lockWaitMs})}}import{dirname as Ct}from"node:path";import{fileURLToPath as Ut}from"node:url";Ct(Ut(import.meta.url));class Jt extends Error{name="ReflectionParkStateError"}function Lt(e){if(!Wt(e)||1!==e.version)throw new Jt("Invalid reflection park state");let t=e.streak;if("number"!=typeof t||!Number.isInteger(t)||t<0)throw new Jt("Invalid reflection park streak");let n=Bt(e.firstFailureAt,"firstFailureAt"),r=Bt(e.parkedAt,"parkedAt"),i=Bt(e.lastProbeAt,"lastProbeAt"),o=void 0===e.lastFailure?void 0:function(e){if(!Wt(e))throw new Jt("Invalid reflection park failure");let{runId:t,at:n,fingerprint:r,retryable:i,reason:o,detail:a}=e;if("string"!=typeof t||"string"!=typeof r||"boolean"!=typeof i)throw new Jt("Invalid reflection park failure");let s=Bt(n,"at");if(void 0===s)throw new Jt("Invalid reflection park failure timestamp");if(void 0!==o&&"string"!=typeof o)throw new Jt("Invalid reflection park failure reason");if(void 0!==a&&"string"!=typeof a)throw new Jt("Invalid reflection park failure detail");return{runId:t,at:s,fingerprint:r,retryable:i,...void 0===o?{}:{reason:o},...void 0===a?{}:{detail:a}}}(e.lastFailure);return{version:1,streak:t,...void 0===n?{}:{firstFailureAt:n},...void 0===o?{}:{lastFailure:o},...void 0===r?{}:{parkedAt:r},...void 0===i?{}:{lastProbeAt:i}}}function Bt(e,t){if(void 0!==e){if("string"!=typeof e||Number.isNaN(Date.parse(e)))throw new Jt(`Invalid reflection park ${t}`);return e}}function Wt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}import{join as Kt}from"node:path";async function Vt(e){let t;try{t=await P(e,"utf8")}catch(e){if("ENOENT"===function(e){if(!(e instanceof Error&&"code"in e))return;return"string"==typeof e.code?e.code:void 0}(e))return null;throw e}return JSON.parse(t)}new Date(0).toISOString();var Gt="\\p{Script=Hangul}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\u30fc";new RegExp(`[${Gt}]+|(?:(?![${Gt}])[\\p{L}\\p{M}\\p{N}])+`,"gu"),new RegExp(`^[${Gt}]+$`,"u"),new RegExp(`[${Gt}]`,"u"),new RegExp(`[${Gt}]`,"gu"),new RegExp(`[\\p{L}${Gt}]`,"gu");import{dirname as qt}from"node:path";import{fileURLToPath as Ht}from"node:url";qt(Ht(import.meta.url));var Yt=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,Xt=[/^\d+\s*\|/,/^\^+$/,/^at\s+\S/,/^(?:path|syscall|errno|code|dest|address|port|erroredSysCall)\s*:/i,/^Bun v\d/,/^\[truncated to last \d+ bytes\]$/],Qt=/^(?:[A-Z][A-Za-z]*(?:Error|Exception)|E[A-Z]{2,}|[Ee]rror|[Ww]arning|[Ff]atal)\b/;function en(e,t){return`${e??"failed"}:${(function(e){if(void 0===e)return e;let t=e.split("\n").map(e=>e.replace(Yt,"").replace(/\s+/g," ").trim()).filter(e=>e.length>0&&!Xt.some(t=>t.test(e))),n=t.find(e=>Qt.test(e))??t[0];return void 0!==n?n.length<=200?n:`${n.slice(0,199)}…`:void 0}(t)??"").slice(0,60)}`}function tn(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function nn(e,t="|"){return e.map(e=>Sn(e)).join(t)}function rn(e,t){return"bigint"==typeof t?t.toString():t}class on{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return void 0!==e&&(this._value=e(),this._getter=void 0),this._value}}function an(e){return new on(e)}function sn(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function un(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ln(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function cn(e){return ln(e._zod.def)??e._zod.def.shape}function dn(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return un(this,t,e),e},enumerable:!0,configurable:!0})}function fn(e,t,n){t in e?un(e,t,n):e[t]=n}function pn(e,t,n,r){let i=cn(t);for(let o of n){let n=Object.getOwnPropertyDescriptor(i,o);n.enumerable&&(n.get?dn(e,o,()=>{let e=t._zod.def.shape[o];return r?r(e,o):e}):fn(e,o,r?r(n.value,o):n.value))}}function hn(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function mn(e){return JSON.stringify(e)}var yn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function vn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var gn=an(()=>{if(rr.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function wn(e){if(!1===vn(e))return!1;let t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;let n=t.prototype;return!1!==vn(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function _n(e){return wn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var bn=new Set(["string","number","symbol"]);function kn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $n(e,t,n){let r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function zn(e){let t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function Sn(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}var On={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},En={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function xn(e,t){let n=cn(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function In(e,t){let n={};return pn(n,e,Reflect.ownKeys(cn(e))),function(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?dn(e,n,()=>t[n]):fn(e,n,r.value))}}(n,t),n}function An(e,t,n,r="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let o=n?new Set(xn(t,n)):void 0,a={};return pn(a,t,Reflect.ownKeys(cn(t)),e&&((t,n)=>o&&!o.has(n)?t:new e({type:"optional",innerType:t}))),$n(t,hn(t._zod.def,{shape:a,checks:[]}))}function Pn(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Nn(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function jn(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Tn(e){return"string"==typeof e?e:e?.message}function Zn(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function Fn(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has("$ZodType")&&(i.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:Tn(e.inst?._zod.def?.error?.(e))??Tn(o?.(e))??Tn(t?.error?.(e))??Tn(n.customError?.(e))??Tn(n.localeError?.(e))??"Invalid input",s={};for(let t of Object.keys(e))"inst"!==t&&"schema"!==t&&"continue"!==t&&"input"!==t&&"__proto__"!==t&&(s[t]=e[t]);return s.path??(s.path=[]),s.message=a,t?.reportInput&&(s.input=e.input),s}var Dn=/[\uD800-\uDBFF]/;function Rn(e){let t=e.length;if(!Dn.test(e))return t;let n=t;for(let r=0;r<t-1;r++)55296==(64512&e.charCodeAt(r))&&56320==(64512&e.charCodeAt(r+1))&&(n--,r++);return n}function Mn(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Cn(...e){let[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function Un(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Jn(e,t,n){return Un(e,t,n,!1)}function Ln(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Un(this,n,r(this))},set(e){Un(this,n,e)}})}return t}function Bn(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:Un(this,t,n.bind(this))},set(e){Un(this,t,e)}})}var Wn,Kn=!1,Vn={configurable:!0,get(){Kn=!0}};function Gn(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Wn!==e._zod?Wn=void 0:(Wn=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Vn);let e=Kn;Kn=!1;try{let r=n(this);return Kn?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Kn=Kn||e,r}catch(n){throw delete this[t],Kn=Kn||e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function qn(e,t,n,r){let i=function(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var Hn;function Yn(e){let t=()=>e;return t["~constantCatch"]=!0,t}var Xn={value:void 0,enumerable:!1},Qn="captureStackTrace"in Error?Error:null;function er(e,t,n,r){function i(e){this.def=e,this.constr=c,this.traits=new Set}i.prototype={};let o=n,a=o&&new WeakSet;function s(n,r){if(n._zod){if(n._zod.traits.has(e))return}else{Xn.value=new i(r);try{Object.defineProperty(n,"_zod",Xn)}finally{Xn.value=void 0}}if(n._zod.traits.add(e),t(n,r),a){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;a.has(i)||(a.add(i),function(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):Bn(e,n,r.value)}}(i,o))}let s=c.prototype;for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&(e in n||(n[e]=s[e].bind(n)))}let u=r?.Parent??Object;class l extends u{}function c(e){let t=r?.Parent?function(e){let t=Qn;if(t){let n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return Qn=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}(l):this;s(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(l,"name",{value:e}),Object.defineProperty(c,"init",{value:s}),Object.defineProperty(c,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(c,"name",{value:e}),c}class tr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class nr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Hn=globalThis).__zod_globalConfig??(Hn.__zod_globalConfig={});var rr=globalThis.__zod_globalConfig;function ir(e){return e&&Object.assign(rr,e),rr}var or={get:function(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,rn,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},ar={value:void 0,enumerable:!1},sr=new WeakSet([Object.prototype,Error.prototype]),ur=(e,t)=>{e.name="$ZodError",ar.value=t,Object.defineProperty(e,"issues",ar),ar.value=void 0,Object.defineProperty(e,"message",or);let n=Object.getPrototypeOf(e);sr.has(n)||(sr.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},lr=er("$ZodError",ur);er("$ZodError",ur,void 0,{Parent:Error});function cr(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||("__proto__"===t?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function dr(e,t){return{callee:t?.callee??e,Err:t?.Err}}var fr=e=>{let t=(n,r,i,o)=>{let a=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},a);if(s instanceof Promise)throw new tr;if(s.issues.length){let n=new(o?.Err??e)(s.issues.map(e=>Fn(e,a,ir())));throw yn(n,o?.callee??t),n}return s.value};return t},pr=e=>{let t=async(n,r,i,o)=>{let a=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new(o?.Err??e)(s.issues.map(e=>Fn(e,a,ir())));throw yn(n,o?.callee??t),n}return s.value};return t},hr=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new tr;return o.issues.length?mr(e,o.issues,i):{success:!0,data:o.value}};function mr(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>Fn(e,n,ir()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var yr=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?mr(e,o.issues,i):{success:!0,data:o.value}},vr=Symbol.for("zod.compile.invalid"),gr=Symbol.for("zod.compile.fallback"),wr=(e,t,n)=>{let r=e._zod.bag.validator;if(void 0!==r){if(r(t)!==vr)return!0;if(!0===r.definite&&void 0===n)return!1}return function(e,t,n){let r,i=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun;o?(i[gr]=!0,r=o({value:t,issues:[]},i)):r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)throw new tr;return 0===r.issues.length}(e,t,n)};var _r=/^[cC][0-9a-z]{6,}$/,br=/^[0-9a-z]+$/,kr=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,$r=/^[0-9a-vA-V]{20}$/,zr=/^[A-Za-z0-9]{27}$/,Sr=/^[a-zA-Z0-9_-]{21}$/;var Or=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Er=/^([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})$/,xr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,Ir=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Ar=/^(?:(?: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])$/,Pr=/^(([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}|:))$/,Nr=/^((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])$/,jr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Tr=/^https?$/,Zr=/^\+[1-9]\d{6,14}$/,Fr="(?:(?:\\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 Dr=new RegExp(`^${Fr}$`);function Rr(e){return"number"==typeof e.precision?-1===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d":0===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}var Mr=/^[\s\S]{0,}$/,Cr=/^-?\d+(?:\.\d+)?$/,Ur=/^null$/i,Jr=/^[^A-Z]*$/,Lr=/^[^a-z]*$/,Br=er("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Wr=e=>{let t=e.value;return!(n=t,null==n||void 0===t.length);var n},Kr={number:"number",bigint:"bigint",object:"date"},Vr=er("$ZodCheckLessThan",(e,t)=>{Br.init(e,t);let n=Kr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Kr[typeof r.value]??n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Gr=er("$ZodCheckGreaterThan",(e,t)=>{Br.init(e,t);let n=Kr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Kr[typeof r.value]??n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),qr=er("$ZodCheckMultipleOf",(e,t)=>{Br.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?t.value===BigInt(0)||n.value%t.value!==BigInt(0):0!==function(e,t){let n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Hr=er("$ZodCheckNumberFormat",(e,t)=>{Br.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=On[t.format];e._zod.check=a=>{let s=a.value;if(n){if(!Number.isInteger(s))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}s<i&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Yr=er("$ZodCheckMaxLength",(e,t)=>{var n;Br.init(e,t),(n=e._zod.def).when??(n.when=Wr),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>t.maximum?Rn(r):i)<=t.maximum)return;let o=Mn(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Xr=er("$ZodCheckMinLength",(e,t)=>{var n;Br.init(e,t),(n=e._zod.def).when??(n.when=Wr),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>=t.minimum&&i<2*t.minimum?Rn(r):i)>=t.minimum)return;let o=Mn(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Qr=er("$ZodCheckLengthEquals",(e,t)=>{var n;Br.init(e,t),(n=e._zod.def).when??(n.when=Wr),e._zod.check=n=>{let r=n.value,i=r.length,o="string"==typeof r&&i>=t.length&&i<=2*t.length?Rn(r):i;if(o===t.length)return;let a=Mn(r),s=o>t.length;n.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ei=er("$ZodCheckStringFormat",(e,t)=>{var n,r;Br.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),ti=er("$ZodCheckRegex",(e,t)=>{ei.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ni=er("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Jr),ei.init(e,t)}),ri=er("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lr),ei.init(e,t)}),ii=er("$ZodCheckIncludes",(e,t)=>{Br.init(e,t);let n=kn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),oi=er("$ZodCheckStartsWith",(e,t)=>{Br.init(e,t);let n=new RegExp(`^${kn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),ai=er("$ZodCheckEndsWith",(e,t)=>{Br.init(e,t);let n=new RegExp(`.*${kn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),si=er("$ZodCheckOverwrite",(e,t)=>{Br.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class ui{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});let t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {\n${t.join("\n")}\n};`)(...Object.values(this.closed))}}var li={major:4,minor:6,patch:5},ci=er("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=li;let r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(0===i.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i,o=Pn(t);for(let a of n){if(a._zod.def.when){if(Nn(t))continue;if(!a._zod.def.when(t))continue}else if(o)continue;let n=t.issues.length,s=a._zod.check(t);if(s instanceof Promise&&!1===r?.async)throw new tr;if(i||s instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(Zn(t.issues,n,e),o||(o=Pn(t,n)))});else{if(t.issues.length===n)continue;Zn(t.issues,n,e),o||(o=Pn(t,n))}}return i?i.then(()=>t):t},n=(n,r,o)=>{if(Pn(n))return n.aborted=!0,n;let a=t(r,i,o);if(a instanceof Promise){if(!1===o.async)throw new tr;return a.then(t=>e._zod.parse(t,o))}return e._zod.parse(a,o)};e._zod.run=(r,o)=>{if(o.skipChecks)return e._zod.parse(r,o);if("backward"===o.direction){let t=e._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,o)):n(t,r,o)}let a=e._zod.parse(r,o);if(a instanceof Promise){if(!1===o.async)throw new tr;return a.then(e=>t(e,i,o))}return t(a,i,o)}}},{get"~standard"(){return Jn(this,"~standard",fi(this))},set"~standard"(e){Un(this,"~standard",e)}}),di=(e,t)=>e.issues.length?{issues:e.issues.map(e=>Fn(e,t,ir()))}:{value:e.value};function fi(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return di(r,n)}catch(e){}return async function(e,t){let n={async:!0};return di(await e._zod.run({value:t,issues:[]},n),n)}(e,t)},vendor:"zod",version:1}}var pi=er("$ZodString",(e,t)=>{ci.init(e,t),e._zod.pattern=t.pattern??Mr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),hi=er("$ZodStringFormat",(e,t)=>{ei.init(e,t),pi.init(e,t)}),mi=er("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Er),hi.init(e,t)}),yi=er("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=xr(e))}else t.pattern??(t.pattern=xr());hi.init(e,t)}),vi=er("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ir),hi.init(e,t)});function gi(e){try{return typeof URL<"u"&&"function"==typeof URL.canParse?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function wi(e,t){return"normalize"in t||"hostname"in t||"protocol"in t?function(e,t){if(!t.normalize&&t.protocol?.source===Tr.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<"u"){let t=URL;if("function"==typeof t.parse)return t.parse(e)??2}return new URL(e)}catch{return 2}}(e,t):gi(e)||2}var _i=/[\t\n\r]/g;function bi(e){return e.replace(_i,"")}var ki=er("$ZodURL",(e,t)=>{hi.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=wi(r,t);return 1===i?void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort}):2===i?void n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort}):!0===i?void(n.value=bi(r)):(t.hostname&&!function(e,t){return t.lastIndex=0,t.test(e.hostname)}(i,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!function(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}(i,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),void(n.value=t.normalize?i.href:bi(r)))}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),$i=er("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),hi.init(e,t)}),zi=er("$ZodNanoID",(e,t)=>{if(void 0!==t.length&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);var n;t.pattern??(t.pattern=void 0===t.length?Sr:(n=t.length,new RegExp(`^[a-zA-Z0-9_-]{${n}}$`))),hi.init(e,t)}),Si=er("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=_r),hi.init(e,t)}),Oi=er("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=br),hi.init(e,t)}),Ei=er("$ZodULID",(e,t)=>{t.pattern??(t.pattern=kr),hi.init(e,t)}),xi=er("$ZodXID",(e,t)=>{t.pattern??(t.pattern=$r),hi.init(e,t)}),Ii=er("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=zr),hi.init(e,t)}),Ai=er("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Rr({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Rr({precision:e.precision})}`:n;return new RegExp(`^${Fr}T(?:${r})$`)}(t)),hi.init(e,t)}),Pi=er("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Dr),hi.init(e,t)}),Ni=er("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Rr(t)}$`)),hi.init(e,t)}),ji=er("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Or),hi.init(e,t)}),Ti=er("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ar),hi.init(e,t)}),Zi=/^[0-9a-fA-F:.]+$/;function Fi(e){return!!Zi.test(e)&&gi(`http://[${e}]`)}var Di=er("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Pr),hi.init(e,t),e._zod.check=n=>{Fi(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),Ri=er("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Nr),hi.init(e,t)});var Mi=er("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=jr),hi.init(e,t),e._zod.check=n=>{(function(e){let t=e.split("/");if(2!==t.length)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`===r&&!(i<0||i>128)&&Fi(n)})(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Ci(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Ui=/^[0-9a-zA-Z+/]*={0,2}$/,Ji=er("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ui),hi.init(e,t),e._zod.check=n=>{Ci(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Li=/^[A-Za-z0-9_-]*$/;var Bi=er("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Li),hi.init(e,t),e._zod.check=n=>{(function(e){if(!Li.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Ci(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Wi=er("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Zr),hi.init(e,t)});var Ki=er("$ZodJWT",(e,t)=>{hi.init(e,t),e._zod.check=n=>{(function(e,t=null){try{let n=e.split(".");if(3!==n.length)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Vi=er("$ZodNumber",(e,t)=>{ci.init(e,t),e._zod.pattern=Cr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}let i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Gi=er("$ZodNumberFormat",(e,t)=>{Hr.init(e,t),Vi.init(e,t)}),qi=er("$ZodNull",(e,t)=>{ci.init(e,t),e._zod.pattern=Ur,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}}),Hi=er("$ZodUnknown",(e,t)=>{ci.init(e,t),e._zod.parse=e=>e}),Yi=er("$ZodNever",(e,t)=>{ci.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Xi(e,t,n){e.issues.length&&t.issues.push(...jn(n,e.issues)),t.value[n]=e.value}var Qi=er("$ZodArray",(e,t)=>{ci.init(e,t);let n=rr.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);let a=[],s=i?.abortEarly;for(let e=0;e<o.length;e++){let n=o[e],u=t.element._zod.run({value:n,issues:[]},i);if(u instanceof Promise)a.push(u.then(t=>Xi(t,r,e)));else if(Xi(u,r,e),s&&0!==u.issues.length&&Pn(u))break}return a.length?Promise.all(a).then(()=>r):r}});function eo(e,t,n,r,i,o){let a=n in r,s="optional"===o;if(a||!s||"optional"!==i){if(e.issues.length){if(void 0!==i&&s&&!a)return;t.issues.push(...jn(n,e.issues))}a||void 0!==i?void 0===e.value?(a||"defaulted"===i&&!s)&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}}var to=[];function no(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:to,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let o=(a=e.shape,Object.keys(a).filter(e=>void 0!==a[e]._zod.optin&&"optional"===a[e]._zod.optout));var a;return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function ro(e,t,n,r,i,o,a){let s=[],u=i.keySet,l=i.catchall._zod,c=l.def.type,{optin:d,optout:f}=l,p=0;for(let i in t){if(a&&n.issues.length!==p){if(Pn(n,p))break;p=n.issues.length}if(u.has(i))continue;if("__proto__"===i){"never"===c&&s.push(i);continue}if("never"===c){s.push(i);continue}let o=l.run({value:t[i],issues:[]},r);o instanceof Promise?e.push(o.then(e=>eo(e,n,i,t,d,f))):eo(o,n,i,t,d,f)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var io=er("$ZodObject",(e,t)=>{ci.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=an(()=>no(t));Gn(e,"propValues",e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||un(n,e,new Set);for(let t of r.values)n[e].add(t);void 0!==r.optin&&n[e].add(void 0)}}return n});let o,a=vn,s=t.catchall,u=rr.memoizer;u?.attach(e),e._zod.parse=(t,n)=>{o??(o=i.value);let r=t.value;if(!a(r))return t.issues.push({expected:"object",code:"invalid_type",input:r,inst:e}),t;t.value=u?u.alloc(e,t,{},n):{};let l=[],c=o.shape,d=n?.abortEarly,f=t.issues.length;for(let e of o.allKeys){if(d&&t.issues.length!==f){if(Pn(t,f))break;f=t.issues.length}if("__proto__"===e)continue;let i=c[e],o=i._zod.optin,a=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>eo(n,t,e,r,o,a))):eo(s,t,e,r,o,a)}return s?ro(l,r,t,n,i.value,e,!0===d):l.length?Promise.all(l).then(()=>t):t}}),oo=er("$ZodObjectJIT",(e,t)=>{io.init(e,t);let n,r,i=e._zod.parse,o=an(()=>no(t)),a=rr.memoizer,s=vn,u=!rr.jitless,l=u&&gn.value,c=t.catchall;e._zod.parse=(d,f)=>{r??(r=o.value);let p=d.value;return s(p)?u&&l&&!1===f?.async&&!0!==f.jitless?(n||(n=(t=>{let n=o.value,r=n.symbolKeys,i=new ui(["payload","ctx"],{shape:t,inst:e,memo:a,syms:r}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,u=(e,t)=>`\n let ${e}_ab = false;\n for (let i = 0; i < ${e}.issues.length; i++) {\n const iss = ${e}.issues[i];\n iss.path = iss.path ? [${t}, ...iss.path] : [${t}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${e}_ab = true;\n }\n if (${e}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;i.write("const input = payload.value;");let l=Object.create(null),c=0;for(let e of n.allKeys)l[e]="key_"+c++;i.write(a?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let e of n.allKeys){if("__proto__"===e)continue;let n=l[e],o="symbol"==typeof e?`syms[${r.indexOf(e)}]`:mn(e),a=`${o} in input`,c=t[e],d=c?._zod?.optin,f=void 0!==d,p="optional"===c?._zod?.optout;if(i.write(`const ${n} = ${s(o)};`),f&&p){let e="optional"===d?`${n}_present`:`${n}.value !== undefined || ${n}_present`;i.write(`\n const ${n}_present = ${a};\n if (!${n}.issues.length || ${n}_present) {\n if (${n}.issues.length) {${u(n,o)}\n }\n\n if (${e}) {\n newResult[${o}] = ${n}.value;\n }\n }\n\n `)}else f?(i.write(`\n if (${n}.issues.length) {${u(n,o)}\n }\n `),"defaulted"===d?i.write(`newResult[${o}] = ${n}.value;`):i.write(`\n if (${n}.value !== undefined || ${a}) {\n newResult[${o}] = ${n}.value;\n }\n `)):i.write(`\n const ${n}_present = ${a};\n if (${n}.issues.length) {${u(n,o)}\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${o}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${n}_present) {\n newResult[${o}] = ${n}.value;\n }\n\n `)}return i.write("payload.value = newResult;"),i.write("return payload;"),i.compile()})(t.shape)),d=n(d,f),c?ro([],p,d,f,r,e,!0===f?.abortEarly):d):i(d,f):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d)}});function ao(e,t,n,r){for(let n of e)if(0===n.issues.length)return t.value=n.value,t;let i=e.filter(e=>!Pn(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Fn(e,r,ir())))}),t)}var so=er("$ZodUnion",(e,t)=>{ci.init(e,t),Gn(e,"optin",e=>e.def.options.some(e=>"defaulted"===e._zod.optin)?"defaulted":e.def.options.some(e=>void 0!==e._zod.optin)?"optional":void 0),Gn(e,"optout",e=>e.def.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Gn(e,"values",e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Gn(e,"pattern",e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return new RegExp(`^(${t.map(e=>sn(e.source)).join("|")})$`)}});let n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,a=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)a.push(t),o=!0;else{if(0===t.issues.length)return t;a.push(t)}}return o?Promise.all(a).then(t=>ao(t,r,e,i)):ao(a,r,e,i)}}),uo=er("$ZodIntersection",(e,t)=>{ci.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>co(e,t,n)):co(e,i,o)}});function lo(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(wn(e)&&wn(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(let n of r){if("__proto__"===n)continue;let r=lo(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=lo(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function co(e,t,n){let r,i=new Map,o=new Map,a=(e,t)=>{let n;if("unrecognized_keys"!==e.code||e.path?.length){if("invalid_key"!==e.code||"record"!==e.origin||1!==e.path?.length)return!1;{let t=String(e.path[0]);o.has(t)||o.set(t,e),n=[t]}}else r??(r=e),n=e.keys;for(let e of n)i.has(e)||i.set(e,{}),i.get(e)[t]=!0;return!0};for(let n of t.issues)a(n,"l")||e.issues.push(n);for(let t of n.issues)a(t,"r")||e.issues.push(t);let s=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=r?s.filter(e=>r.keys.includes(e)):[];t.length&&e.issues.push({...r,keys:t});for(let n of s)!t.includes(n)&&o.has(n)&&e.issues.push(o.get(n))}let u=lo(t.value,n.value);if(!u.valid){if(Pn(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}var fo=er("$ZodEnum",(e,t)=>{ci.init(e,t);let n=tn(t.entries),r=new Set(n);e._zod.values=r,Gn(e,"pattern",e=>{let t=tn(e.def.entries).filter(e=>bn.has(typeof e));return new RegExp(t.length?`^(${t.map(e=>kn(e.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(t,i)=>{let o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),po=er("$ZodLiteral",(e,t)=>{ci.init(e,t);let n=new Set(t.values);e._zod.values=n,Gn(e,"pattern",e=>{let t=e.def.values;return new RegExp(t.length?`^(${t.map(e=>"string"==typeof e?kn(e):e?kn(e.toString()):String(e)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,i)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),ho=er("$ZodTransform",(e,t)=>{ci.init(e,t),e._zod.optin="optional",rr.memoizer?.guard(e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new nr(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new tr;return n.value=i,n}});function mo(e,t){return e.value=t.issues.length?void 0:t.value,e}var yo=er("$ZodOptional",(e,t)=>{ci.init(e,t),Gn(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",Gn(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Gn(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${sn(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(void 0===e.value){if("defaulted"!==t.innerType._zod.optin)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>mo(e,t)):mo(e,r)}return t.innerType._zod.run(e,n)}}),vo=er("$ZodExactOptional",(e,t)=>{yo.init(e,t),Gn(e,"values",e=>e.def.innerType._zod.values),Gn(e,"pattern",e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),go=er("$ZodNullable",(e,t)=>{ci.init(e,t),Gn(e,"optin",e=>e.def.innerType._zod.optin),Gn(e,"optout",e=>e.def.innerType._zod.optout),Gn(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${sn(t.source)}|null)$`):void 0}),Gn(e,"values",e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),wo=er("$ZodDefault",(e,t)=>{ci.init(e,t),e._zod.optin="defaulted",Gn(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>_o(e,t)):_o(r,t)}});function _o(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var bo=er("$ZodPrefault",(e,t)=>{ci.init(e,t),e._zod.optin="defaulted",Gn(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ko=er("$ZodNonOptional",(e,t)=>{ci.init(e,t),Gn(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>$o(t,e)):$o(i,e)}});function $o(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function zo(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Fn(e,r,ir()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var So=er("$ZodCatch",(e,t)=>{ci.init(e,t),Gn(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),Gn(e,"optout",e=>e.def.innerType._zod.optout),Gn(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>zo(e,r,t,n)):zo(e,r,t,n)}}),Oo=er("$ZodPipe",(e,t)=>{ci.init(e,t),Gn(e,"values",e=>e.def.in._zod.values),Gn(e,"optin",e=>e.def.in._zod.optin),Gn(e,"optout",e=>e.def.out._zod.optout),Gn(e,"propValues",e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Eo(e,t.in,n)):Eo(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Eo(e,t.out,n)):Eo(r,t.out,n)}});function Eo(e,t,n){return e.issues.some(e=>"unrecognized_keys"!==e.code)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var xo=er("$ZodReadonly",(e,t)=>{ci.init(e,t),Gn(e,"propValues",e=>e.def.innerType._zod.propValues),Gn(e,"values",e=>e.def.innerType._zod.values),Gn(e,"optin",e=>e.def.innerType?._zod?.optin),Gn(e,"optout",e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Io):Io(r)}});function Io(e){return e.memo||(e.value=Object.freeze(e.value)),e}var Ao=er("$ZodCustom",(e,t)=>{Br.init(e,t),ci.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Po(t,n,r,e));Po(i,n,r,e)}});function Po(e,t,n,r){if(!e){let e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Cn(e))}}class No extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}var jo="~memo",To=[];function Zo(e){return null!==e&&"object"==typeof e}function Fo(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var Do=new WeakMap;function Ro(e,t,n){let r=Do.get(e);if(void 0!==r)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,o=e=>{if(2!==i&&e?._zod){let r=Ro(e,t,n);r>i&&(i=r)}},a=e=>{e>i&&(i=e)},s=e._zod.def;switch(s.type){case"object":{let e=ln(s);a(e?((e,r)=>{let i=0;for(let o of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,o);if(r&&!a.enumerable)continue;let s=a.get?1:a.value?._zod?Ro(a.value,t,n):0;s>i&&(i=s)}return i})(e,!0):1),o(s.catchall);break}case"array":o(s.element);break;case"tuple":for(let e of s.items)o(e);o(s.rest);break;case"record":case"map":o(s.keyType),o(s.valueType);break;case"set":o(s.valueType);break;case"union":for(let e of s.options)o(e);break;case"intersection":o(s.left),o(s.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(s.innerType);break;case"pipe":o(s.in),o(s.out);break;case"function":o(s.input),o(s.output);break;case"lazy":{let r=s._cachedInner??(n?e._zod.innerType:void 0);a(r?Ro(r,t,!1):1);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let e in s){let t=Object.getOwnPropertyDescriptor(s,e);if(!t||t.get)continue;let n=t.value;if(n&&"object"==typeof n)if(n._zod)o(n);else if(Array.isArray(n))for(let e of n)o(e)}}return t.delete(e),function(e,t){1!==t&&Do.set(e,2===t);return t}(e,i)}var Mo,Co=[],Uo={alloc(e,t,n){let r=Mo;if(!r)return n;Mo=void 0;let i={value:n,issues:null};return r.set(t.value,i),Co.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if("backward"!==n.direction&&function(e,t){let n=e[jo]?.backEdges;return void 0!==n&&Zo(t)&&n.has(t)}(n,e.value))throw new No;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i,o=!1;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,a=(s,u)=>{if(void 0===n){let r=Ro(e,new Set,!1);if(0===r)return e._zod.parse=t,e._zod.run===a&&(e._zod.run=t),t(s,u);2===r||o?n=!0:o=!0}let l=s.value;if(!Zo(l))return t(s,u);let c,d=u[jo];d||(d={buckets:new WeakMap,backEdges:void 0},u[jo]=d),r===u?c=i:(c=function(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}(d,e),r=u,i=c);let f=c.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Fo(f.issues)):(s.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(f.value)),s;Mo=c;let p=Co.length,h=t(s,u);Mo=void 0;let m=Co.length>p?Co.pop():void 0;return h instanceof Promise?h.then(e=>(m&&(m.issues=e.issues.length?Fo(e.issues):To),e)):(m&&(m.issues=h.issues.length?Fo(h.issues):To),h)};e._zod.parse=a,e._zod.run===t&&(e._zod.run=a)})}};var Jo,Lo=()=>{let e={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 t(t){return e[t]??null}let n={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",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(e,t){return"number"!==e||"number"!=typeof t||Number.isFinite(t)?r[e]??e:String(t)}return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${i(e.expected)}, received ${i(function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(null===e)return"null";if(Array.isArray(e))return"array";let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return t}(e.input),e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${Sn(e.values[0])}`:`Invalid option: expected one of ${nn(e.values,"|")}`;case"too_big":{let n=e.exact?"exactly ":e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{let n=e.exact?"exactly ":e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${nn(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(" | ")}`:!1===e.inclusive?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`;default:return"Invalid input"}}};class Bo{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(Jo=globalThis).__zod_globalRegistry??(Jo.__zod_globalRegistry=new Bo);var Wo=globalThis.__zod_globalRegistry;function Ko(e){return e.checks&&(e.checks=[...e.checks]),e}function Vo(e,t){return new Vr({check:"less_than",...zn(t),value:e,inclusive:!1})}function Go(e,t){return new Vr({check:"less_than",...zn(t),value:e,inclusive:!0})}function qo(e,t){return new Gr({check:"greater_than",...zn(t),value:e,inclusive:!1})}function Ho(e,t){return new Gr({check:"greater_than",...zn(t),value:e,inclusive:!0})}function Yo(e,t){return new qr({check:"multiple_of",...zn(t),value:e})}function Xo(e,t){return new Yr({check:"max_length",...zn(t),maximum:e})}function Qo(e,t){return new Xr({check:"min_length",...zn(t),minimum:e})}function ea(e,t){return new Qr({check:"length_equals",...zn(t),length:e})}function ta(e){return new si({check:"overwrite",tx:e})}function na(e,t){let n=function(e,t){let n=new Br({check:"custom",...zn(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(Cn(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),"input"in r||(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(Cn(r))}},e(t.value,t)),t);return n}function ra(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&un(e,t,n[t]);return e}function ia(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Wo,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function oa(e,t,n,r,i){let o="function"==typeof t.unrepresentable?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if("any"===o)return!1;if(void 0===o||"throw"===o)throw Error(i);return Object.assign(n,o),!0}function aa(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{let n=a.schema,o=t.processors[i.type];if(!o)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,n,r)}let o=e._zod.parent;o&&(a.ref||(a.ref=o),aa(o,t,r),t.seen.get(o).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&ra(a.schema,u),"input"===t.io&&ya(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function sa(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ua(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{if(t[1].schema.$ref)return;let r=t[1],{ref:i,defId:o}=(t=>{let r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${r}/${sa(o)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:"#"};let o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+sa(o)}})(t);r.def={...r.schema},o&&(r.defId=o);let a=r.schema;for(let e in a)delete a[e];a.$ref=i};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t!==n[0]){if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){i(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&"ref"===e.reused)&&i(n)}else i(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function la(e){let t=e.anyOf;if(!Array.isArray(t)||0===t.length||void 0!==e.type)return;let n=[];for(let e of t){if(!e||"object"!=typeof e)return;la(e);let t=Object.keys(e);if(1!==t.length||"type"!==t[0])return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if("string"!=typeof e)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=1===n.length?n[0]:n}var ca=new Set(["type","properties","required","additionalProperties"]),da=["oneOf","anyOf"];function fa(e){let t=e.additionalProperties;return void 0===t||!1===t||"object"!=typeof t||null===t?null:Object.keys(t).length?t:null}function pa(e){let t=[];for(let n of e){if("object"!=typeof n||"object"!==n.type)return null;for(let e in n)if(!ca.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??fa(n);null!=t&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}un(n,r,1===e.length?e[0]:pa(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:"object",properties:n};if(r.size&&(i.required=[...r]),t.every(e=>!1===e.additionalProperties))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=fa(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}1===e.length?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ha(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ca)if(t in e)return;let n=t.filter(e=>da.some(t=>Array.isArray(e[t]))),r=null;if(n.length){let e=n[0],i=da.find(t=>Array.isArray(e[t]));if(1!==Object.keys(e).length)return;let o=t.filter(t=>t!==e),a=e[i].map(e=>pa([...o,e]));if(a.some(e=>!e))return;r={[i]:a}}else r=pa(t);r&&(delete e.allOf,ra(e,r))}function ma(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=t=>{let n=e.seen.get(t);if(null===n.ref)return;let i=n.def??n.schema,o={...i},a=n.ref;if(n.ref=null,a){r(a);let n=e.seen.get(a),s=n.schema;if(!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?ra(i,s):(i.allOf=i.allOf??[],i.allOf.push(s)),ra(i,o),t._zod.parent===a)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(s.$ref&&n.def)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==a){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if("openapi-3.0"!==e.target)for(let t of e.seen.entries())la(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ha(e)}}let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}ra(i,n.defId?n.schema:n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;void 0!==o&&i.id===o&&delete i.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,un(a,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:va(t,"input",e.processors),output:va(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw Error("Error converting schema to JSON.")}}function ya(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return ya(r.element,n);if("set"===r.type)return ya(r.valueType,n);if("lazy"===r.type)return ya(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type||"catch"===r.type)return ya(r.innerType,n);if("intersection"===r.type)return ya(r.left,n)||ya(r.right,n);if("record"===r.type||"map"===r.type)return ya(r.keyType,n)||ya(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(ya(r.in,n)||ya(r.out,n));if("object"===r.type){for(let e in r.shape)if(ya(r.shape[e],n))return!0;return!1}if("union"===r.type){for(let e of r.options)if(ya(e,n))return!0;return!1}if("tuple"===r.type){for(let e of r.items)if(ya(e,n))return!0;return!(!r.rest||!ya(r.rest,n))}return!1}var va=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r??{},a=ia({...i??{},target:o,io:t,processors:n});return aa(e,a),ua(a,e),ma(a,e)},ga=(e,t,n)=>{(void 0===e[t]||n>e[t])&&(e[t]=n)},wa=(e,t,n)=>{(void 0===e[t]||n<e[t])&&(e[t]=n)},_a=(e,t)=>{ga(e,"minimum",t),wa(e,"maximum",t)},ba=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},ka=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},$a=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},za=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Sa=(e,t)=>ga(e,"minimum",t.minimum),Oa=(e,t)=>wa(e,"maximum",t.maximum),Ea=e=>(t,n)=>{za(t,n.format);let[r,i]=e[n.format];ga(t,"minimum",r),wa(t,"maximum",i)},xa={greater_than:(e,t)=>ga(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>wa(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>ba(e,t.value),number_format:Ea(On),bigint_format:Ea(En),min_length:Sa,max_length:Oa,length_equals:(e,t)=>_a(e,t.length),min_size:Sa,max_size:Oa,size_equals:(e,t)=>_a(e,t.size),string_format:(e,t)=>{za(e,t.format),t.pattern&&ka(e,t.pattern),"base64"!==t.format&&"base64url"!==t.format||(e.contentEncoding=t.format),(t.local||-1===t.precision)&&(e.laxFormat=!0)},mime_type:(e,t)=>$a(e,t.mime)};function Ia(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let e of r)xa[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;void 0!==i.minimum&&ga(t,"minimum",i.minimum),void 0!==i.exclusiveMinimum&&ga(t,"exclusiveMinimum",i.exclusiveMinimum),void 0!==i.maximum&&wa(t,"maximum",i.maximum),void 0!==i.exclusiveMaximum&&wa(t,"exclusiveMaximum",i.exclusiveMaximum),void 0!==i.multipleOf&&ba(t,i.multipleOf),void 0!==i.format&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&$a(t,i.mime);for(let e of i.patterns??[])ka(t,e);return t}var Aa={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Pa=new Map([[Ui,/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/],[Li,/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/]]),Na=e=>Pa.get(e)??e;function ja(e){let t=e._zod.def;return"pipe"===t.type&&t.in._zod.traits.has("$ZodTransform")?ja(t.out):"catch"===t.type?ja(t.innerType):e._zod.optin}var Ta=Symbol();function Za(e,t,n,r,i){let o=!1,a=JSON.stringify(e,(e,t)=>"bigint"!=typeof t?t:(o=!0,null));return o?(oa(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),Ta):JSON.parse(a)}var Fa=(e,t,n,r)=>{let i=e._zod.def;aa(i.innerType,t,r),t.seen.get(e).ref=i.innerType},Da=new WeakSet([Object.prototype,Error.prototype]);function Ra(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Ma,Ca=er("ZodError",(e,t)=>{lr.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);Da.has(n)||(Da.add(n),Ra(n,"format",e=>t=>function(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>r({issues:e},[...i,...o.path]));else if("invalid_key"===o.code)r({issues:o.issues},[...i,...o.path]);else if("invalid_element"===o.code)r({issues:o.issues},[...i,...o.path]);else{let e=[...i,...o.path];if(0===e.length)n._errors.push(t(o));else{let r=n,i=0;for(;i<e.length;){let n=e[i],a=i===e.length-1;if("_errors"===n){a&&r._errors.push(t(o)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];a&&s._errors.push(t(o)),r=s,i++}}}};return r(e),n}(e,t)),Ra(n,"flatten",e=>t=>function(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?cr(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)),Ra(n,"addIssue",e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,rn,2)}),Ra(n,"addIssues",e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,rn,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),Ua=fr(Ca),Ja=pr(Ca),La=hr(Ca),Ba=yr(Ca),Wa=(e=>{let t=fr(e),n=(e,r,i,o)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return t(e,r,a,dr(n,o))};return n})(Ca),Ka=(e=>{let t=fr(e),n=(e,r,i,o)=>t(e,r,i,dr(n,o));return n})(Ca),Va=(e=>{let t=pr(e),n=async(e,r,i,o)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return await t(e,r,a,dr(n,o))};return n})(Ca),Ga=(e=>{let t=pr(e),n=async(e,r,i,o)=>await t(e,r,i,dr(n,o));return n})(Ca),qa=(Ma=Ca,(e,t,n)=>{let r=n?{...n,direction:"backward"}:{direction:"backward"};return hr(Ma)(e,t,r)}),Ha=(e=>(t,n,r)=>hr(e)(t,n,r))(Ca),Ya=(e=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return yr(e)(t,n,i)})(Ca),Xa=(e=>async(t,n,r)=>yr(e)(t,n,r))(Ca);function Qa(){rr.localeError||ir({localeError:Lo()})}function es(){rr.memoizer||ir({memoizer:Uo})}var ts=er("ZodType",(e,t)=>(Qa(),ci.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(hn(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return $n(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...zn(n)})}(iu,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return na(e,t)}(e,t))},overwrite(e){return this.check(ta(e))},optional(){return Vs(this)},exactOptional(){return new Gs({type:"optional",innerType:this})},nullable(){return Hs(this)},nullish(){return Vs(Hs(this))},nonoptional(e){return function(e,t){return new Qs({type:"nonoptional",innerType:e,...zn(t)})}(this,e)},array(){return function(e,t,n){return new e({type:"array",element:t,...zn(n)})}(Ds,this,e);var e},or(e){return new Cs({type:"union",options:[this,e],...zn(t)});var t},and(e){return new Us({type:"intersection",left:this,right:e})},transform(e){return nu(this,new Ws({type:"transform",transform:e}))},default(e){return t=e,new Ys({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():_n(t)}});var t},prefault(e){return t=e,new Xs({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():_n(t)}});var t},catch(e){return new eu({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:Yn(t)});var t},pipe(e){return nu(this,e)},readonly(){return new ru({type:"readonly",innerType:this})},describe(e){let t=this.clone();return Wo.add(t,{description:e}),t},meta(...e){if(0===e.length)return Wo.get(this);let t=this.clone();return Wo.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return 0===t.length?e(this):e(this,...t)},get"~standard"(){return Jn(this,"~standard",{...fi(this),jsonSchema:{input:va(this,"input"),output:va(this,"output")}})},set"~standard"(e){Un(this,"~standard",e)},parse:function e(t,n){return Ua(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ja(this,t,n,{callee:e})},safeParse(e,t){return La(this,e,t)},async safeParseAsync(e,t){return Ba(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Un(this,"spa",e)},validate(e,t){return wr(this,e,t)},validateAsync(e,t){return(async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),0===i.issues.length})(this,e,t)},encode:function e(t,n){return Wa(this,t,n,{callee:e})},decode:function e(t,n){return Ka(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Va(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Ga(this,t,n,{callee:e})},safeEncode(e,t){return qa(this,e,t)},safeDecode(e,t){return Ha(this,e,t)},async safeEncodeAsync(e,t){return Ya(this,e,t)},async safeDecodeAsync(e,t){return Xa(this,e,t)},toJSONSchema(e){return((e,t={})=>n=>{let r=ia({...n,processors:t});return aa(e,r),ua(r,e),ma(r,e)})(this,{})(e)},get description(){return Wo.get(this)?.description},get _def(){return this._zod.def}}),ns=er("_ZodString",(e,t)=>{pi.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{let r=n;r.type="string";let{minimum:i,maximum:o,format:a,patterns:s,contentEncoding:u,laxFormat:l}=Ia(e);if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),a&&(r.format=Aa[a]??a,""===r.format&&delete r.format,("time"===a||l)&&delete r.format),u&&(r.contentEncoding=u),s&&s.size>0){let e=[...s].map(Na);1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n)},Ln({format:e=>Ia(e).format??null,minLength:e=>Ia(e).minimum??null,maxLength:e=>Ia(e).maximum??null},{regex(...e){return this.check(function(e,t){return new ti({check:"string_format",format:"regex",...zn(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new ii({check:"string_format",format:"includes",...zn(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new oi({check:"string_format",format:"starts_with",...zn(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new ai({check:"string_format",format:"ends_with",...zn(t),suffix:e})}(...e))},min(...e){return this.check(Qo(...e))},max(...e){return this.check(Xo(...e))},length(...e){return this.check(ea(...e))},nonempty(...e){return this.check(Qo(1,...e))},lowercase(e){return this.check(function(e){return new ni({check:"string_format",format:"lowercase",...zn(e)})}(e))},uppercase(e){return this.check(function(e){return new ri({check:"string_format",format:"uppercase",...zn(e)})}(e))},trim(){return this.check(ta(e=>e.trim()))},normalize(...e){return this.check(function(e){return ta(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(ta(e=>e.toLowerCase()))},toUpperCase(){return this.check(ta(e=>e.toUpperCase()))},slugify(){return this.check(ta(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})),rs=er("ZodString",(e,t)=>{pi.init(e,t),ns.init(e,t)},{email(e){return this.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...zn(t)})}(cs,e))},url(e){return this.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...zn(t)})}(ps,e))},jwt(e){return this.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...zn(t)})}(xs,e))},emoji(e){return this.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...zn(t)})}(hs,e))},guid(e){return this.check(function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...zn(t)})}(ds,e))},uuid(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...zn(t)})}(fs,e))},uuidv4(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...zn(t)})}(fs,e))},uuidv6(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...zn(t)})}(fs,e))},uuidv7(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...zn(t)})}(fs,e))},nanoid(e){return this.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...zn(t)})}(ms,e))},cuid(e){return this.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...zn(t)})}(ys,e))},cuid2(e){return this.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...zn(t)})}(vs,e))},ulid(e){return this.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...zn(t)})}(gs,e))},base64(e){return this.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...zn(t)})}(Ss,e))},base64url(e){return this.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...zn(t)})}(Os,e))},xid(e){return this.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...zn(t)})}(ws,e))},ksuid(e){return this.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...zn(t)})}(_s,e))},ipv4(e){return this.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...zn(t)})}(bs,e))},ipv6(e){return this.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...zn(t)})}(ks,e))},cidrv4(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...zn(t)})}($s,e))},cidrv6(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...zn(t)})}(zs,e))},e164(e){return this.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...zn(t)})}(Es,e))},datetime(e){return this.check(function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...zn(t)})}(as,e))},date(e){return this.check(function(e,t){return new e({type:"string",format:"date",check:"string_format",...zn(t)})}(ss,e))},time(e){return this.check(function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...zn(t)})}(us,e))},duration(e){return this.check(function(e,t){return new e({type:"string",format:"duration",check:"string_format",...zn(t)})}(ls,e))}});function is(e){return function(e,t){return new e(Ko({type:"string",...zn(t)}))}(rs,e)}var os=er("ZodStringFormat",(e,t)=>{hi.init(e,t),ns.init(e,t)}),as=er("ZodISODateTime",(e,t)=>{Ai.init(e,t),os.init(e,t)}),ss=er("ZodISODate",(e,t)=>{Pi.init(e,t),os.init(e,t)}),us=er("ZodISOTime",(e,t)=>{Ni.init(e,t),os.init(e,t)}),ls=er("ZodISODuration",(e,t)=>{ji.init(e,t),os.init(e,t)}),cs=er("ZodEmail",(e,t)=>{vi.init(e,t),os.init(e,t)}),ds=er("ZodGUID",(e,t)=>{mi.init(e,t),os.init(e,t)}),fs=er("ZodUUID",(e,t)=>{yi.init(e,t),os.init(e,t)}),ps=er("ZodURL",(e,t)=>{ki.init(e,t),os.init(e,t)}),hs=er("ZodEmoji",(e,t)=>{$i.init(e,t),os.init(e,t)}),ms=er("ZodNanoID",(e,t)=>{zi.init(e,t),os.init(e,t)}),ys=er("ZodCUID",(e,t)=>{Si.init(e,t),os.init(e,t)}),vs=er("ZodCUID2",(e,t)=>{Oi.init(e,t),os.init(e,t)}),gs=er("ZodULID",(e,t)=>{Ei.init(e,t),os.init(e,t)}),ws=er("ZodXID",(e,t)=>{xi.init(e,t),os.init(e,t)}),_s=er("ZodKSUID",(e,t)=>{Ii.init(e,t),os.init(e,t)}),bs=er("ZodIPv4",(e,t)=>{Ti.init(e,t),os.init(e,t)}),ks=er("ZodIPv6",(e,t)=>{Di.init(e,t),os.init(e,t)}),$s=er("ZodCIDRv4",(e,t)=>{Ri.init(e,t),os.init(e,t)}),zs=er("ZodCIDRv6",(e,t)=>{Mi.init(e,t),os.init(e,t)}),Ss=er("ZodBase64",(e,t)=>{Ji.init(e,t),os.init(e,t)}),Os=er("ZodBase64URL",(e,t)=>{Bi.init(e,t),os.init(e,t)}),Es=er("ZodE164",(e,t)=>{Wi.init(e,t),os.init(e,t)}),xs=er("ZodJWT",(e,t)=>{Ki.init(e,t),os.init(e,t)}),Is=er("ZodNumber",(e,t)=>{Vi.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,{minimum:o,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:l,isInt:c}=Ia(e);i.type=c?"integer":"number";let d="number"==typeof l&&l>=(o??Number.NEGATIVE_INFINITY),f="number"==typeof u&&u<=(a??Number.POSITIVE_INFINITY),p="draft-04"===t.target||"openapi-3.0"===t.target;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:"number"==typeof o&&(i.minimum=o),f?p?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u:"number"==typeof a&&(i.maximum=a),s){let n=new Set;for(let o of s)Number.isFinite(o)&&0!==o?n.add(Math.abs(o)):oa(e,t,i,r,`A multipleOf divisor of ${o} cannot be represented in JSON Schema`);let[o,...a]=n;void 0!==o&&(i.multipleOf=o),a.length&&(i.allOf=[...i.allOf??[],...a.map(e=>({multipleOf:e}))])}})(e,t,n,r),e.isFinite=!0},Ln({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Ia(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Ia(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:n}=Ia(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Ia(e).format??null},{gt(e,t){return this.check(qo(e,t))},gte(e,t){return this.check(Ho(e,t))},min(e,t){return this.check(Ho(e,t))},lt(e,t){return this.check(Vo(e,t))},lte(e,t){return this.check(Go(e,t))},max(e,t){return this.check(Go(e,t))},int(e){return this.check(Ps(e))},safe(e){return this.check(Ps(e))},positive(e){return this.check(qo(0,e))},nonnegative(e){return this.check(Ho(0,e))},negative(e){return this.check(Vo(0,e))},nonpositive(e){return this.check(Go(0,e))},multipleOf(e,t){return this.check(Yo(e,t))},step(e,t){return this.check(Yo(e,t))},finite(){return this}}));var As=er("ZodNumberFormat",(e,t)=>{Gi.init(e,t),Is.init(e,t)});function Ps(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...zn(t)})}(As,e)}var Ns=er("ZodNull",(e,t)=>{qi.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"})(0,e,t)});var js=er("ZodUnknown",(e,t)=>{Hi.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Ts(){return new js({type:"unknown"})}var Zs=er("ZodNever",(e,t)=>{Yi.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function Fs(e){return function(e,t){return new e({type:"never",...zn(t)})}(Zs,e)}var Ds=er("ZodArray",(e,t)=>{es(),Qi.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:a,maximum:s}=Ia(e);"number"==typeof a&&(i.minItems=a),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=aa(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Qo(e,t))},nonempty(e){return this.check(Qo(1,e))},max(e,t){return this.check(Xo(e,t))},length(e,t){return this.check(ea(e,t))},unwrap(){return this.element}});var Rs=er("ZodObject",(e,t)=>{es(),oo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,o=e._zod.def,a=o.shape;if(Object.getOwnPropertySymbols(a).length&&oa(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let e in a)un(i.properties,e,aa(a[e],t,{...r,path:[...r.path,"properties",e]}));let s=[];for(let e of Object.keys(a)){let n=o.shape[e];("input"===t.io?void 0===ja(n):void 0===n._zod.optout)&&s.push(e)}s.length>0&&(i.required=s),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=aa(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),qn(e,"shape",e=>e._zod.def.shape,!1)},{keyof(){return function(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Js({type:"enum",entries:n,...zn(t)})}(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(hn(this._zod.def,{catchall:e}))},passthrough(){return this.clone(hn(this._zod.def,{catchall:Ts()}))},loose(){return this.clone(hn(this._zod.def,{catchall:Ts()}))},strict(){return this.clone(hn(this._zod.def,{catchall:Fs()}))},strip(){return this.clone(hn(this._zod.def,{catchall:void 0}))},extend(e){return function(e,t){if(!wn(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let n=cn(e);for(let e of Reflect.ownKeys(t))if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return $n(e,hn(e._zod.def,{shape:In(e,t)}))}(this,e)},safeExtend(e){return function(e,t){if(!wn(t))throw Error("Invalid input to safeExtend: expected a plain object");return $n(e,hn(e._zod.def,{shape:In(e,t)}))}(this,e)},merge(e){return function(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};return pn(n,e,Reflect.ownKeys(cn(e))),pn(n,t,Reflect.ownKeys(cn(t))),$n(e,hn(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return pn(i,e,xn(e,t)),$n(e,hn(n,{shape:i,checks:[]}))}(this,e)},omit(e){return function(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(xn(e,t)),o={};return pn(o,e,Reflect.ownKeys(cn(e)).filter(e=>!i.has(e))),$n(e,hn(n,{shape:o,checks:[]}))}(this,e)},partial(...e){return An(Ks,this,e[0])},exactPartial(...e){return An(Gs,this,e[0],"exactPartial")},required(...e){return function(e,t,n){let r=n?new Set(xn(t,n)):void 0,i={};return pn(i,t,Reflect.ownKeys(cn(t)),(t,n)=>r&&!r.has(n)?t:new e({type:"nonoptional",innerType:t})),$n(t,hn(t._zod.def,{shape:i}))}(Qs,this,e[0])}});function Ms(e,t){let n={type:"object",shape:e??{},...zn(t)};return new Rs(n)}var Cs=er("ZodUnion",(e,t)=>{so.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=!1===i.inclusive,a=i.options.map((e,n)=>aa(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options});var Us=er("ZodIntersection",(e,t)=>{uo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=aa(i.left,t,{...r,path:[...r.path,"allOf",0]}),a=aa(i.right,t,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,u=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];n.allOf=u,t.intersections.push(u)})(e,t,n,r)});var Js=er("ZodEnum",(e,t)=>{fo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{let r=tn(e._zod.def.entries);0!==r.length?(r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r):n.not={}})(e,0,n),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e){if(!n.has(r))throw Error(`Key ${r} not found in enum`);i[r]=t.entries[r]}return new Js({...t,checks:[],...zn(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e){if(!n.has(t))throw Error(`Key ${t} not found in enum`);delete i[t]}return new Js({...t,checks:[],...zn(r),entries:i})}});var Ls=er("ZodLiteral",(e,t)=>{po.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;if(0===i.values.length)return void(n.not={});let o=[];for(let a of i.values)if(void 0===a){if(oa(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof a){if(oa(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(a))}else o.push(a);if(0===o.length);else if(1===o.length){let e=o[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else o.every(e=>"number"==typeof e)&&(n.type="number"),o.every(e=>"string"==typeof e)&&(n.type="string"),o.every(e=>"boolean"==typeof e)&&(n.type="boolean"),o.every(e=>null===e)&&(n.type="null"),n.enum=o})(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Bs(e,t){return new Ls({type:"literal",values:Array.isArray(e)?e:[e],...zn(t)})}var Ws=er("ZodTransform",(e,t)=>{es(),ho.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{oa(e,t,n,r,"Transforms cannot be represented in JSON Schema")})(e,t,n,r),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new nr(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Cn(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),"input"in t||(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Cn(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});var Ks=er("ZodOptional",(e,t)=>{yo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fa(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Vs(e){return new Ks({type:"optional",innerType:e})}var Gs=er("ZodExactOptional",(e,t)=>{vo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fa(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var qs=er("ZodNullable",(e,t)=>{go.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=aa(i.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hs(e){return new qs({type:"nullable",innerType:e})}var Ys=er("ZodDefault",(e,t)=>{wo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;aa(i.innerType,t,r),t.seen.get(e).ref=i.innerType;let o=Za(i.defaultValue,e,t,n,r);o!==Ta&&(n.default=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var Xs=er("ZodPrefault",(e,t)=>{bo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;if(aa(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"!==t.io)return;let o=Za(i.defaultValue,e,t,n,r);o!==Ta&&(n._prefault=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Qs=er("ZodNonOptional",(e,t)=>{ko.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;aa(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var eu=er("ZodCatch",(e,t)=>{So.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i,o=e._zod.def;aa(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{return void oa(e,t,n,r,"Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var tu=er("ZodPipe",(e,t)=>{Oo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),a="input"===t.io?o?i.out:i.in:i.out;aa(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function nu(e,t){return new tu({type:"pipe",in:e,out:t})}var ru=er("ZodReadonly",(e,t)=>{xo.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;aa(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var iu=er("ZodCustom",(e,t)=>{Ao.init(e,t),ts.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{oa(e,t,n,r,"Custom types cannot be represented in JSON Schema")})(e,t,n,r)});var ou;Ms({version:Bs(1),runId:is(),attempt:function(e,t){return new e(Ko({type:"number",checks:[],...zn(t)}))}(Is,ou).int().positive(),childExit:Ms({code:Bs(0),signal:function(e){return function(e,t){return new e({type:"null",...zn(t)})}(Ns,e)}()}),timedOut:Bs(!1)}),Ms({version:Bs(1),runId:is(),outcome:Bs("merged"),finishedAt:is(),integrationSha:is()});import{join as au}from"node:path";async function su(e,t={}){let n;try{n=(await N(e)).filter(e=>e.endsWith(".json"))}catch{return{streak:0,fingerprint:"",counts:{merged:0,no_changes:0,failed:0,timed_out:0},pendingCount:0,recentFailureFingerprints:[]}}let r=[];for(let t of n){let n=await lu(au(e,t));void 0!==n&&r.push(n)}r.sort((e,t)=>Date.parse(t.finishedAt)-Date.parse(e.finishedAt));let i=r.slice(0,Math.max(0,t.limit??100)),o={merged:0,no_changes:0,failed:0,timed_out:0};for(let e of i)e.outcome in o&&(o[e.outcome]+=1);let a=[];for(let e of i){if("merged"===e.outcome||"no_changes"===e.outcome)break;"failed"===e.outcome&&a.push(e)}let s=t.now??Date.now(),u=void 0===a[0]?void 0:Date.parse(a[0].finishedAt),l=void 0!==u&&Number.isFinite(u)&&s-u>6048e5,c=(l?[]:a.slice(0,3)).map(uu),d=function(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return[...t].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0]))[0]?.[0]??""}(c),f=i.find(e=>"failed"===e.outcome),p=i.find(e=>"merged"===e.outcome||"no_changes"===e.outcome),h=l?void 0:a.at(-1)?.finishedAt,m=a.flatMap(e=>void 0===e.runId?[]:[e.runId]),y=[...new Set(a.flatMap(e=>void 0===e.launcher?[]:[e.launcher.runtime]))],v=i[0];return{streak:l?0:a.length,fingerprint:d,...void 0===f?{}:{lastFailure:{reason:f.reason??"failed",...void 0===f.detail?{}:{detail:f.detail},finishedAt:f.finishedAt,...void 0===f.launcher?{}:{launcher:f.launcher}}},...void 0===p?{}:{lastSuccessAt:p.finishedAt},...void 0===v?{}:{lastOutcome:{runId:v.runId??"",outcome:v.outcome,...void 0===v.reason?{}:{reason:v.reason},finishedAt:v.finishedAt}},counts:o,pendingCount:i.filter(e=>e.pending).length,recentFailureFingerprints:c,...void 0===h?{}:{streakSinceISO:h},...!0===t.includeStreakRunIds?{streakRunIds:m}:{},...0===y.length?{}:{streakRuntimes:y}}}function uu(e){return en(e.reason,e.detail)}async function lu(e){try{let n=JSON.parse(await P(e,"utf8"));if(!cu(n)||"string"!=typeof n.finishedAt||"merged"!==(t=n.outcome)&&"no_changes"!==t&&"parent_dirty"!==t&&"merge_conflict"!==t&&"dirty_uncommitted"!==t&&"failed"!==t&&"timed_out"!==t)return;let r=cu(n.delivery)?n.delivery:void 0;return{..."string"==typeof n.runId?{runId:n.runId}:{},outcome:n.outcome,..."string"==typeof n.reason?{reason:n.reason}:{},..."string"==typeof n.detail?{detail:n.detail}:{},finishedAt:n.finishedAt,pending:"pending"===r?.status,...du(n.launcher)?{launcher:n.launcher}:{}}}catch{return}var t}function cu(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function du(e){return!(!cu(e)||"string"!=typeof e.runtime||"string"!=typeof e.execPath||!Number.isInteger(e.pid)||Number(e.pid)<=0)&&(void 0===e.sessionId||"string"==typeof e.sessionId)}import{truncateToWidth as fu}from"@earendil-works/pi-tui";var pu=/\battempted:/;["<omo-senpi-task>","Background task results are automatically delivered: an idle session is always woken, and a running turn receives them at its next tool boundary.",'- /tasks shows this session\'s children; task_output is for one midpoint status or transcript peek (mode:"tail" for recent output).',"- task_send always steers a message into the addressed child, while task_cancel ends it.","- Team mail is steered into the recipient's running turn. Use task_send for updates; team mail never queues as editable follow-up work.","If no independent work remains, end your turn.","</omo-senpi-task>"].join("\n");var hu=["--no-skills","--no-prompt-templates","--no-context-files","--list-models"];import{isAbsolute as mu,join as yu,relative as vu}from"node:path";yu("@code-yeongyu","senpi"),yu("dist","cli.js");import{join as gu}from"node:path";async function wu(e,t){let n;try{n=await N(gu(e,t),{withFileTypes:!0})}catch{return[]}let r=[];for(let i of n){let n=""===t?i.name:`${t}/${i.name}`;i.isDirectory()?r.push(...await wu(e,n)):i.isFile()&&i.name.endsWith(".md")&&r.push(n)}return r}async function _u(e){let t=await wu(e,"system"),n=[];for(let r of t){let t=await P(gu(e,r),"utf8"),i=Buffer.byteLength(t,"utf8");n.push({path:r,bytes:i,tokens:Math.ceil(i/4)})}return n.sort((e,t)=>t.tokens-e.tokens||e.path.localeCompare(t.path)),{totalBytes:n.reduce((e,t)=>e+t.bytes,0),totalTokens:n.reduce((e,t)=>e+t.tokens,0),files:n}}function bu(e,t,n="info"){return e.ui?.notify(t,n),t}function ku(e){try{return process.kill(e,0),!0}catch{return!1}}var $u="system/persona.md";async function zu(e,t){let n;try{n=await N(""===t?e:te(e,t),{withFileTypes:!0})}catch{return[]}let r=[];for(let i of n){if(".git"===i.name||""===t&&"skills"===i.name)continue;let n=""===t?i.name:`${t}/${i.name}`;i.isDirectory()?r.push(...await zu(e,n)):i.isFile()&&i.name.endsWith(".md")&&r.push(n)}return r}async function Su(e){let t=(await zu(e,"")).filter(dt),n=[];for(let r of t)try{ut(await P(te(e,r),"utf8"))}catch(e){n.push(`${r} (${e instanceof Error?e.message:String(e)})`)}return[0===n.length?{name:"frontmatter",level:"ok",detail:`${t.length} memory file${1===t.length?"":"s"} valid`}:{name:"frontmatter",level:"fail",detail:`${n.length} invalid file${1===n.length?"":"s"}: ${n.join("; ")}; fix the frontmatter or remove the file`},t.includes($u)?{name:"persona",level:"ok",detail:`${$u} present`}:{name:"persona",level:"warn",detail:`${$u} is missing; create it with /init or the memory tools`}]}async function Ou(e,t){let{repo:n,worktrees:r}=t.identityPaths;if(!Q(te(n,".git")))return{name:"worktrees",level:"ok",detail:"no repository to inspect"};let i=await function(e,t,n){return(e.exec??de()).run(n,{cwd:t,timeoutMs:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}(e,n,["worktree","list","--porcelain"]);if(0!==i.code)return{name:"worktrees",level:"warn",detail:`could not list worktrees: ${i.stderr.trim()||`exit ${i.code}`}`};let o,a=new Set(i.stdout.split(/\r?\n/).filter(e=>e.startsWith("worktree ")).map(e=>e.slice(9).trim()));try{o=await N(r)}catch{return{name:"worktrees",level:"ok",detail:"no reflection worktrees"}}let s=o.map(e=>te(r,e)).filter(e=>!a.has(e)),u=[...a].filter(e=>e.startsWith(`${r}/`)&&!Q(e)),l=[...s.map(e=>`${e} (not registered with git)`),...u.map(e=>`${e} (registered but missing; run git worktree prune)`)];return 0===l.length?{name:"worktrees",level:"ok",detail:"no orphaned worktrees"}:{name:"worktrees",level:"warn",detail:`${l.length} orphan${1===l.length?"":"s"}: ${l.join("; ")}`}}async function Eu(e,t={}){let n=await su(te(e,"completions"),{now:t.now??Date.now()}),r=n.lastSuccessAt??"never";if(0===n.streak&&0===n.pendingCount)return{name:"reflection-health",level:"ok",detail:`streak 0; pending 0; last success ${r}`};let i=n.lastFailure,o=function(e,t){if(function(e){return!0===e?.startsWith("model_unreachable_with_extensions")}(t))return"no memory child can see the reflection model, not even with extensions loaded; set categories.<category>.model (or memory.reflection.category) in omo.json to a model from a core provider, or set memory.reflection.enabled to false";let n=`${e??""} ${t??""}`.toLowerCase();return n.includes("budget_not_met")?"run /dream again and trim or demote the largest system/ files until the committed estimate is below $SYSTEM_TOKEN_TARGET":n.includes("category_unavailable")||n.includes("could not resolve a usable model")?"no connected provider offers a model for the memory reflection category; run /login <provider>, or pin categories.<category>.model (or memory.reflection.category) in omo.json":n.includes("model-not-found")||n.includes("model_not_visible")||n.includes("model not found")||/model\s+"[^"]+"\s+not found/.test(n)?"the reflection child cannot see the configured category model; adjust memory.reflection category/model in your omo config":/bwrap:|setting up (uid map|gid map|namespace)/.test(n)?'the sandbox helper (bwrap) cannot create a user namespace on this host; set memory.reflection.sandbox to "off" in your omo config, or allow unprivileged user namespaces on the host':pu.test(n)?n.includes("provider_unavailable")?"every model for the memory reflection category was refused by its provider (rate limit or outage); automatic reflection resumes at the next probe, or run /reflect once the provider recovers":n.includes("context_overflow")?"the reflection prompt outgrew the context window of every candidate model; run /dream to trim system memory, or point memory.reflection at a larger-context model":n.includes("auth_missing")||n.includes("api key")?"run /login <provider>":"no model for the memory reflection category could be admitted; the models that were tried are named in the failure detail":"spawn_failed"===e||n.includes("execvp")?"senpi executable not resolvable for the reflection child; set SENPI_BIN":n.includes("api key")||n.includes("auth_missing")?"run /login <provider>":"inspect runtime/reflection-sessions/<runId>/child-stderr.log"}(i?.reason,i?.detail),a=await async function(e){try{let t=await async function(e){let t=await Vt(Kt(e,"park.json"));return null===t?{version:1,streak:0}:Lt(t)}(e);return void 0===t.parkedAt?"":`; automatic reflection paused since ${t.parkedAt} (next probe ${function(e){if(void 0!==e.parkedAt)return new Date(Date.parse(e.lastProbeAt??e.parkedAt)+216e5).toISOString()}(t)??"unknown"}; run /reflect to retry now)`}catch(e){return`; park state unreadable: ${e instanceof Error?e.message:String(e)}`}}(e);return{name:"reflection-health",level:n.streak>=3||""!==a?"warn":"ok",detail:`streak ${n.streak}; fingerprint ${n.fingerprint||"none"}; pending ${n.pendingCount}; last success ${r}; ${o}${a}`}}import{hostname as xu}from"node:os";import{join as Iu}from"node:path";var Au="a current runtime reclaims it at session start; on older builds delete runtime/reflection/active.lock after confirming no reflection run is active";var Pu=6e4,Nu=36e5;function ju(e){return e.records.filter(e=>"parked"===e.state)}function Tu(e){return e.records.filter(e=>"backoff"===e.state)}function Zu(e){let t=Tu(e).map(e=>null===e.nextEligibleAt?Number.NaN:Date.parse(e.nextEligibleAt)).filter(e=>Number.isFinite(e));if(0!==t.length)return Math.max(0,Math.min(...t)-e.now.getTime())}function Fu(e){return e<Pu?"now":e<Nu?`${Math.round(e/Pu)}m`:`${Math.round(e/Nu)}h`}async function Du(e){let t=vt(e.identityPaths),n=await async function(e){try{return(await N(e)).filter(e=>e.endsWith(".json")&&"consumed.json"!==e&&"failures.json"!==e).length}catch{return 0}}(t.queueDir),r=new Mt({identityPaths:e.identityPaths,now:()=>e.now});try{return{pending:n,records:(await r.readFailures()).entries,now:e.now}}catch(t){let r=t instanceof wt?t.message:`failure ledger unreadable: ${t instanceof Error?t.message:String(t)}`;return{pending:n,records:[],now:e.now,corrupt:r}}}import{basename as Ru,dirname as Mu,join as Cu,relative as Uu}from"node:path";var Ju=/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/;async function Lu(e){let t=await N(e,{withFileTypes:!0}),n=[];for(let r of t){if(".git"===r.name||"node_modules"===r.name)continue;let t=Cu(e,r.name);r.isSymbolicLink()||(r.isDirectory()?n.push(...await Lu(t)):r.isFile()&&"SKILL.md"===r.name&&n.push(t))}return n}function Bu(e,t){if(!t.trim())return{content:e,changed:!1,reason:"skill directory name is empty"};let n=e.match(Ju);if(!n)return{content:e,changed:!1,reason:"missing YAML frontmatter"};let r=n[1]??"",i=n[2]??"",o=n[3]??"",a=r.includes("\r\n")?"\r\n":"\n",s=i.replace(/\r\n/g,"\n").split("\n"),u=s.findIndex(e=>/^\s*name\s*:/.test(e));if(u>=0&&function(e){let t=e.match(/^\s*name\s*:\s*(.*?)\s*$/);return Boolean(t?.[1]?.trim())}(s[u]??""))return{content:e,changed:!1};let l=`name: ${c=t.trim(),/^[A-Za-z0-9_-]+$/.test(c)?c:JSON.stringify(c)}`;var c;return u>=0?s[u]=l:s.unshift(l),{content:`${r}${s.join(a)}${o}${e.slice(n[0].length)}`,changed:!0}}async function Wu(e){let t={scanned:0,repaired:[],skipped:[]};if(!e)return t;let n,r=Cu(e,"skills");if(!await async function(e){try{return await F(e),!0}catch{return!1}}(r))return t;try{n=await Lu(r)}catch(e){return t.skipped.push({path:"skills/",reason:`failed to scan skills directory: ${e instanceof Error?e.message:String(e)}`}),t}for(let r of n.sort()){let n=Uu(e,r).replace(/\\/g,"/");t.scanned+=1;try{let e=Bu(await P(r,"utf8"),Ru(Mu(r)));if(void 0!==e.reason){t.skipped.push({path:n,reason:e.reason});continue}if(!e.changed)continue;await X(r,e.content,"utf8"),t.repaired.push(n)}catch(e){t.skipped.push({path:n,reason:e instanceof Error?e.message:String(e)})}}return t}var Ku={ok:0,warn:1,fail:2};async function Vu(e,t){let n=await Du({identityPaths:t,now:new Date(e.now?.()??Date.now())}),r=function(e){if(void 0!==e.corrupt)return"facts: failure ledger unreadable (run /facts for detail)";let t=ju(e).length,n=Tu(e).length;if(0===t&&0===n)return;let r=Zu(e);return`facts: ${t} parked / ${n} backoff${void 0===r?"":` (next ${Fu(r)})`}`}(n);if(void 0===r)return;let i=function(e){if(void 0!==e.corrupt)return`facts failure ledger is unreadable (${e.corrupt}); repair or delete failures.json to resume launches`;let t=ju(e).length;if(t>0)return`${t} parked facts batch${1===t?"":"es"} need${1===t?"s":""} a manual unpark; run /facts retry after fixing the cause`;let n=Tu(e).length;if(0===n)return;let r=Zu(e);return`${n} facts batch${1===n?" is":"es are"} backing off${void 0===r?"":`; next attempt in ${Fu(r)}`}`}(n);return{name:"facts",level:void 0===n.corrupt?"warn":"fail",detail:`${r.replace(/^facts: /,"")}${void 0===i?"":`; ${i}`}`}}async function Gu(t,n){let r=function(e,t){let n=function(e,t){let n=function(e){return e.sessionManager?.getSessionId()}(t);if(void 0!==n)return e.contextForSession(n)}(e,t);return void 0!==n?n:"memory is not bound to this session; start a session with memory enabled and retry"}(t,n);if("string"==typeof r)return bu(n,r,"error");let i=r.identityPaths.repo,o=function(e){return Q(te(e.identityPaths.repo,".git"))?{name:"repository",level:"ok",detail:e.identityPaths.repo}:{name:"repository",level:"fail",detail:`missing at ${e.identityPaths.repo}; run /memfs init to create it`}}(r),a=[o],s=[];if("ok"===o.level){let n=t.loadSettings().settings.compile_warn_tokens;a.push(...await Su(i),await async function(t){let n;try{n=await P(te(t,$u))}catch{return{name:"soul-seed",level:"ok",detail:"no persona file to compare"}}return"ed9106790224a2820d68b1e09c847672dbd3c44b56e8dedd17091e8d0a8c0e8e"===e("sha256").update(n).digest("hex")?{name:"soul-seed",level:"warn",detail:`${$u} is still the v1 seed; review it against the v2 soul seed and rewrite it with the memory tools when ready`}:{name:"soul-seed",level:"ok",detail:"persona differs from the v1 seed"}}(i),await async function(e,t){let n;try{n=await N(t)}catch{return{name:"locks",level:"ok",detail:"no lock directory yet"}}let r=e.isProcessAlive??ku,i=[];for(let e of n.filter(e=>e.endsWith(".lock"))){let n=te(t,e),o=Ze(await P(n,"utf8").catch(()=>""));null!==o?o.hostname===ee()&&(r(o.pid)||i.push(`${n} (pid ${o.pid} is not running)`)):i.push(`${n} (unreadable lock record)`)}return 0===i.length?{name:"locks",level:"ok",detail:"no stale locks"}:{name:"locks",level:"warn",detail:`${i.length} stale lock${1===i.length?"":"s"}: ${i.join("; ")}; delete the file after confirming no run is active`}}(t,r.identityPaths.locks),await Ou(t,r),await async function(e){let t,n=te(e,"runs");try{t=await N(n,{withFileTypes:!0})}catch{return{name:"abandoned-runs",level:"ok",detail:"no abandoned runs"}}let r=t.filter(e=>e.isDirectory()&&Q(te(n,e.name,"abandoned.json"))).map(e=>te(n,e.name)).sort();return 0===r.length?{name:"abandoned-runs",level:"ok",detail:"no abandoned runs"}:{name:"abandoned-runs",level:"warn",detail:`${r.length} run${1===r.length?"":"s"} need manual disposal: ${r.join("; ")}`}}(r.identityPaths.reflection),await async function(e,t){let n,r=Iu(e.reflection,"active.lock");if(!Q(r))return{name:"reservation",level:"ok",detail:"no active reservation"};try{n=JSON.parse(await P(r,"utf8"))}catch(e){if(e instanceof SyntaxError)return{name:"reservation",level:"warn",detail:"active.lock is not valid JSON; delete it after confirming no reflection run is active"};throw e}let i="object"==typeof n&&null!==n?n:{},o="string"==typeof i.runId?i.runId:"unknown",a="string"==typeof i.reservedAt?Date.parse(i.reservedAt):Number.NaN,s="number"==typeof i.launcherPid?i.launcherPid:void 0,u="string"==typeof i.launcherHostname?i.launcherHostname:void 0;return void 0!==s&&void 0!==u&&Number.isFinite(a)?Date.now()-a<=6e4?{name:"reservation",level:"ok",detail:`reservation ${o} is recent`}:u!==xu()?{name:"reservation",level:"ok",detail:`reservation ${o} is owned by ${u}`}:(t.isProcessAlive??ku)(s)?{name:"reservation",level:"ok",detail:`reservation ${o} launcher pid ${s} is alive`}:{name:"reservation",level:"warn",detail:`ghost active reservation ${o}: launcher pid ${s} is dead (reserved ${new Date(a).toISOString()}); ${Au}`}:{name:"reservation",level:"warn",detail:`ghost active reservation ${o}: launcher identity missing (pre-stamping legacy); ${Au}`}}(r.identityPaths,t),await Eu(r.identityPaths.reflection,{now:t.now?.()??Date.now()}),await async function(e,t){let n=await _u(e);return n.totalTokens<t?{name:"tokens",level:"ok",detail:`~${n.totalTokens} tokens in system/ (warn at ${t})`}:{name:"tokens",level:"warn",detail:`~${n.totalTokens} tokens in system/ reached the ${t} warning threshold; trim system/ and move detail into external memory`}}(i,n));let o=await Vu(t,r.identityPaths);void 0!==o&&a.push(o);let u=await Wu(i),l=function(e){let t=[];return e.repaired.length>0&&t.push(`added missing \`name:\` frontmatter to ${e.repaired.length} skill${1===e.repaired.length?"":"s"}: ${e.repaired.map(e=>`\`${e}\``).join(", ")}`),e.skipped.length>0&&t.push(`could not repair ${e.skipped.length} skill${1===e.skipped.length?"":"s"}: ${e.skipped.map(e=>`\`${e.path}\` (${e.reason})`).join(", ")}`),t.join("\n")}(u);s.push(`[info] skills: scanned ${u.scanned} skill file${1===u.scanned?"":"s"}`,...l.split("\n").filter(e=>e.length>0).map(e=>`[info] skills: ${e}`))}let u=function(e){return e.reduce((e,t)=>Ku[t.level]>Ku[e]?t.level:e,"ok")}(a),l=[`# Memory doctor: ${r.identity}`,"",...a.map(e=>`[${e.level}] ${e.name}: ${e.detail}`),...s];return"fail"===u?l.push("","fix the failing checks above, then re-run /doctor"):"warn"===u&&l.push("","warnings do not block memory; re-run /doctor after addressing them"),bu(n,l.join("\n"),"fail"===u?"error":"warn"===u?"warning":"info")}export{Gu as runDoctor};
@@ -1,2 +1,2 @@
1
- // omo:3N7OblmFQfSQRQV8P5NKfuxchL8Oc_DZLRHWumedebM:t442sbFCSKYdQLnd8PNHMSS7uXJ13QdQ3kBtNotPNi8
1
+ // omo:kYqpIUFJhCJlUe7TxhpuDFE9-s2wmL-4C_NzHIlcrpQ:t442sbFCSKYdQLnd8PNHMSS7uXJ13QdQ3kBtNotPNi8
2
2
  import{Buffer as t}from"node:buffer";import*as e from"node:fs";import*as n from"node:fs/promises";function i(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}async function r(t){for(let e=0;;e+=1)try{return await t()}catch(t){if("EINTR"!==i(t)||e>=128)throw t}}function a(t){for(let e=0;;e+=1)try{return t()}catch(t){if("EINTR"!==i(t)||e>=128)throw t}}var o=new Set(["EPERM","EBUSY","EACCES"]),s=[10,25,50,100,200,400],l=t=>new Promise(e=>setTimeout(e,t));import{Buffer as c}from"node:buffer";import{constants as u}from"node:fs";import*as f from"node:fs/promises";function d(t){return"number"==typeof t?0!==(t&u.O_EXCL):"string"==typeof t&&t.toLowerCase().includes("x")}async function h(t,e,n,i){let a="string"==typeof e?c.from(e,n??"utf8"):e,o=0;for(;o<a.length;){i?.throwIfAborted();let{bytesWritten:e}=await r(()=>t.write(a,o));if(e<=0)throw Error(`fs write made no progress at offset ${o}`);o+=e}}function p(t){return"function"==typeof t}function m(t){return(...e)=>r(async()=>t(...e))}function y(t){return(...e)=>a(()=>t(...e))}function w(t,e){let n="async"===e?m:y,i=new Map;return new Proxy(t,{get(t,e){if(i.has(e))return i.get(e);let r=Reflect.get(t,e);if(!p(r))return r;let a=n(r),o=Reflect.get(r,"native");return p(o)&&Object.assign(a,{native:n(o)}),i.set(e,a),a}})}var g=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]);var $=w(n,"async");function v(t,e){return async function(t,e,n){let r="win32"===n.platform?n.delaysMs??s:[],a=n.sleep??l;for(let s=0;;s+=1)try{return void await n.rename(t,e)}catch(t){let e=r[s],n=i(t);if(void 0===e||void 0===n||!o.has(n))throw t;await a(e)}}(t,e,{rename:$.rename,platform:process.platform})}var k=w(e,"sync"),{access:b,chmod:x,copyFile:E,cp:S,link:I,lstat:A,mkdir:N,mkdtemp:_,readFile:P,readdir:T,realpath:L,rm:M,rmdir:O,stat:R,unlink:B}=$,{accessSync:D,chmodSync:j,fsyncSync:C,linkSync:H,lstatSync:U,mkdirSync:F,readFileSync:W,readdirSync:G,realpathSync:z,statSync:q,unlinkSync:K,writeFileSync:Y,writeSync:X}=k,Z=async(...t)=>{let e=()=>n.open(...t);return function(t){return new Proxy(t,{get(t,e){let n=Reflect.get(t,e);if(!p(n))return n;let a=e=>Reflect.apply(n,t,[...e]);return"close"===e||e===Symbol.asyncDispose?(...t)=>{let e=a(t);return e instanceof Promise?e.catch(t=>{if("EINTR"!==i(t))throw t}):e}:"string"==typeof e&&g.has(e)?(...t)=>{let e=a(t);return e instanceof Promise?e.catch(e=>{if("EINTR"!==i(e))throw e;return r(async()=>a(t))}):e}:(...t)=>a(t)}})}(await(d(t[1]??"r")?e():r(e)))};var J=async(e,a,o)=>{if("string"!=typeof a&&!(a instanceof Uint8Array))return n.writeFile(e,a,o);if("object"==typeof(s=e)&&!(s instanceof URL)&&!t.isBuffer(s)&&"fd"in s){let t="string"==typeof o?{encoding:o}:o??{};return t.signal?.throwIfAborted(),await h(e,a,t.encoding??void 0,t.signal),void(!0===t.flush&&await r(()=>e.sync()))}var s;return async function(t,e,n,a){let o="string"==typeof n?{encoding:n}:n??{};o.signal?.throwIfAborted();let s=o.flag??a,l=()=>f.open(t,s,o.mode),c=await(d(s)?l():r(l));try{await h(c,e,o.encoding??"utf8",o.signal),!0===o.flush&&await r(()=>c.sync())}finally{await c.close().catch(t=>{if("EINTR"!==i(t))throw t})}}(e,a,o??void 0,"w")};function V(t){try{return a(()=>e.statSync(t)),!0}catch{return!1}}import{join as Q}from"node:path";import{resolve as tt}from"node:path";var et=/(could not lock config file|unable to create '[^']*config\.lock')/i,nt=/(could not lock config file|unable to create '[^']*\.lock'|cannot lock ref|another git process seems to be running)/i,it=new Map;function rt(t){return et.test(ot(t))}function at(t){return nt.test(ot(t))}function ot(t){return t instanceof Error?t.message:String(t)}async function st(t,e){let n=tt(t),i=(it.get(n)??Promise.resolve()).catch(()=>{}).then(()=>async function(t){for(let e=1;e<=5;e+=1)try{return void await t()}catch(t){if(!rt(t)||5===e)throw t;await ct(25*2**(e-1))}}(e));it.set(n,i);try{await i}finally{it.get(n)===i&&it.delete(n)}}async function lt(t){for(let e=1;e<=5;e+=1)try{return await t()}catch(t){if(!at(t)||5===e)throw t;await ct(25*2**(e-1))}throw Error("unreachable: git lock retry exhausted without result")}function ct(t){return new Promise(e=>setTimeout(e,t))}class ut extends Error{constructor(t,e){super(t,e),this.name=new.target.name}}class ft extends ut{argv;code;stdout;stderr;constructor(t,e,n,i){let r=i.trim()||n.trim()||`exit code ${e}`;super(`git ${t.join(" ")} failed: ${r}`),this.argv=t,this.code=e,this.stdout=n,this.stderr=i}}class dt extends ut{argv;timeoutMs;constructor(t,e){super(`git ${t.join(" ")} timed out after ${e}ms`),this.argv=t,this.timeoutMs=e}}class ht extends ut{constructor(t){super("Git is required for memory storage but was not found on PATH.",t)}}class pt extends ut{porcelain;encodingDiagnostics;constructor(t,e){let n=e.length>0?` Dirty markdown encoding issue(s): ${e.join("; ")}.`:"";super(`Memory repo has uncommitted changes. Commit, discard, or sync them before using memory tools.\n${t.trimEnd()}${n}`),this.porcelain=t,this.encodingDiagnostics=e}}class mt extends ut{paths;constructor(t){super(`Memory write produced no effective changes for: ${t.join(", ")}`),this.paths=t}}class yt extends ut{}import{spawn as wt}from"node:child_process";import{win32 as gt}from"node:path";var $t=[["ProgramFiles",["Git","cmd","git.exe"]],["ProgramW6432",["Git","cmd","git.exe"]],["ProgramFiles(x86)",["Git","cmd","git.exe"]],["LOCALAPPDATA",["Programs","Git","cmd","git.exe"]]];function vt(t,e){for(let[n,i]of Object.entries(t)){if(n.toLowerCase()!==e.toLowerCase()||void 0===i)continue;let t=i.trim();if(t.length>0)return t}}function kt(t){return t instanceof ht&&t.cause instanceof Error&&"ENOENT"===t.cause.code}function bt(t,e,n,i){return new Promise((r,a)=>{let o=void 0!==n.stdin,s=wt(t,[...e],{cwd:n.cwd,env:i,shell:!1,stdio:[o?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),l=[],c=[],u=!1,f=!1,d=setTimeout(()=>{f=!0,s.kill("SIGKILL")},n.timeoutMs);s.stdout.on("data",t=>l.push(t)),s.stderr.on("data",t=>c.push(t)),o&&s.stdin.end(n.stdin),s.on("error",t=>{if(!u)if(u=!0,clearTimeout(d),"ENOENT"===t.code){if(!V(n.cwd))return void r({code:128,stdout:"",stderr:`fatal: cannot change to '${n.cwd}': No such file or directory`});a(new ht({cause:t}))}else a(t)}),s.on("close",t=>{if(u)return;if(u=!0,clearTimeout(d),f)return void a(new dt(e,n.timeoutMs));let i=Buffer.concat(l);r({code:t??1,stdout:i.toString("utf8"),stderr:Buffer.concat(c).toString("utf8"),stdoutBytes:i})})})}function xt(t={}){let e=t.platform??process.platform,n=t.runCommand??bt;return{async run(t,i){let r=i.env??process.env;try{return await n("git",t,i,r)}catch(a){if("win32"!==e||!kt(a))throw a;for(let e of function(t){let e=new Set,n=[];for(let[i,r]of $t){let a=vt(t,i);if(void 0===a||!/^[A-Za-z]:[\\/]/.test(a))continue;let o=gt.join(a,...r),s=gt.normalize(o).toLowerCase();e.has(s)||(e.add(s),n.push(o))}return n}(r))try{return await n(e,t,i,r)}catch(t){if(kt(t))continue;throw t}throw a}}}}import{join as Et}from"node:path";function St(t){return["-c",`user.name=${t.authorName.trim()||t.agentId}`,"-c",`user.email=${t.authorEmail??`${t.agentId}@omo.local`}`]}function It(t){return[...new Set(t.map(t=>t.replace(/\\/g,"/")).filter(t=>t.trim()))]}function At(t){let e=t.replace(/\\/g,"/"),n=e.split("/").filter(Boolean);if(!e||e.startsWith("/")||n.some(t=>"."===t||".."===t))throw new yt(`Invalid memory seed path: ${t}`);return n.join("/")}function Nt(t,e){return new ft(t,e.code,e.stdout,e.stderr)}import{randomUUID as _t}from"node:crypto";import{isAbsolute as Pt,resolve as Tt}from"node:path";import{randomUUID as Lt}from"node:crypto";import{basename as Mt,dirname as Ot,join as Rt}from"node:path";async function Bt(t,e,n,i,r){let a=Rt(t,e);await Ct(t,e),r||await async function(t){try{let e=await A(t);if(!e.isFile())throw Ht(t,e.isSymbolicLink()?"symlink":"non-file")}catch(t){if("ENOENT"!==Ut(t))throw t}}(a),await N(Ot(a),{recursive:!0}),await Ct(t,e);let o=Rt(Ot(a),`.${Mt(a)}.omo-${process.pid}-${Lt()}`),s=await Z(o,"wx",i);try{await h(s,n,"utf8"),await x(o,i),await s.sync()}catch(t){throw await s.close(),await M(o,{force:!0}),t}if(await s.close(),r){try{await I(o,a)}catch(t){if(await M(o,{force:!0}),"EEXIST"===Ut(t))return!1;throw t}await M(o)}else await v(o,a);return await Ft(Ot(a)),!0}async function Dt(t,e,n){let i=Rt(t,e);try{await I(n,i)}catch(t){if("EEXIST"===Ut(t))return!1;throw t}return await M(n),await Ft(Ot(i)),!0}async function jt(t){await M(t,{force:!0})}async function Ct(t,e){let n=e.split("/").slice(0,-1),i=t;for(let t of n){i=Rt(i,t);try{let t=await A(i);if(t.isSymbolicLink()||!t.isDirectory())throw Ht(e,"unsafe parent")}catch(t){if("ENOENT"===Ut(t))return;throw t}}}function Ht(t,e){return new qt(`Unsupported worktree ${e} at path: ${t}`)}function Ut(t){return t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:void 0}async function Ft(t){try{let e=await Z(t,"r");try{await e.sync()}finally{await e.close()}}catch(t){if("win32"!==process.platform||!["EISDIR","EPERM","EACCES","EINVAL"].includes(Ut(t)??""))throw t}}async function Wt(t){let e,n=(await Gt(t,["rev-parse","--git-path","index"])).stdout.trim(),i=Pt(n)?n:Tt(t.dir,n),r=`${i}.lock`,a=`${i}.omo-${process.pid}-${_t()}`;try{e=await Z(r,"wx")}catch(t){if("EEXIST"===Ut(t))return!1;throw t}let o=!1;try{if(s=await t.capture(),l=t.expected,JSON.stringify(s)!==JSON.stringify(l))return!1;await E(i,a);let n=null===t.next?["update-index","--force-remove","--",t.path]:["update-index","--add","--cacheinfo",t.next.mode,t.next.oid,t.path];return await Gt(t,n,{GIT_INDEX_FILE:a}),await h(e,await P(a)),await e.sync(),await e.close(),await v(r,i),o=!0,!0}finally{o||await e.close().catch(()=>{}),await M(a,{force:!0}),o||await M(r,{force:!0})}var s,l}async function Gt(t,e,n={}){let i=await t.exec.run(e,{cwd:t.dir,timeoutMs:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...n}});if(0!==i.code)throw Nt(e,i);return i}var zt=new Set(["100644","100755"]);class qt extends Error{constructor(t,e){super(t,e),this.name="GitPathStateError"}}class Kt{dir;exec;ownershipLossRecoveryPath;constructor(t,e){this.dir=t,this.exec=e}async capture(t){let e=Yt(t);return{index:await this.captureIndex(e),worktree:await this.captureWorktree(e)}}async captureAll(t){let e=[...new Set(t.map(Yt))],n=await Promise.all(e.map(async t=>[t,await this.capture(t)]));return new Map(n)}async hashWorktreeBlob(t,e=!1){return this.hashBlob([...e?["-w"]:[],"--no-filters","--stdin"],t)}async hashIndexBlob(t,e,n=!1){let i=Yt(t);return this.hashBlob([...n?["-w"]:[],`--path=${i}`,"--stdin"],e)}async readBlob(t){return Zt(t),(await this.git(["cat-file","blob",t])).stdout}async setIndex(t,e){let n=Yt(t);Jt(e),await this.git(["update-index","--add","--cacheinfo",e.mode,e.oid,n])}async writeIndexIfIdentity(t,e,n){let i=Yt(t);return null!==n&&Jt(n),Wt({dir:this.dir,exec:this.exec,path:i,expected:e,next:n,capture:()=>this.captureIndex(i)})}async removeIndex(t){let e=Yt(t);await this.git(["update-index","--force-remove","--",e])}async writeWorktree(t,e){let n=Yt(t);Vt(e),await Bt(this.dir,n,await this.readBlob(e.oid),e.mode,!1)}async writeWorktreeIfIdentity(t,e,n){this.ownershipLossRecoveryPath=void 0;let i=Yt(t);if("missing"===e.kind)return"missing"===(await this.captureWorktree(i)).kind&&("missing"===n.kind||(Vt(n),Bt(this.dir,i,await this.readBlob(n.oid),n.mode,!0)));let r=await async function(t,e){let n=Rt(t,e);await Ct(t,e);try{let t=await A(n);if(!t.isFile())throw Ht(e,t.isSymbolicLink()?"symlink":"non-file");let i=Rt(Ot(n),`.${Mt(n)}.omo-moved-${process.pid}-${Lt()}`);return await v(n,i),i}catch(t){if("ENOENT"===Ut(t))return;throw t}}(this.dir,i);if(void 0===r)return!1;try{let t=await this.captureMovedWorktree(r);if(a=t,o=e,JSON.stringify(a)!==JSON.stringify(o))return await Dt(this.dir,i,r)||await jt(r),!1;if("missing"===n.kind){let t=await this.reserveWorktreeDeletion(i,r);if(void 0===t)return await jt(r),!1;let e=await t.verify();if(void 0===e)return await jt(r),!1;let n=await e.finish();return!0!==n&&await jt(r),"string"==typeof n&&(this.ownershipLossRecoveryPath=n),!0===n}Vt(n);let s=await Bt(this.dir,i,await this.readBlob(n.oid),n.mode,!0);return await jt(r),s}catch(t){throw await Dt(this.dir,i,r)||await jt(r),t}var a,o}consumeOwnershipLossRecoveryPath(){let t=this.ownershipLossRecoveryPath;return this.ownershipLossRecoveryPath=void 0,t}async reserveWorktreeDeletion(t,e){return async function(t,e,n,i){let r=Rt(t,e),a=Lt();try{await N(r,{mode:448}),await J(Rt(r,".omo-reservation"),a,"utf8")}catch(t){if("EEXIST"===Ut(t))return;throw t}let o=await A(r);return{verify:async()=>{let t;try{t=await A(r)}catch(t){if("ENOENT"===Ut(t))return;throw t}if(t.isDirectory()&&t.dev===o.dev&&t.ino===o.ino){try{if(await P(Rt(r,".omo-reservation"),"utf8")!==a)return}catch(t){if("ENOENT"===Ut(t))return;throw t}return{finish:async()=>{let t=Rt(Ot(r),`.${Mt(r)}.omo-reserved-${process.pid}-${Lt()}`);try{await v(r,t)}catch(t){if("ENOENT"===Ut(t))return!1;throw t}let e,s=await A(t);if(s.isDirectory())try{e=await P(Rt(t,".omo-reservation"),"utf8")}catch(t){if("ENOENT"!==Ut(t))throw t}if(!s.isDirectory()||s.dev!==o.dev||s.ino!==o.ino||e!==a){let e=await i(t);return!0!==e&&e}await M(n),await M(t,{recursive:!0}),await Ft(Ot(r));try{return await A(r),!1}catch(t){if("ENOENT"===Ut(t))return!0;throw t}}}}}}}(this.dir,t,e,e=>this.restoreWorktreeClaim(t,e))}async restoreWorktreeClaim(t,e){return async function(t,e,n){if(!(await A(n)).isFile())return n;try{await I(n,Rt(t,e))}catch(t){if("EEXIST"===Ut(t))return n;throw t}return await M(n),!0}(this.dir,t,e)}async removeWorktree(t){await async function(t,e){let n,i=Rt(t,e);await Ct(t,e);try{n=await A(i)}catch(t){if("ENOENT"===Ut(t))return;throw t}if(!n.isFile())throw Ht(e,n.isSymbolicLink()?"symlink":"non-file");await M(i),await Ft(Ot(i))}(this.dir,Yt(t))}async captureIndex(t){let e=(await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",t])).stdout.split("\0").filter(Boolean);if(0===e.length)return null;let n=e.map(Xt);if(n.some(t=>"0"!==t.stage))throw new qt(`Git path is unmerged and cannot be recovered safely: ${t}`);if(1!==n.length||n[0]?.path!==t)throw new qt(`Git path did not resolve to one stage-zero index entry: ${t}`);let i=n[0];if(!zt.has(i.mode))throw new qt(`Unsupported Git index mode ${i.mode} for path: ${t}`);return{mode:i.mode,oid:i.oid}}async captureWorktree(t){await Ct(this.dir,t);let e,n=Et(this.dir,t);try{e=await A(n)}catch(t){if("ENOENT"===Ut(t))return{kind:"missing"};throw t}if(!e.isFile())throw Ht(t,e.isSymbolicLink()?"symlink":"non-file");let i=await this.hashWorktreeBlob(await P(n),!0);return{kind:"file",mode:Qt(e.mode),oid:i}}async captureMovedWorktree(t){let e=await A(t);if(!e.isFile())throw Ht(t,e.isSymbolicLink()?"symlink":"non-file");return{kind:"file",mode:Qt(e.mode),oid:await this.hashWorktreeBlob(await P(t),!0)}}async hashBlob(t,e){let n=(await this.git(["hash-object",...t],e)).stdout.trim();return Zt(n),n}async git(t,e){let n=await this.exec.run(t,{cwd:this.dir,timeoutMs:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"},...void 0===e?{}:{stdin:e}});if(0!==n.code)throw Nt(t,n);return n}}function Yt(t){let e=t.replace(/\\/g,"/"),n=e.split("/");if(!e||e.includes("\0")||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||n.some(t=>!t||"."===t||".."===t||".git"===t.toLowerCase()))throw new qt(`Invalid repository-relative Git path: ${t}`);return e}function Xt(t){let e=/^(\d{6}) ([0-9a-f]+) ([0-3])\t([\s\S]+)$/.exec(t);if(null===e)throw new qt("Git returned a malformed index entry");return{mode:e[1],oid:e[2],stage:e[3],path:e[4]}}function Zt(t){if(!/^[0-9a-f]+$/.test(t))throw new qt(`Invalid Git object ID: ${t}`)}function Jt(t){if(!zt.has(t.mode))throw new qt(`Unsupported Git index mode: ${t.mode}`);Zt(t.oid)}function Vt(t){if("file"!==t.kind||!Number.isInteger(t.mode)||t.mode<0||t.mode>511)throw new qt("Invalid worktree file identity");Zt(t.oid)}function Qt(t){return"win32"===process.platform?420:511&t}import{join as te}from"node:path";function ee(t,e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(Boolean).map(ne).filter(t=>t?.endsWith(".md")??!1).map(e=>function(t,e){let n=te(t,e);if(!V(n))return null;let i=W(n);return i.length>=2&&255===i[0]&&254===i[1]?`${e} has UTF-16 LE BOM`:i.length>=2&&254===i[0]&&255===i[1]?`${e} has UTF-16 BE BOM`:i.includes(0)?`${e} contains NUL bytes, possibly UTF-16`:null}(t,e)).filter(t=>null!==t)}function ne(t){if(t.length<4)return null;let e=t.slice(0,2);if(" D"===e||"D "===e||"DD"===e)return null;let n=t.slice(3);return(n.includes(" -> ")?n.split(" -> ").pop()??n:n).replace(/^"|"$/g,"")}import{dirname as ie,join as re}from"node:path";function ae(t){return t.split("\0").filter(Boolean)}function oe(t){let e={};for(let n of t.split(/\r?\n/)){let t=/^([^:\s][^:]*):\s*(.*)$/.exec(n);if(null===t)continue;let i=t[1]?.trim();void 0!==i&&i.length>0&&(e[i]=t[2]??"")}return e}async function se(t,e,n){let i=(await n()).split(/\r?\n/).filter(Boolean).filter(t=>{let n=ne(t);return null!==n&&!e.some(t=>n===t||n.startsWith(`${t}/`)||t.startsWith(n.endsWith("/")?n:`${n}/`))});if(0===i.length)return;let r=`${i.join("\n")}\n`;throw new pt(r,ee(t,r))}import{resolve as le}from"node:path";var ce=new Map;async function ue(t,e){let n=le(t),i=(ce.get(n)?.then(()=>{},()=>{})??Promise.resolve()).then(e),r=i.then(()=>{},()=>{});ce.set(n,r);try{return await i}finally{ce.get(n)===r&&ce.delete(n)}}class fe{dir;agentId;pathState;exec;hookInstaller;constructor(t){this.dir=t.dir,this.agentId=t.agentId,this.exec=t.exec??xt(),this.pathState=new Kt(this.dir,this.exec),this.hookInstaller=t.installHooks??(()=>{})}async init(t={}){await N(this.dir,{recursive:!0}),V(re(this.dir,".git"))||(await lt(()=>this.git(["init","--template="])),await lt(()=>this.git(["symbolic-ref","HEAD","refs/heads/main"]))),await(t.installHooks??this.hookInstaller)(this.dir),await this.ensureIdentity(t.authorName?.trim()||"OmO Agent");let e=await this.head();if(e)return e;let n=[];for(let e of t.seedFiles??[]){let t=At(e.relativePath),i=re(this.dir,t);await N(ie(i),{recursive:!0}),await J(i,e.content,"utf8"),n.push(t)}let i={agentId:this.agentId,authorName:t.authorName?.trim()||"OmO Agent"};return n.length>0&&(await this.stage(n),await this.hasPathChanges(n))?(await this.commitStaged("chore: initialize local memory",i)).sha:(await lt(()=>this.git([...St(i),"commit","--allow-empty","-m","chore: initialize empty local memory"])),this.requireHead())}async cleanCheck(){await this.hookInstaller(this.dir);let t=await this.status();if(t.trim())throw new pt(t,ee(this.dir,t))}async commitWrite(t,e,n){await this.hookInstaller(this.dir);let i=It(t);if(0===i.length)throw new mt(i);return await se(this.dir,i,()=>this.status()),await this.stage(i),this.commitPrepared(i,e,n)}async commitPrepared(t,e,n){await this.hookInstaller(this.dir);let i=It(t);if(0===i.length)throw new mt(i);if(await se(this.dir,i,()=>this.status()),!await this.hasPathChanges(i))throw new mt(i);return this.commitStaged(e,n)}async status(t=[]){let e=It(t),n=e.length>0?["--",...e]:[];return(await this.git(["-c","core.quotePath=false","status","--porcelain","--untracked-files=all",...n])).stdout}async head(){let t=await this.gitResult(["rev-parse","--verify","HEAD"]);return 0!==t.code?null:t.stdout.trim()||null}async headCommitTimestamp(){let t=await this.gitResult(["show","-s","--format=%ct","HEAD"]);if(0!==t.code)return null;let e=Number.parseInt(t.stdout.trim(),10);return Number.isSafeInteger(e)&&e>=0?e:null}async lsTree(t="HEAD",e){let n=e?["--",e]:[];return(await this.git(["ls-tree","-r","--name-only","-z",t,...n])).stdout.split("\0").filter(Boolean)}async lsTreeSized(t="HEAD"){return function(t){let e=[];for(let n of t.split("\0")){if(0===n.length)continue;let t=n.indexOf("\t");if(-1===t)continue;let i=n.slice(0,t).trim().split(/\s+/),r=n.slice(t+1);if(i.length<4||0===r.length)continue;let a=i[3];if(void 0===a||"-"===a)continue;let o=Number.parseInt(a,10);!Number.isSafeInteger(o)||o<0||e.push({path:r,bytes:o})}return e}((await this.git(["ls-tree","-r","-l","-z",t])).stdout)}async lsTreeBlobs(t="HEAD"){return function(t){let e=[];for(let n of t.split("\0")){let t=n.indexOf("\t");if(-1===t)continue;let[,i,r]=n.slice(0,t).trim().split(/\s+/),a=n.slice(t+1);"blob"===i&&void 0!==r&&0!==a.length&&e.push({path:a,oid:r})}return e}((await this.git(["ls-tree","-r","-z",t])).stdout)}async show(t,e){return(await this.git(["show",`${t}:${e}`])).stdout}async readBlobs(t){let e=[...new Set(t)];if(0===e.length)return new Map;let n=["cat-file","--batch"],i=await this.gitResult(n,`${e.join("\n")}\n`);if(0!==i.code)throw Nt(n,i);return function(t){let e=new Map,n=0;for(;n<t.length;){let i=t.indexOf(10,n);if(-1===i)throw Error("git cat-file --batch output ended inside a record header");let r=t.toString("utf8",n,i);n=i+1;let[a,o,s]=r.split(" ");if(void 0===s)continue;let l=Number.parseInt(s,10);if(void 0===a||!Number.isSafeInteger(l)||l<0||n+l>t.length)throw Error(`git cat-file --batch output is malformed at "${r}"`);"blob"===o&&e.set(a,t.toString("utf8",n,n+l)),n+=l+1}return e}(i.stdoutBytes??Buffer.from(i.stdout,"utf8"))}async log(t={}){let e=["log","--format=%x1e%H%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%cI"];void 0!==t.grep&&t.grep.length>0&&e.push("--fixed-strings","--all-match",...t.grep.map(t=>`--grep=${t}`)),void 0!==t.limit&&e.push("-n",String(t.limit)),void 0!==t.range&&e.push(t.range),void 0!==t.paths&&t.paths.length>0&&e.push("--",...t.paths);let n=(await this.git(e)).stdout.split("").slice(1).map(t=>{let[e="",n="",i="",r="",a="",o=""]=t.split(""),s=i.replace(/\r?\n$/,"");return{sha:e,subject:n,body:s,authorName:r,authorEmail:a,committedAt:o.trim(),trailers:oe(s)}});return!0!==t.includePaths?n:Promise.all(n.map(async t=>({...t,paths:ae((await this.git(["diff-tree","--no-commit-id","--name-only","-z","-r",t.sha])).stdout)})))}async worktreeAdd(t,e,n="HEAD"){await ue(this.dir,()=>lt(()=>this.git(["worktree","add","-b",e,t,n])))}async worktreeRemove(t,e=!0){await ue(this.dir,()=>lt(()=>this.git(["worktree","remove",...e?["--force"]:[],t])))}async merge(t,e={}){let n=["merge"];return(e.noFF??!0)&&n.push("--no-ff"),e.message&&n.push("-m",e.message),n.push(t),await lt(()=>this.git(n)),this.requireHead()}async configGet(t){let e=await this.gitResult(["config","--local","--get",t]);if(1===e.code)return null;if(0!==e.code)throw Nt(["config","--local","--get",t],e);return e.stdout.trim()||null}async configSet(t,e){await st(this.dir,async()=>{await this.git(["config","--local",t,e])})}async ensureIdentity(t){await this.configGet("omo.agentId")!==this.agentId&&await this.configSet("omo.agentId",this.agentId),await this.configGet("user.email")||await this.configSet("user.email",`${this.agentId}@omo.local`),await this.configGet("user.name")||await this.configSet("user.name",t),null===await this.configGet("commit.gpgsign")&&await this.configSet("commit.gpgsign","false"),null===await this.configGet("gc.auto")&&await this.configSet("gc.auto","0")}async stage(t){await lt(()=>this.git(["add","-A","--",...t]))}async hasPathChanges(t){return(await this.status(t)).trim().length>0}async commitStaged(t,e){return await lt(()=>this.git([...St(e),"commit","-m",t])),{committed:!0,sha:await this.requireHead()}}async requireHead(){let t=await this.head();if(!t)throw Error("Memory repository has no HEAD commit");return t}async git(t){let e=await this.gitResult(t);if(0!==e.code)throw Nt(t,e);return e}gitResult(t,e){return this.exec.run(t,{cwd:this.dir,timeoutMs:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"},...void 0===e?{}:{stdin:e}})}}import{execFile as de}from"node:child_process";var he=null;function pe(){return he??=async function(){if("darwin"!==process.platform)return null;try{let{dlopen:t,FFIType:e}=await(import("bun:ffi")),n=t("/usr/lib/libSystem.B.dylib",{proc_pidinfo:{args:[e.i32,e.i32,e.u64,e.ptr,e.i32],returns:e.i32}});return(t,e,i,r,a)=>Number(n.symbols.proc_pidinfo(t,e,i,r,a))}catch{return null}}(),he}var me=null;async function ye(t){if("win32"!==process.platform)return null;if(!Number.isSafeInteger(t)||t<=0)return null;me??=async function(){if("win32"!==process.platform)return null;try{let{dlopen:t,FFIType:e}=await(import("bun:ffi"));return t("kernel32.dll",{OpenProcess:{args:[e.u32,e.i32,e.u32],returns:e.ptr},GetProcessTimes:{args:[e.ptr,e.ptr,e.ptr,e.ptr,e.ptr],returns:e.i32},CloseHandle:{args:[e.ptr],returns:e.i32}}).symbols}catch{return null}}();let e=await me;if(null===e)return null;let n=e.OpenProcess(4096,0,t);if(null===n||0===n||0n===n)return null;try{let t=new BigUint64Array(1),i=e.GetProcessTimes(n,t,new BigUint64Array(1),new BigUint64Array(1),new BigUint64Array(1)),r=t[0]??0n;return 0===i||0n===r?null:r}finally{e.CloseHandle(n)}}async function we(t,e){return await new Promise(n=>{de(t,e,{encoding:"utf8",timeout:2e3,windowsHide:!0},(t,e)=>{if(null!==t)return void n(null);let i=e.trim();n(i.length>0?i:null)})})}!function(t,e){let n}(async function(t){if("linux"===process.platform)return await async function(t){try{let e=await P(`/proc/${t}/stat`,"utf8"),n=e.lastIndexOf(")");if(n<0)return null;let i=e.slice(n+2).trim().split(/\s+/)[19];return void 0===i?null:`linux-proc-start-ticks:${i}`}catch{return null}}(t);if("darwin"===process.platform||"freebsd"===process.platform){if("dead"===ge(t))return null;let e=await async function(t){if("darwin"!==process.platform)return null;if(!Number.isSafeInteger(t)||t<=0)return null;let e=await pe();if(null===e)return null;let n=new Uint8Array(136),i=0;try{i=e(t,3,0n,n,136)}catch{return null}if(136!==i)return null;let r=new DataView(n.buffer,n.byteOffset,n.byteLength),a=Number(r.getBigUint64(120,!0));return a>0?a:null}(t);if(null!==e)return`proc-start-epoch:${e}`;let n=await we("/bin/ps",["-o","lstart=","-p",String(t)]);return null===n?null:`ps-lstart:${n.replace(/\s+/g," ")}`}return"win32"===process.platform?await async function(t){if("dead"===ge(t))return null;let e=await ye(t);if(null!==e)return`win32-creation-filetime:${e}`;let n=await we("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${t} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`]);return null===n?null:`win32-creation-date:${n}`}(t):null},process.pid);function ge(t){try{return process.kill(t,0),"alive"}catch(t){let e=function(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}(t);return"ESRCH"===e?"dead":"EPERM"===e?"alive":"unknown"}}Promise.resolve();import{isAbsolute as $e,join as ve,resolve as ke}from"node:path";import{join as be}from"node:path";var xe=[["\\bAKIA[0-9A-Z]{16}\\b",""],["\\b(?:bearer|token|api[_-]?key|secret|password|passwd|pwd)\\s*[=:]\\s*\\S{1,256}","i"],["\\bAuthorization\\s*:\\s*Bearer\\s+\\S{1,256}","i"],["\\bsk-(?:proj-)?[-_A-Za-z0-9]+\\b",""],["\\b(?:ghp|github_pat|glpat|xox[baprs])-[-_A-Za-z0-9]+\\b",""]],Ee=(xe.map(([t,e])=>new RegExp(t,e)),xe.map(([t,e])=>new RegExp(t,`${e}g`)));function Se(t,e=0){let n=t.indexOf("-----BEGIN ",e);if(n<0)return;let i=t.indexOf("-----",n+11);if(i<0||i-(n+11)>64)return;let r=t.slice(n+11,i);if(0===r.length||/[^A-Za-z0-9 ]/.test(r))return;let a=t.indexOf("-----END ",i+5);for(;a>=0;){let e=a+9,i=t.indexOf("-----",e);if(i>=0&&t.slice(e,i)===r)return{start:n,end:i+5};a=t.indexOf("-----END ",i>=0?i+5:e)}}var Ie=/([a-z][a-z0-9+.-]*:\/\/)([^/@\s:]{1,256})(?::([^/@\s]{0,256}))?@/gi,Ae=/(^|[\s'"(<])([^\s:/@]{1,256})@([^\s:/@]{1,256}):/g;function Ne(t){if(!t)return"";let e=t.includes("://")?t.replace(Ie,(t,e,n,i)=>void 0===i?`${e}***@`:`${e}***:***@`):t;return function(t){let e=Ee.reduce((t,e)=>t.replace(e,"***"),t),n=0;for(;;){let t=Se(e,n);if(void 0===t)return e;e=`${e.slice(0,t.start)}***${e.slice(t.end)}`,n=t.start+3}}(e.includes("@")?e.replace(Ae,(t,e,n,i)=>`${e}***@${i}:`):e)}var _e="omo.memoryRepository.url",Pe="memory-repository-push.log",Te="main",Le=1e4;class Me{repo;exec;constructor(t){this.repo=t.repo,this.exec=t.exec??xt()}async set(t){let e=Oe(t);if(!e)throw Error("Memory repository URL must not be empty");return await this.repo.configSet(_e,e),{url:e,...await this.push(e,1e4)}}async unset(){await st(this.repo.dir,async()=>{let t=await this.run(["config","--local","--unset-all",_e],Le);if(0!==t.code&&5!==t.code)throw Error(Re(t))})}async status(){let t=await this.configuredUrl(),e=this.readLogTail();return t?{url:t,redactedUrl:Ne(t),lastLogLines:e,aheadCount:await this.aheadCount(t)}:{lastLogLines:e,aheadCount:0}}async pushNow(){let t=await this.configuredUrl();return t?this.push(t,6e4):{pushed:!1,detail:"No memory repository configured. Set one first."}}async configuredUrl(){return Oe(await this.repo.configGet(_e)??"")||void 0}async push(t,e){let n=await this.run(["push","--quiet",t,`${Te}:${Te}`],e);return 0===n.code?{pushed:!0,detail:""}:{pushed:!1,detail:Ne(Re(n))}}async aheadCount(t){let e=await this.run(["ls-remote",t,`refs/heads/${Te}`],Le),n=0===e.code?e.stdout.trim().split(/\s+/)[0]??"":"",i=n?`${n}..${Te}`:Te,r=await this.run(["rev-list","--count",i],Le);return 0!==r.code?0:Number.parseInt(r.stdout.trim(),10)||0}readLogTail(){let t;try{t=W((e=this.repo.dir,be(e,".git",Pe)),"utf8")}catch{return[]}var e;return t.split(/\r?\n/).filter(t=>t.trim().length>0).slice(-20).map(Ne)}async run(t,e){try{return await this.exec.run(t,{cwd:this.repo.dir,timeoutMs:e,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}catch(t){return{code:1,stdout:"",stderr:t instanceof Error?t.message:String(t)}}}}function Oe(t){let e=t.trim();return e.replace(/\/+$/,"")||e}function Re(t){return t.stderr.trim()||t.stdout.trim()||`git exited with code ${t.code}`}var Be=[{name:"pre-commit",script:'#!/bin/sh\n# Validate frontmatter in staged memory .md files.\n# Installed by omo memory-core. Do not edit by hand - regenerated on startup.\n\nALL_KNOWN_KEYS="description read_only limit kind aliases"\nTAB=$(printf \'\\t\')\n\nfm_value() {\n # $1 = file content, $2 = key. Prints the value of a top-level frontmatter\n # key, or nothing when the key is absent.\n closing=$(printf \'%s\\n\' "$1" | tail -n +2 | grep -n \'^---$\' | head -1 | cut -d: -f1)\n [ -z "$closing" ] && return 0\n printf \'%s\\n\' "$1" | tail -n +2 | head -n $((closing - 1)) |\n grep "^$2:" | head -1 | cut -d: -f2- | sed \'s/^ *//;s/ *$//\'\n}\n\ncheck_plain_scalar() {\n # $1 = file, $2 = key, $3 = value. A quoted value is the renderer\'s own\n # output; a plain value must be one that strict YAML reads back verbatim.\n case "$3" in\n \\"*|\\\'*|"") return 0 ;;\n *": "*|*":"|*" #"*|"#"*|"["*|"]"*|"{"*|"}"*|"&"*|"*"*|"!"*|"|"*|">"*|"%"*|"@"*|"\\`"*|","*|"?"*|"-"|"- "*)\n printf " %s: \'%s\' is not a safe YAML plain scalar (quote it, or remove \': \' and \' #\'): %s\\n" "$1" "$2" "$3"\n ;;\n esac\n}\n\ncheck_keys() {\n # $1 = file, $2 = HEAD content, $3 = frontmatter, $4 = key policy\n # ("contract" = memory key allowlist, "skill" = any key). Prints one error\n # line per offending frontmatter key. Runs in a pipeline subshell, so it\n # must never rely on assignments leaking to the caller.\n printf \'%s\\n\' "$3" | while IFS= read -r line; do\n [ -z "$line" ] && continue\n # Indented lines are YAML continuations of the previous key.\n case "$line" in " "*|"$TAB"*) continue ;; esac\n\n key=$(printf \'%s\\n\' "$line" | cut -d: -f1 | tr -d \' \')\n value=$(printf \'%s\\n\' "$line" | cut -d: -f2- | sed \'s/^ *//;s/ *$//\')\n\n if [ "$4" != skill ]; then\n known=false\n for k in $ALL_KNOWN_KEYS; do\n [ "$key" = "$k" ] && known=true && break\n done\n if [ "$known" = false ]; then\n printf " %s: unknown frontmatter key \'%s\' (allowed: %s)\\n" "$1" "$key" "$ALL_KNOWN_KEYS"\n continue\n fi\n fi\n\n if [ "$key" != description ] && [ "$key" != aliases ] && [ "$key" != read_only ]; then\n check_plain_scalar "$1" "$key" "$value"\n fi\n\n if [ "$key" = read_only ]; then\n if [ -n "$2" ]; then\n [ "$value" != "$(fm_value "$2" read_only)" ] &&\n printf " %s: \'read_only\' is a protected field and cannot be changed by the agent\\n" "$1"\n else\n printf " %s: \'read_only\' is a protected field and cannot be set by the agent\\n" "$1"\n fi\n fi\n\n # Deviation from letta: a YAML block scalar (\'>\' or \'|\', with optional\n # chomping or indent modifiers) is rejected. letta accepted the indicator\n # as the value, which silently stored \'>\' as the description.\n if [ "$key" = description ]; then\n case "$value" in\n "") printf " %s: \'description\' must not be empty\\n" "$1" ;;\n [\\>\\|]*) printf " %s: \'description\' must be a non-empty single line\\n" "$1" ;;\n *) check_plain_scalar "$1" description "$value" ;;\n esac\n fi\n done\n}\n\ncheck_file() {\n # $1 = file, $2 = key policy ("contract" or "skill")\n file="$1"\n policy="${2:-contract}"\n staged=$(git show ":$file")\n\n if [ "$(printf \'%s\\n\' "$staged" | head -1)" != "---" ]; then\n printf \' %s: missing frontmatter (must start with ---)\\n\' "$file"\n return 0\n fi\n\n closing_line=$(printf \'%s\\n\' "$staged" | tail -n +2 | grep -n \'^---$\' | head -1 | cut -d: -f1)\n if [ -z "$closing_line" ]; then\n printf \' %s: frontmatter opened but never closed (missing closing ---)\\n\' "$file"\n return 0\n fi\n\n head_content=$(git show "HEAD:$file" 2>/dev/null || true)\n if [ -n "$head_content" ] && [ "$(fm_value "$head_content" read_only)" = "true" ]; then\n printf \' %s: file is read_only and cannot be modified\\n\' "$file"\n return 0\n fi\n\n frontmatter=$(printf \'%s\\n\' "$staged" | tail -n +2 | head -n $((closing_line - 1)))\n check_keys "$file" "$head_content" "$frontmatter" "$policy"\n\n if ! printf \'%s\\n\' "$frontmatter" | grep -q \'^description:\'; then\n printf " %s: missing required field \'description\'\\n" "$file"\n fi\n\n if [ -n "$head_content" ] && [ -n "$(fm_value "$head_content" read_only)" ] &&\n [ -z "$(fm_value "$staged" read_only)" ]; then\n printf " %s: \'read_only\' is a protected field and cannot be removed by the agent\\n" "$file"\n fi\n}\n\nerrors=$(\n # Skills must always be directories: skills/<name>/SKILL.md.\n git diff --cached --name-only --diff-filter=ACMR |\n grep -E \'^(memory/)?skills/[^/]+\\.md$\' |\n while IFS= read -r skill_file; do\n printf \' %s: invalid skill path (skills must be folders). Use skills/<name>/SKILL.md\\n\' "$skill_file"\n done\n\n # Memory content keys are an allowlist under system/, reference/ and people/.\n git diff --cached --name-only --diff-filter=ACM |\n grep -E \'^(memory/)?(system|reference|people)/.*\\.md$\' |\n while IFS= read -r file; do\n check_file "$file" contract\n done\n\n # SKILL.md is read by the skill loader as strict YAML: same value rules,\n # description required, any key allowed.\n git diff --cached --name-only --diff-filter=ACM |\n grep -E \'^(memory/)?skills/.+/SKILL\\.md$\' |\n while IFS= read -r file; do\n check_file "$file" skill\n done\n)\n\nif [ -n "$errors" ]; then\n echo "Frontmatter validation failed:"\n printf \'%s\\n\' "$errors"\n exit 1\nfi\n\nexit 0\n'},{name:"post-commit",script:`#!/bin/sh\n# Push memory commits to the configured memory-repository mirror.\n# Installed by omo memory-core. Do not edit by hand - regenerated on startup.\nurl=$(git config --local --get ${_e} 2>/dev/null)\n[ -z "$url" ] && exit 0\n\nbranch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || exit 0\n[ -z "$branch" ] && exit 0\n[ "$branch" != "${Te}" ] && exit 0\n\nlog="$(git rev-parse --git-dir)/${Pe}"\n\npush_to_mirror() {\n {\n printf '\\n--- %s %s on %s ---\\n' "$(date '+%Y-%m-%dT%H:%M:%S')" "$(git rev-parse --short HEAD)" "$branch"\n git push --quiet "$url" "$branch:$branch" 2>&1\n echo "exit=$?"\n } >> "$log" 2>&1\n}\n\nif [ "$OMO_MEMORY_PUSH_SYNC" = "1" ]; then\n push_to_mirror\n exit 0\nfi\n\npush_to_mirror &\nexit 0\n`}];function De(t){let e=function(t){return ve(function(t){let e=ve(t,".git");if(!V(e)||q(e).isDirectory())return e;let n=W(e,"utf8").trim(),i=/^gitdir:\s*(.+)$/.exec(n);if(!i?.[1])return e;let r=je(i[1].trim(),t),a=ve(r,"commondir");return V(a)?je(W(a,"utf8").trim(),r):r}(t),"hooks")}(t);return F(e,{recursive:!0}),Be.map(({name:t,script:n})=>{let i=ve(e,t);return Y(i,n,"utf8"),j(i,493),{name:t,path:i}})}function je(t,e){return $e(t)?t:ke(e,t)}new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});import{dirname as Ce}from"node:path";import{fileURLToPath as He}from"node:url";Ce(He(import.meta.url));import{dirname as Ue}from"node:path";import{fileURLToPath as Fe}from"node:url";Ue(Fe(import.meta.url)),new Date(0).toISOString();var We="\\p{Script=Hangul}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\u30fc";new RegExp(`[${We}]+|(?:(?![${We}])[\\p{L}\\p{M}\\p{N}])+`,"gu"),new RegExp(`^[${We}]+$`,"u"),new RegExp(`[${We}]`,"u"),new RegExp(`[${We}]`,"gu"),new RegExp(`[\\p{L}${We}]`,"gu");import{dirname as Ge}from"node:path";import{fileURLToPath as ze}from"node:url";Ge(ze(import.meta.url));import{join as qe}from"node:path";var Ke="memory-backup-";function Ye(t){return t.identityPaths.root}async function Xe(t,e){let n=function(t){let e=new Date(t).toISOString();return`${e.slice(0,10).replace(/-/g,"")}-${e.slice(11,19).replace(/:/g,"")}`}((t.now??Date.now)()),i=Ye(e),r=qe(i,`${Ke}${n}`),a=2;for(;V(r);)r=qe(i,`${Ke}${n}-${a}`),a+=1;return await S(e.identityPaths.repo,r,{recursive:!0}),r}import{join as Ze}from"node:path";function Je(t,e){return new fe({dir:e.identityPaths.repo,agentId:e.identity,installHooks:t=>{De(t)},...void 0===t.exec?{}:{exec:t.exec}})}function Ve(t){return t.slice(0,8)}function Qe(t){return V(Ze(t.identityPaths.repo,".git"))}function tn(t,e){return Qe(e)?Je(t,e):function(t){return`no memory repository for ${t.identity} at ${t.identityPaths.repo}; run /memfs init first`}(e)}import{join as en}from"node:path";async function nn(t,e){let n;try{n=await T(en(t,e),{withFileTypes:!0})}catch{return[]}let i=[];for(let r of n){let n=""===e?r.name:`${e}/${r.name}`;r.isDirectory()?i.push(...await nn(t,n)):r.isFile()&&r.name.endsWith(".md")&&i.push(n)}return i}async function rn(t){let e=await nn(t,"system"),n=[];for(let i of e){let e=await P(en(t,i),"utf8"),r=Buffer.byteLength(e,"utf8");n.push({path:i,bytes:r,tokens:Math.ceil(r/4)})}return n.sort((t,e)=>e.tokens-t.tokens||t.path.localeCompare(e.path)),{totalBytes:n.reduce((t,e)=>t+e.bytes,0),totalTokens:n.reduce((t,e)=>t+e.tokens,0),files:n}}function an(t,e,n="info"){return t.ui?.notify(e,n),e}function on(t,e){let n=function(t){return t.sessionManager?.getSessionId()}(e);if(void 0!==n)return t.contextForSession(n)}function sn(t){return!0===t.hasUI&&"function"==typeof t.ui?.confirm}import{basename as ln,dirname as cn,join as un,relative as fn}from"node:path";var dn=/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/;async function hn(t){let e=await T(t,{withFileTypes:!0}),n=[];for(let i of e){if(".git"===i.name||"node_modules"===i.name)continue;let e=un(t,i.name);i.isSymbolicLink()||(i.isDirectory()?n.push(...await hn(e)):i.isFile()&&"SKILL.md"===i.name&&n.push(e))}return n}function pn(t,e){if(!e.trim())return{content:t,changed:!1,reason:"skill directory name is empty"};let n=t.match(dn);if(!n)return{content:t,changed:!1,reason:"missing YAML frontmatter"};let i=n[1]??"",r=n[2]??"",a=n[3]??"",o=i.includes("\r\n")?"\r\n":"\n",s=r.replace(/\r\n/g,"\n").split("\n"),l=s.findIndex(t=>/^\s*name\s*:/.test(t));if(l>=0&&function(t){let e=t.match(/^\s*name\s*:\s*(.*?)\s*$/);return Boolean(e?.[1]?.trim())}(s[l]??""))return{content:t,changed:!1};let c=`name: ${u=e.trim(),/^[A-Za-z0-9_-]+$/.test(u)?u:JSON.stringify(u)}`;var u;return l>=0?s[l]=c:s.unshift(c),{content:`${i}${s.join(o)}${a}${t.slice(n[0].length)}`,changed:!0}}async function mn(t){let e={scanned:0,repaired:[],skipped:[]};if(!t)return e;let n,i=un(t,"skills");if(!await async function(t){try{return await R(t),!0}catch{return!1}}(i))return e;try{n=await hn(i)}catch(t){return e.skipped.push({path:"skills/",reason:`failed to scan skills directory: ${t instanceof Error?t.message:String(t)}`}),e}for(let i of n.sort()){let n=fn(t,i).replace(/\\/g,"/");e.scanned+=1;try{let t=pn(await P(i,"utf8"),ln(cn(i)));if(void 0!==t.reason){e.skipped.push({path:n,reason:t.reason});continue}if(!t.changed)continue;await J(i,t.content,"utf8"),e.repaired.push(n)}catch(t){e.skipped.push({path:n,reason:t instanceof Error?t.message:String(t)})}}return e}var yn=["status","init","sync","repair","reset","backup","restore","diff","tokens"],wn="skills-usage.json";var gn={status:async({deps:t,ctx:e,identity:n})=>{let i=tn(t,n);if("string"==typeof i)return an(e,i,"error");let r=await i.head(),a=(await i.status()).split(/\r?\n/).filter(t=>t.trim().length>0),o=await new Me({repo:i,...void 0===t.exec?{}:{exec:t.exec}}).status(),s=a.length>0,l=[`# Memfs status: ${n.identity}`,`Repository: ${n.identityPaths.repo}`,`HEAD: ${null===r?"(no commits)":Ve(r)}`,"Working tree: "+(s?`dirty — ${a.length} entr${1===a.length?"y":"ies"}`:"clean"),`Mirror: ${o.redactedUrl??"not configured"}${void 0===o.url?"":` (${o.aheadCount} ahead)`}`];s&&l.push("",...a,"","uncommitted changes present; inspect with /memfs diff or commit through the memory tools");let c=await async function(t){let e,n;try{e=await P(Q(t,wn),"utf8")}catch{return}try{n=JSON.parse(e)}catch{return}if(null===n||"object"!=typeof n||Array.isArray(n))return;let i=Object.entries(n);if(0===i.length)return;let r=["","## Skills usage"];for(let[t,e]of i){if(null===e||"object"!=typeof e||Array.isArray(e))continue;let n=e,i="number"==typeof n.count?n.count:0,a="string"==typeof n.lastUsedAt?n.lastUsedAt:"unknown";r.push(` ${t}: ${i} read${1===i?"":"s"}, last ${a}`)}return r.length>2?r.join("\n"):void 0}(n.identityPaths.runtime);return void 0!==c&&l.push(c),an(e,l.join("\n"),s?"warning":"info")},init:async({deps:t,ctx:e,identity:n})=>{if(Qe(n)){let i=await Je(t,n).head();return an(e,`memory repository already initialized at ${n.identityPaths.repo}${null===i?"":` (HEAD ${Ve(i)})`}`)}let i=await Je(t,n).init();return an(e,`initialized memory repository at ${n.identityPaths.repo} (HEAD ${Ve(i)})`)},sync:async({deps:t,ctx:e,identity:n})=>{let i=tn(t,n);if("string"==typeof i)return an(e,i,"error");let r=new Me({repo:i,...void 0===t.exec?{}:{exec:t.exec}}),a=await r.status();if(void 0===a.url)return an(e,"no memory repository mirror configured; set one with /memory-repository set <url>","error");let o=await r.pushNow();return o.pushed?an(e,`pushed main to ${a.redactedUrl}`):an(e,`push to ${a.redactedUrl} failed: ${o.detail}`,"error")},repair:async({deps:t,ctx:e,identity:n})=>{let i=tn(t,n);if("string"==typeof i)return an(e,i,"error");let r=De(i.dir),a=await mn(i.dir),o=function(t){let e=[];return t.repaired.length>0&&e.push(`added missing \`name:\` frontmatter to ${t.repaired.length} skill${1===t.repaired.length?"":"s"}: ${t.repaired.map(t=>`\`${t}\``).join(", ")}`),t.skipped.length>0&&e.push(`could not repair ${t.skipped.length} skill${1===t.skipped.length?"":"s"}: ${t.skipped.map(t=>`\`${t.path}\` (${t.reason})`).join(", ")}`),e.join("\n")}(a),s=[`# Memfs repair: ${n.identity}`,`- reinstalled ${r.length} git hook${1===r.length?"":"s"}`,`- scanned ${a.scanned} skill file${1===a.scanned?"":"s"}`];return o.length>0&&s.push(...o.split("\n").map(t=>`- ${t}`)),an(e,s.join("\n"))},reset:async({deps:t,ctx:e,parsed:n,identity:i})=>{let r=tn(t,i);if("string"==typeof r)return an(e,r,"error");if(sn(e)){if(!0!==await(e.ui?.confirm?.("Reset memory repository",`This deletes ${i.identityPaths.repo} and starts an empty history. A backup is written first.`)))return an(e,"reset aborted; nothing changed")}else if(!0!==n.flags.get("force"))return an(e,"reset requires --force in a noninteractive session (no confirmation UI available): /memfs reset --force","error");let a=await Xe(t,i);return await M(i.identityPaths.repo,{recursive:!0,force:!0}),an(e,`reset complete; backup at ${a}; new HEAD ${Ve(await Je(t,i).init())}`)},backup:async({deps:t,ctx:e,identity:n})=>{let i=tn(t,n);return"string"==typeof i?an(e,i,"error"):an(e,`backup written to ${await Xe(t,n)}`)},restore:async({deps:t,ctx:e,parsed:n,identity:i})=>{let r=await async function(t){let e;try{e=await T(Ye(t))}catch{return[]}return e.filter(t=>t.startsWith(Ke)).sort()}(i);if(0===r.length)return an(e,`no backups found for ${i.identity} in ${i.identityPaths.root}`,"error");let a,o=n.positionals[1];if(void 0===o){if(!sn(e))return an(e,`specify a backup name: /memfs restore <name>; available: ${r.join(", ")}`,"error");let t=await(e.ui?.select?.("Restore memory backup",[...r]));if(void 0===t)return an(e,"restore cancelled; nothing changed");a=t}else a=o;if(!r.includes(a))return an(e,`unknown backup: ${a}; available: ${r.join(", ")}`,"error");let s=await async function(t,e,n){let i=qe(Ye(e),n),r=e.identityPaths.repo,a=V(r)?await Xe(t,e):void 0;return await M(r,{recursive:!0,force:!0}),await S(i,r,{recursive:!0}),{restored:n,safetyBackup:a}}(t,i,a),l=void 0===s.safetyBackup?"":`; safety backup at ${s.safetyBackup}`;return an(e,`restored ${s.restored} into ${i.identityPaths.repo}${l}`)},diff:async({deps:t,ctx:e,identity:n})=>{let i=tn(t,n);if("string"==typeof i)return an(e,i,"error");let r=await function(t,e,n){return(t.exec??xt()).run(n,{cwd:e,timeoutMs:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}(t,i.dir,["diff"]);if(0!==r.code)return an(e,`git diff failed: ${r.stderr.trim()||`exit ${r.code}`}`,"error");let a=r.stdout.trim();return 0===a.length?an(e,"No changes."):an(e,`# Memfs diff: ${n.identity}\n\n${a}`,"warning")},tokens:async({deps:t,ctx:e,identity:n})=>{let i=tn(t,n);if("string"==typeof i)return an(e,i,"error");let r=await rn(i.dir),a=[`# System prompt token estimate (bytes/4): ${n.identity}`,`Total: ~${r.totalTokens} tokens (${r.totalBytes} bytes)`];if(r.files.length>0){a.push(""," tokens path");for(let t of r.files)a.push(` ${String(t.tokens).padStart(6)} ${t.path}`)}return an(e,a.join("\n"))}};async function $n(t,e,n){let i=function(t,e={}){let n=new Set(e.booleans??[]),i=[],r=new Map,a=t.trim().split(/\s+/).filter(Boolean);for(let t=0;t<a.length;t+=1){let e=a[t]??"";if(!e.startsWith("--")){i.push(e);continue}let o=e.slice(2),s=o.indexOf("=");if(s>=0){r.set(o.slice(0,s),o.slice(s+1));continue}let l=a[t+1];n.has(o)||void 0===l||l.startsWith("--")?r.set(o,!0):(r.set(o,l),t+=1)}return{positionals:i,flags:r}}(e,{booleans:["force"]}),[r]=i.positionals;if(void 0===r)return an(n,`usage: /memfs <${yn.join("|")}>`,"error");let a=gn[r];if(void 0===a)return an(n,`unknown /memfs subcommand: ${r}; expected one of ${yn.join(", ")}`,"error");let o="init"===r?function(t,e){return on(t,e)??t.resolveIdentity?.()}(t,n):function(t,e){let n=on(t,e);return void 0!==n?n:"memory is not bound to this session; start a session with memory enabled and retry"}(t,n);return void 0===o?an(n,"no memory identity resolved; check the memory config for this project","error"):"string"==typeof o?an(n,o,"error"):a({deps:t,ctx:n,parsed:i,identity:o})}export{$n as runMemfs};