agestra 4.8.3 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -1,59 +1,59 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as ___cr } from 'module';import { fileURLToPath as ___fu } from 'url';import { dirname as ___dn } from 'path';const __filename = ___fu(import.meta.url);const __dirname = ___dn(__filename);const require = ___cr(import.meta.url);
3
- var Fb=Object.create;var ec=Object.defineProperty;var Ub=Object.getOwnPropertyDescriptor;var Vb=Object.getOwnPropertyNames;var Wb=Object.getPrototypeOf,Bb=Object.prototype.hasOwnProperty;var an=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),We=(t,e)=>{for(var r in e)ec(t,r,{get:e[r],enumerable:!0})},Hb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Vb(e))!Bb.call(t,o)&&o!==r&&ec(t,o,{get:()=>e[o],enumerable:!(n=Ub(e,o))||n.enumerable});return t};var ap=(t,e,r)=>(r=t!=null?Fb(Wb(t)):{},Hb(e||!t||!t.__esModule?ec(r,"default",{value:t,enumerable:!0}):r,t));var cp,to,up,lp,dp,pp,fp,mp,hp,gp,yp,_p,vp,Ts,tc,xp,bp,ln,vr=an(()=>{"use strict";cp="4.8.3",to="http://localhost:11434",up="llama3",lp=".agestra/.jobs",dp=".agestra/traces",pp=".agestra/worktrees",fp=".agestra/sessions",mp=".agestra/workspace",hp=".agestra/messages",gp=".agestra/workers",yp=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),_p=2,vp=6e4,Ts=20,tc=5e4,xp="[REDACTED]",bp=["","--- REQUIRED RESPONSE FORMAT ---","Respond with JSON only, matching exactly this shape:",'{ "agrees": true | false, "feedback": "specific issues or why you agree", "suggestions": "concrete changes if you disagree (optional, may be omitted)" }',"No prose, markdown, or explanation outside the JSON object. The JSON must be the entire response or wrapped in a single ```json code fence.","-------------------------------"].join(`
4
- `),ln=Object.freeze({auto:Object.freeze({name:"auto",description:"Auto-detect build profile from project structure (package.json scripts, tsconfig, vitest config, etc.).",command:"npx",args:Object.freeze([])}),tsc:Object.freeze({name:"tsc",description:"TypeScript project-references build via `npx tsc -b --noEmit`.",command:"npx",args:Object.freeze(["tsc","-b","--noEmit"])}),vitest:Object.freeze({name:"vitest",description:"Run the Vitest unit-test suite in CI mode.",command:"npx",args:Object.freeze(["vitest","run","--reporter=dot"])}),"npm-build":Object.freeze({name:"npm-build",description:"Run the project's `npm run build` script.",command:"npm",args:Object.freeze(["run","build"])}),"npm-test":Object.freeze({name:"npm-test",description:"Run the project's `npm test` script.",command:"npm",args:Object.freeze(["test","--","--run"])})})});import{execFileSync as Gb}from"child_process";function dn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return Gb("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0}),{delivered:!0}}catch{try{return process.kill(t),{delivered:!0}}catch{return{delivered:!1}}}try{return process.kill(-t,"SIGTERM"),{delivered:!0}}catch{try{return process.kill(t,"SIGTERM"),{delivered:!0}}catch{return{delivered:!1}}}}function Kt(t,e=3e3){let r=t.pid;if(r)dn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e)}var ro=an(()=>{"use strict"});import{execFileSync as Jb,spawn as Kb}from"child_process";import{existsSync as Qb}from"fs";function Xb(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:Yb.has(t.toLowerCase())}function ew(t){if(t.includes("\0"))throw new Error(`Windows shim arg contains null byte: ${JSON.stringify(t)}`);if(t.includes("%"))throw new Error(`Windows shim arg contains '%' which would trigger cmd.exe env expansion: ${JSON.stringify(t)}`);return/[\s"&^<>|()!]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function tw(t){let e=t.toLowerCase();if(pn.has(e))return pn.get(e)??null;try{let n=Jb("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return pn.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return pn.set(e,a),a}let i=`${n[0]}.ps1`;if(Qb(i)){let a={type:"powershell",path:i};return pn.set(e,a),a}}catch{}return pn.set(e,null),null}function Nt(t,e){if(!Xb(t))return{command:t,args:e};let r=tw(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>ew(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function De(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c}=t;return new Promise((u,l)=>{let d=Nt(e,r),p=Kb(d.command,d.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),f="",g="",y=0,m=0,b=!1,_=null,w=!1,k=()=>{!w&&y+m>a&&(b=!0,w=!0,Kt(p))};p.stdout.on("data",j=>{y+=j.length,y<=a&&(f+=j.toString()),k()}),p.stderr.on("data",j=>{m+=j.length;let Se=j.toString();if(m<=a&&(g+=Se),k(),!w&&c){let Q=c(Se);Q&&(_=Q,w=!0,Kt(p))}}),i&&p.stdin&&(p.stdin.write(i),p.stdin.end());let P=()=>{Kt(p),l(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`))},U=setTimeout(P,n),Z=()=>{clearTimeout(U),U=setTimeout(P,n)};p.stdout.on("data",Z),p.stderr.on("data",Z),p.on("close",j=>{if(clearTimeout(U),_){l(_);return}u({stdout:f,stderr:g,exitCode:j??1,truncated:b})}),p.on("error",j=>{clearTimeout(U),l(new Error(`CLI spawn error: ${j.message}`))})})}var Yb,pn,fn=an(()=>{"use strict";ro();Yb=new Set(["codex","gemini","npm","npx"]),pn=new Map});import{writeFileSync as v$,mkdirSync as io,openSync as ic,writeSync as ac,fsyncSync as Mp,closeSync as cc,renameSync as x$,unlinkSync as b$,appendFileSync as w$}from"fs";import{dirname as ao,join as $$}from"path";import{randomUUID as S$}from"crypto";function ie(t,e){let r=ao(t);io(r,{recursive:!0});let n=$$(r,`.tmp-${S$().slice(0,8)}`);try{v$(n,e,"utf-8"),x$(n,t)}catch(o){try{b$(n)}catch{}throw o}}function it(t,e){ie(t,JSON.stringify(e,null,2))}function co(t,e){let r=ao(t);io(r,{recursive:!0});let n=ic(t,"a");try{ac(n,e),Mp(n)}finally{cc(n)}}var Ns,js=an(()=>{"use strict";Ns=class{buffer=new Map;flushTimer=null;flushIntervalMs;maxBufferSize;auditFsync;destroyed=!1;constructor(e){this.flushIntervalMs=e?.flushIntervalMs??2e3,this.maxBufferSize=e?.maxBufferSize??100,this.auditFsync=e?.auditFsync??!0,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer&&typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}append(e,r,n){if(this.destroyed)throw new Error("DurableAppendWriter has been destroyed");if(n==="audit"){if(this.auditFsync)co(e,r);else{let s=ao(e);io(s,{recursive:!0}),w$(e,r)}return}let o=this.buffer.get(e);o||(o=[],this.buffer.set(e,o)),o.push(r),o.length>=this.maxBufferSize&&this.flushFile(e),this.flushIntervalMs===0&&this.flushFile(e)}flush(){for(let e of this.buffer.keys())this.flushFile(e)}panicFlush(){for(let[e,r]of this.buffer)if(r.length!==0)try{let n=ao(e);io(n,{recursive:!0});let o=ic(e,"a");try{ac(o,r.join("")),Mp(o)}finally{cc(o)}}catch{}this.buffer.clear()}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush())}flushFile(e){let r=this.buffer.get(e);if(!r||r.length===0)return;let n=ao(e);io(n,{recursive:!0});let o=ic(e,"a");try{ac(o,r.join(""))}finally{cc(o)}this.buffer.delete(e)}}});import{existsSync as Np,realpathSync as k$}from"fs";import{basename as T$,dirname as P$,isAbsolute as Zp,join as E$,normalize as R$,resolve as uc,relative as z$}from"path";function C$(t){return t===""||!t.startsWith("..")&&!Zp(t)}function jp(t){let e=[],r=uc(t);for(;!Np(r);){let o=P$(r);if(o===r)break;e.unshift(T$(r)),r=o}let n=Np(r)?k$(r):r;return e.reduce((o,s)=>E$(o,s),n)}function qp(t,e){let r=jp(e),n=jp(t),o=z$(r,n);return C$(o)}function lc(t,e){let r=uc(e,t);return qp(r,e)}function ht(t,e){let r=uc(e,t);if(!qp(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Me(t,e){if(t.length===0)throw new Error("Filename must not be empty");if(t.includes("\0"))throw new Error(`Filename contains null byte: ${JSON.stringify(t)}`);if(t.includes("/")||t.includes("\\"))throw new Error(`Filename must not contain path separators: ${JSON.stringify(t)}`);if(t.includes(".."))throw new Error(`Filename must not contain '..': ${JSON.stringify(t)}`);return ht(t,e)}function Ft(t,e){if(Zp(t)){let r=R$(t);if(!lc(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return ht(t,e)}function Ls(t){return A$.test(t)}function Zs(t,e){if(!t||typeof t!="string")throw new et(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new et(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new et(t,"command must not contain path separators");if(!Lp.has(t))throw new et(t,`command is not in the allowlist (${[...Lp].join(", ")})`);for(let r of e){if(typeof r!="string")throw new et(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new et(t,`arg contains null byte: ${JSON.stringify(r)}`);if(I$.has(r))throw new et(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var A$,Lp,I$,et,uo=an(()=>{"use strict";A$=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Lp=new Set(["gemini","codex","npx","node","npm","tsc"]),I$=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),et=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});var Vp={};We(Vp,{CLI_PROVIDERS:()=>Fp,resolveCliConfig:()=>Up});import{readFileSync as dc}from"fs";import{join as tt}from"path";import{spawn as D$}from"child_process";function Up(t){let e=O$[t.provider]??t.provider;return Fp[e]??null}function Nr(t,e){let r=tt(t,"status.json"),n=JSON.parse(dc(r,"utf-8"));it(r,{...n,...e})}async function M$(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(dc(tt(t,"job.json"),"utf-8"))}catch{try{it(tt(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),ie(tt(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Up(e);r||(Nr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ie(tt(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Nr(t,{state:"running",startedAt:new Date().toISOString()});let s=dc(tt(t,"prompt.txt"),"utf-8"),i=o(s);try{Zs(n,i)}catch(c){let u=c instanceof et?c.message:`Argv rejected: ${c.message}`;Nr(t,{state:"error",completedAt:new Date().toISOString()}),ie(tt(t,"error.txt"),u);return}let a;if(e.cwd)try{a=ht(e.cwd,process.cwd())}catch(c){Nr(t,{state:"error",completedAt:new Date().toISOString()}),ie(tt(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Nt(n,i),l=D$(u.command,u.args,{cwd:a,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,g=0;l.stdout.on("data",m=>{f+=m.length,f<=10485760&&(d+=m.toString())}),l.stderr.on("data",m=>{g+=m.length,g<=10485760&&(p+=m.toString())});let y=setTimeout(()=>{Kt(l),ie(tt(t,"output.txt"),d),ie(tt(t,"error.txt"),p),Nr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",m=>{clearTimeout(y),ie(tt(t,"output.txt"),d),ie(tt(t,"error.txt"),p);let b=d.trim().length>0;Nr(t,{state:m===0||b?"completed":"error",exitCode:m??1,completedAt:new Date().toISOString()}),c()}),l.on("error",m=>{clearTimeout(y);let b=m.code==="ENOENT"?"missing_cli":"error";ie(tt(t,"error.txt"),m.message),Nr(t,{state:b,completedAt:new Date().toISOString()}),c()})})}var O$,Fp,N$,Wp=an(()=>{"use strict";js();ro();uo();fn();O$={"gemini-cli":"gemini","codex-cli":"codex"},Fp={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--full-auto","--ephemeral",t]}};N$=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");N$&&M$().catch(()=>process.exit(1))});var Qo=E(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.regexpCode=ne.getEsmExportName=ne.getProperty=ne.safeStringify=ne.stringify=ne.strConcat=ne.addCodeArg=ne.str=ne._=ne.nil=ne._Code=ne.Name=ne.IDENTIFIER=ne._CodeOrName=void 0;var Jo=class{};ne._CodeOrName=Jo;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gr=class extends Jo{constructor(e){if(super(),!ne.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ne.Name=Gr;var lt=class extends Jo{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Gr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ne._Code=lt;ne.nil=new lt("");function jy(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Wu(r,e[n]),r.push(t[++n]);return new lt(r)}ne._=jy;var Vu=new lt("+");function Ly(t,...e){let r=[Ko(t[0])],n=0;for(;n<e.length;)r.push(Vu),Wu(r,e[n]),r.push(Vu,Ko(t[++n]));return RP(r),new lt(r)}ne.str=Ly;function Wu(t,e){e instanceof lt?t.push(...e._items):e instanceof Gr?t.push(e):t.push(AP(e))}ne.addCodeArg=Wu;function RP(t){let e=1;for(;e<t.length-1;){if(t[e]===Vu){let r=zP(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function zP(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Gr||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Gr))return`"${t}${e.slice(1)}`}function CP(t,e){return e.emptyStr()?t:t.emptyStr()?e:Ly`${t}${e}`}ne.strConcat=CP;function AP(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ko(Array.isArray(t)?t.join(","):t)}function IP(t){return new lt(Ko(t))}ne.stringify=IP;function Ko(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ne.safeStringify=Ko;function DP(t){return typeof t=="string"&&ne.IDENTIFIER.test(t)?new lt(`.${t}`):jy`[${t}]`}ne.getProperty=DP;function OP(t){if(typeof t=="string"&&ne.IDENTIFIER.test(t))return new lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ne.getEsmExportName=OP;function MP(t){return new lt(t.toString())}ne.regexpCode=MP});var Gu=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ke=Qo(),Bu=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Vi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Vi||(Qe.UsedValueState=Vi={}));Qe.varKinds={const:new Ke.Name("const"),let:new Ke.Name("let"),var:new Ke.Name("var")};var Wi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ke.Name?e:this.name(e)}name(e){return new Ke.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=Wi;var Bi=class extends Ke.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ke._)`.${new Ke.Name(r)}[${n}]`}};Qe.ValueScopeName=Bi;var NP=(0,Ke._)`\n`,Hu=class extends Wi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?NP:Ke.nil}}get(){return this._scope}name(e){return new Bi(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ke._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ke.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Vi.Started);let l=r(u);if(l){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ke._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ke._)`${s}${l}${this.opts._n}`;else throw new Bu(u);c.set(u,Vi.Completed)})}return s}};Qe.ValueScope=Hu});var B=E(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.or=H.and=H.not=H.CodeGen=H.operators=H.varKinds=H.ValueScopeName=H.ValueScope=H.Scope=H.Name=H.regexpCode=H.stringify=H.getProperty=H.nil=H.strConcat=H.str=H._=void 0;var te=Qo(),vt=Gu(),lr=Qo();Object.defineProperty(H,"_",{enumerable:!0,get:function(){return lr._}});Object.defineProperty(H,"str",{enumerable:!0,get:function(){return lr.str}});Object.defineProperty(H,"strConcat",{enumerable:!0,get:function(){return lr.strConcat}});Object.defineProperty(H,"nil",{enumerable:!0,get:function(){return lr.nil}});Object.defineProperty(H,"getProperty",{enumerable:!0,get:function(){return lr.getProperty}});Object.defineProperty(H,"stringify",{enumerable:!0,get:function(){return lr.stringify}});Object.defineProperty(H,"regexpCode",{enumerable:!0,get:function(){return lr.regexpCode}});Object.defineProperty(H,"Name",{enumerable:!0,get:function(){return lr.Name}});var Ki=Gu();Object.defineProperty(H,"Scope",{enumerable:!0,get:function(){return Ki.Scope}});Object.defineProperty(H,"ValueScope",{enumerable:!0,get:function(){return Ki.ValueScope}});Object.defineProperty(H,"ValueScopeName",{enumerable:!0,get:function(){return Ki.ValueScopeName}});Object.defineProperty(H,"varKinds",{enumerable:!0,get:function(){return Ki.varKinds}});H.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Wt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ju=class extends Wt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?vt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Nn(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Hi=class extends Wt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Nn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return Ji(e,this.rhs)}},Ku=class extends Hi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qu=class extends Wt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Yu=class extends Wt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Xu=class extends Wt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},el=class extends Wt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Nn(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},Yo=class extends Wt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(jP(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Qr(e,r.names),{})}},Bt=class extends Yo{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},tl=class extends Yo{},Mn=class extends Bt{};Mn.kind="else";var Jr=class t extends Bt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Mn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Zy(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Nn(this.condition,e,r),this}get names(){let e=super.names;return Ji(e,this.condition),this.else&&Qr(e,this.else.names),e}};Jr.kind="if";var Kr=class extends Bt{};Kr.kind="for";var rl=class extends Kr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Nn(this.iteration,e,r),this}get names(){return Qr(super.names,this.iteration.names)}},nl=class extends Kr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?vt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ji(super.names,this.from);return Ji(e,this.to)}},Gi=class extends Kr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Nn(this.iterable,e,r),this}get names(){return Qr(super.names,this.iterable.names)}},Xo=class extends Bt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Xo.kind="func";var es=class extends Yo{render(e){return"return "+super.render(e)}};es.kind="return";var ol=class extends Bt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Qr(e,this.catch.names),this.finally&&Qr(e,this.finally.names),e}},ts=class extends Bt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ts.kind="catch";var rs=class extends Bt{render(e){return"finally"+super.render(e)}};rs.kind="finally";var sl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
5
- `:""},this._extScope=e,this._scope=new vt.Scope({parent:e}),this._nodes=[new tl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Ju(e,s,n)),s}const(e,r,n){return this._def(vt.varKinds.const,e,r,n)}let(e,r,n){return this._def(vt.varKinds.let,e,r,n)}var(e,r,n){return this._def(vt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Hi(e,r,n))}add(e,r){return this._leafNode(new Ku(e,H.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new el(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new Jr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jr(e))}else(){return this._elseNode(new Mn)}endIf(){return this._endBlockNode(Jr,Mn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new rl(e),r)}forRange(e,r,n,o,s=this.opts.es5?vt.varKinds.var:vt.varKinds.let){let i=this._scope.toName(e);return this._for(new nl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=vt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new Gi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?vt.varKinds.var:vt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Gi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Kr)}label(e){return this._leafNode(new Qu(e))}break(e){return this._leafNode(new Yu(e))}return(e){let r=new es;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(es)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ol;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ts(s),r(s)}return n&&(this._currNode=o.finally=new rs,this.code(n)),this._endBlockNode(ts,rs)}throw(e){return this._leafNode(new Xu(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=te.nil,n,o){return this._blockNode(new Xo(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Xo)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Jr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};H.CodeGen=sl;function Qr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ji(t,e){return e instanceof te._CodeOrName?Qr(t,e.names):t}function Nn(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function jP(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Zy(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${il(t)}`}H.not=Zy;var LP=qy(H.operators.AND);function ZP(...t){return t.reduce(LP)}H.and=ZP;var qP=qy(H.operators.OR);function FP(...t){return t.reduce(qP)}H.or=FP;function qy(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${il(e)} ${t} ${il(r)}`}function il(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var oe=E(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var le=B(),UP=Qo();function VP(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=VP;function WP(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vy(t,e),!Wy(e,t.self.RULES.all))}G.alwaysValidSchema=WP;function Vy(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Gy(t,`unknown keyword: "${s}"`)}G.checkUnknownRules=Vy;function Wy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=Wy;function BP(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=BP;function HP({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}G.schemaRefOrVal=HP;function GP(t){return By(decodeURIComponent(t))}G.unescapeFragment=GP;function JP(t){return encodeURIComponent(cl(t))}G.escapeFragment=JP;function cl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=cl;function By(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=By;function KP(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=KP;function Fy({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}G.mergeEvaluated={props:Fy({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),ul(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Hy}),items:Fy({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Hy(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&ul(t,r,e),r}G.evaluatedPropsToName=Hy;function ul(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}G.setEvaluated=ul;var Uy={};function QP(t,e){return t.scopeValue("func",{ref:e,code:Uy[e.code]||(Uy[e.code]=new UP._Code(e.code))})}G.useFunc=QP;var al;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(al||(G.Type=al={}));function YP(t,e,r){if(t instanceof le.Name){let n=e===al.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+cl(t)}G.getErrorPath=YP;function Gy(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=Gy});var Ht=E(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var je=B(),XP={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};ll.default=XP});var ns=E(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var re=B(),Qi=oe(),Ue=Ht();Le.keywordError={message:({keyword:t})=>(0,re.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,re.str)`"${t}" keyword must be ${e} ($data)`:(0,re.str)`"${t}" keyword is invalid ($data)`};function eE(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Qy(t,e,r);n??(i||a)?Jy(s,c):Ky(o,(0,re._)`[${c}]`)}Le.reportError=eE;function tE(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Qy(t,e,r);Jy(o,a),s||i||Ky(n,Ue.default.vErrors)}Le.reportExtraError=tE;function rE(t,e){t.assign(Ue.default.errors,e),t.if((0,re._)`${Ue.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,re._)`${Ue.default.vErrors}.length`,e),()=>t.assign(Ue.default.vErrors,null)))}Le.resetErrorsCount=rE;function nE({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Ue.default.errors,a=>{t.const(i,(0,re._)`${Ue.default.vErrors}[${a}]`),t.if((0,re._)`${i}.instancePath === undefined`,()=>t.assign((0,re._)`${i}.instancePath`,(0,re.strConcat)(Ue.default.instancePath,s.errorPath))),t.assign((0,re._)`${i}.schemaPath`,(0,re.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,re._)`${i}.schema`,r),t.assign((0,re._)`${i}.data`,n))})}Le.extendErrors=nE;function Jy(t,e){let r=t.const("err",e);t.if((0,re._)`${Ue.default.vErrors} === null`,()=>t.assign(Ue.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Ue.default.vErrors}.push(${r})`),t.code((0,re._)`${Ue.default.errors}++`)}function Ky(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,re._)`new ${t.ValidationError}(${e})`):(r.assign((0,re._)`${n}.errors`,e),r.return(!1))}var Yr={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function Qy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:oE(t,e,r)}function oE(t,e,r={}){let{gen:n,it:o}=t,s=[sE(o,r),iE(t,r)];return aE(t,e,s),n.object(...s)}function sE({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,Qi.getErrorPath)(e,Qi.Type.Str)}`:t;return[Ue.default.instancePath,(0,re.strConcat)(Ue.default.instancePath,r)]}function iE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,re.str)`${e}/${t}`;return r&&(o=(0,re.str)`${o}${(0,Qi.getErrorPath)(r,Qi.Type.Str)}`),[Yr.schemaPath,o]}function aE(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Yr.keyword,o],[Yr.params,typeof e=="function"?e(t):e||(0,re._)`{}`]),c.messages&&n.push([Yr.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Yr.schema,i],[Yr.parentSchema,(0,re._)`${l}${d}`],[Ue.default.data,s]),u&&n.push([Yr.propertyName,u])}});var Xy=E(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.boolOrEmptySchema=jn.topBoolOrEmptySchema=void 0;var cE=ns(),uE=B(),lE=Ht(),dE={message:"boolean schema is false"};function pE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Yy(t,!1):typeof r=="object"&&r.$async===!0?e.return(lE.default.data):(e.assign((0,uE._)`${n}.errors`,null),e.return(!0))}jn.topBoolOrEmptySchema=pE;function fE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Yy(t)):r.var(e,!0)}jn.boolOrEmptySchema=fE;function Yy(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,cE.reportError)(o,dE,void 0,e)}});var dl=E(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.getRules=Ln.isJSONType=void 0;var mE=["string","number","integer","boolean","null","object","array"],hE=new Set(mE);function gE(t){return typeof t=="string"&&hE.has(t)}Ln.isJSONType=gE;function yE(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ln.getRules=yE});var pl=E(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.shouldUseRule=dr.shouldUseGroup=dr.schemaHasRulesForType=void 0;function _E({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&e_(t,n)}dr.schemaHasRulesForType=_E;function e_(t,e){return e.rules.some(r=>t_(t,r))}dr.shouldUseGroup=e_;function t_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}dr.shouldUseRule=t_});var os=E(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.reportTypeError=Ze.checkDataTypes=Ze.checkDataType=Ze.coerceAndCheckDataType=Ze.getJSONTypes=Ze.getSchemaTypes=Ze.DataType=void 0;var vE=dl(),xE=pl(),bE=ns(),F=B(),r_=oe(),Zn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Zn||(Ze.DataType=Zn={}));function wE(t){let e=n_(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ze.getSchemaTypes=wE;function n_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(vE.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ze.getJSONTypes=n_;function $E(t,e){let{gen:r,data:n,opts:o}=t,s=SE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,xE.schemaHasRulesForType)(t,e[0]));if(i){let a=ml(e,n,o.strictNumbers,Zn.Wrong);r.if(a,()=>{s.length?kE(t,e,s):hl(t)})}return i}Ze.coerceAndCheckDataType=$E;var o_=new Set(["string","number","integer","boolean","null"]);function SE(t,e){return e?t.filter(r=>o_.has(r)||e==="array"&&r==="array"):[]}function kE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,F._)`typeof ${o}`),a=n.let("coerced",(0,F._)`undefined`);s.coerceTypes==="array"&&n.if((0,F._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,F._)`${o}[0]`).assign(i,(0,F._)`typeof ${o}`).if(ml(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,F._)`${a} !== undefined`);for(let u of r)(o_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),hl(t),n.endIf(),n.if((0,F._)`${a} !== undefined`,()=>{n.assign(o,a),TE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,F._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,F._)`"" + ${o}`).elseIf((0,F._)`${o} === null`).assign(a,(0,F._)`""`);return;case"number":n.elseIf((0,F._)`${i} == "boolean" || ${o} === null
6
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,F._)`+${o}`);return;case"integer":n.elseIf((0,F._)`${i} === "boolean" || ${o} === null
7
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,F._)`+${o}`);return;case"boolean":n.elseIf((0,F._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,F._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,F._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,F._)`${i} === "string" || ${i} === "number"
8
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,F._)`[${o}]`)}}}function TE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,F._)`${e} !== undefined`,()=>t.assign((0,F._)`${e}[${r}]`,n))}function fl(t,e,r,n=Zn.Correct){let o=n===Zn.Correct?F.operators.EQ:F.operators.NEQ,s;switch(t){case"null":return(0,F._)`${e} ${o} null`;case"array":s=(0,F._)`Array.isArray(${e})`;break;case"object":s=(0,F._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,F._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,F._)`typeof ${e} ${o} ${t}`}return n===Zn.Correct?s:(0,F.not)(s);function i(a=F.nil){return(0,F.and)((0,F._)`typeof ${e} == "number"`,a,r?(0,F._)`isFinite(${e})`:F.nil)}}Ze.checkDataType=fl;function ml(t,e,r,n){if(t.length===1)return fl(t[0],e,r,n);let o,s=(0,r_.toHash)(t);if(s.array&&s.object){let i=(0,F._)`typeof ${e} != "object"`;o=s.null?i:(0,F._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=F.nil;s.number&&delete s.integer;for(let i in s)o=(0,F.and)(o,fl(i,e,r,n));return o}Ze.checkDataTypes=ml;var PE={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,F._)`{type: ${t}}`:(0,F._)`{type: ${e}}`};function hl(t){let e=EE(t);(0,bE.reportError)(e,PE)}Ze.reportTypeError=hl;function EE(t){let{gen:e,data:r,schema:n}=t,o=(0,r_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var i_=E(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.assignDefaults=void 0;var qn=B(),RE=oe();function zE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)s_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>s_(t,s,o.default))}Yi.assignDefaults=zE;function s_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,qn._)`${s}${(0,qn.getProperty)(e)}`;if(o){(0,RE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,qn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,qn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,qn._)`${a} = ${(0,qn.stringify)(r)}`)}});var dt=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=B(),gl=oe(),pr=Ht(),CE=oe();function AE(t,e){let{gen:r,data:n,it:o}=t;r.if(_l(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=AE;function IE({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(_l(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=IE;function DE(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=DE;function a_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=a_;function yl(t,e,r){return(0,ge._)`${a_(t)}.call(${e}, ${r})`}ue.isOwnProperty=yl;function OE(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${yl(t,e,r)}`:o}ue.propertyInData=OE;function _l(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(yl(t,e,r))):o}ue.noPropertyInData=_l;function c_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=c_;function ME(t,e){return c_(e).filter(r=>!(0,gl.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=ME;function NE({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[pr.default.instancePath,(0,ge.strConcat)(pr.default.instancePath,s)],[pr.default.parentData,i.parentData],[pr.default.parentDataProperty,i.parentDataProperty],[pr.default.rootData,pr.default.rootData]];i.opts.dynamicRef&&d.push([pr.default.dynamicAnchors,pr.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=NE;var jE=(0,ge._)`new RegExp`;function LE({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?jE:(0,CE.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=LE;function ZE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:gl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=ZE;function qE(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,gl.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=qE});var d_=E(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;var Ve=B(),Xr=Ht(),FE=dt(),UE=ns();function VE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=l_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ct.macroKeywordCode=VE;function WE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;HE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=l_(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)y(),e.modifying&&u_(t),m(()=>t.error());else{let b=e.async?f():g();e.modifying&&u_(t),m(()=>BE(t,b))}}function f(){let b=n.let("ruleErrs",null);return n.try(()=>y((0,Ve._)`await `),_=>n.assign(d,!1).if((0,Ve._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,Ve._)`${_}.errors`),()=>n.throw(_))),b}function g(){let b=(0,Ve._)`${l}.errors`;return n.assign(b,null),y(Ve.nil),b}function y(b=e.async?(0,Ve._)`await `:Ve.nil){let _=c.opts.passContext?Xr.default.this:Xr.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ve._)`${b}${(0,FE.callValidateCode)(t,l,_,w)}`,e.modifying)}function m(b){var _;n.if((0,Ve.not)((_=e.valid)!==null&&_!==void 0?_:d),b)}}Ct.funcKeywordCode=WE;function u_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function BE(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(Xr.default.vErrors,(0,Ve._)`${Xr.default.vErrors} === null ? ${e} : ${Xr.default.vErrors}.concat(${e})`).assign(Xr.default.errors,(0,Ve._)`${Xr.default.vErrors}.length`),(0,UE.extendErrors)(t)},()=>t.error())}function HE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function l_(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function GE(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ct.validSchemaType=GE;function JE({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ct.validateKeywordUsage=JE});var f_=E(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.extendSubschemaMode=fr.extendSubschemaData=fr.getSubschema=void 0;var At=B(),p_=oe();function KE(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,At._)`${t.schemaPath}${(0,At.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,At._)`${t.schemaPath}${(0,At.getProperty)(e)}${(0,At.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,p_.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}fr.getSubschema=KE;function QE(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,At._)`${e.data}${(0,At.getProperty)(r)}`,!0);c(p),t.errorPath=(0,At.str)`${u}${(0,p_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,At._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof At.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}fr.extendSubschemaData=QE;function YE(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}fr.extendSubschemaMode=YE});var vl=E((VF,m_)=>{"use strict";m_.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var g_=E((WF,h_)=>{"use strict";var mr=h_.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Xi(e,n,o,t,"",t)};mr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};mr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};mr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};mr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Xi(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in mr.arrayKeywords)for(var p=0;p<d.length;p++)Xi(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in mr.propsKeywords){if(d&&typeof d=="object")for(var f in d)Xi(t,e,r,d[f],o+"/"+l+"/"+XE(f),s,o,l,n,f)}else(l in mr.keywords||t.allKeys&&!(l in mr.skipKeywords))&&Xi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function XE(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ss=E(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.getSchemaRefs=Ye.resolveUrl=Ye.normalizeId=Ye._getFullPath=Ye.getFullPath=Ye.inlineRef=void 0;var eR=oe(),tR=vl(),rR=g_(),nR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function oR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!xl(t):e?y_(t)<=e:!1}Ye.inlineRef=oR;var sR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function xl(t){for(let e in t){if(sR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(xl)||typeof r=="object"&&xl(r))return!0}return!1}function y_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!nR.has(r)&&(typeof t[r]=="object"&&(0,eR.eachItem)(t[r],n=>e+=y_(n)),e===1/0))return 1/0}return e}function __(t,e="",r){r!==!1&&(e=Fn(e));let n=t.parse(e);return v_(t,n)}Ye.getFullPath=__;function v_(t,e){return t.serialize(e).split("#")[0]+"#"}Ye._getFullPath=v_;var iR=/#\/?$/;function Fn(t){return t?t.replace(iR,""):""}Ye.normalizeId=Fn;function aR(t,e,r){return r=Fn(r),t.resolve(e,r)}Ye.resolveUrl=aR;var cR=/^[a-z_][-a-z0-9._]*$/i;function uR(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Fn(t[r]||e),s={"":o},i=__(n,o,!1),a={},c=new Set;return rR(t,{allKeys:!0},(d,p,f,g)=>{if(g===void 0)return;let y=i+p,m=s[g];typeof d[r]=="string"&&(m=b.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=m;function b(w){let k=this.opts.uriResolver.resolve;if(w=Fn(m?k(m,w):w),c.has(w))throw l(w);c.add(w);let P=this.refs[w];return typeof P=="string"&&(P=this.refs[P]),typeof P=="object"?u(d,P.schema,w):w!==Fn(y)&&(w[0]==="#"?(u(d,a[w],w),a[w]=d):this.refs[w]=y),w}function _(w){if(typeof w=="string"){if(!cR.test(w))throw new Error(`invalid anchor "${w}"`);b.call(this,`#${w}`)}}}),a;function u(d,p,f){if(p!==void 0&&!tR(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ye.getSchemaRefs=uR});var cs=E(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.getData=hr.KeywordCxt=hr.validateFunctionCode=void 0;var S_=Xy(),x_=os(),wl=pl(),ea=os(),lR=i_(),as=d_(),bl=f_(),I=B(),N=Ht(),dR=ss(),Gt=oe(),is=ns();function pR(t){if(P_(t)&&(E_(t),T_(t))){hR(t);return}k_(t,()=>(0,S_.topBoolOrEmptySchema)(t))}hr.validateFunctionCode=pR;function k_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,I._)`${N.default.data}, ${N.default.valCxt}`,n.$async,()=>{t.code((0,I._)`"use strict"; ${b_(r,o)}`),mR(t,o),t.code(s)}):t.func(e,(0,I._)`${N.default.data}, ${fR(o)}`,n.$async,()=>t.code(b_(r,o)).code(s))}function fR(t){return(0,I._)`{${N.default.instancePath}="", ${N.default.parentData}, ${N.default.parentDataProperty}, ${N.default.rootData}=${N.default.data}${t.dynamicRef?(0,I._)`, ${N.default.dynamicAnchors}={}`:I.nil}}={}`}function mR(t,e){t.if(N.default.valCxt,()=>{t.var(N.default.instancePath,(0,I._)`${N.default.valCxt}.${N.default.instancePath}`),t.var(N.default.parentData,(0,I._)`${N.default.valCxt}.${N.default.parentData}`),t.var(N.default.parentDataProperty,(0,I._)`${N.default.valCxt}.${N.default.parentDataProperty}`),t.var(N.default.rootData,(0,I._)`${N.default.valCxt}.${N.default.rootData}`),e.dynamicRef&&t.var(N.default.dynamicAnchors,(0,I._)`${N.default.valCxt}.${N.default.dynamicAnchors}`)},()=>{t.var(N.default.instancePath,(0,I._)`""`),t.var(N.default.parentData,(0,I._)`undefined`),t.var(N.default.parentDataProperty,(0,I._)`undefined`),t.var(N.default.rootData,N.default.data),e.dynamicRef&&t.var(N.default.dynamicAnchors,(0,I._)`{}`)})}function hR(t){let{schema:e,opts:r,gen:n}=t;k_(t,()=>{r.$comment&&e.$comment&&z_(t),xR(t),n.let(N.default.vErrors,null),n.let(N.default.errors,0),r.unevaluated&&gR(t),R_(t),$R(t)})}function gR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,I._)`${r}.evaluated`),e.if((0,I._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,I._)`${t.evaluated}.props`,(0,I._)`undefined`)),e.if((0,I._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,I._)`${t.evaluated}.items`,(0,I._)`undefined`))}function b_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,I._)`/*# sourceURL=${r} */`:I.nil}function yR(t,e){if(P_(t)&&(E_(t),T_(t))){_R(t,e);return}(0,S_.boolOrEmptySchema)(t,e)}function T_({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function P_(t){return typeof t.schema!="boolean"}function _R(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&z_(t),bR(t),wR(t);let s=n.const("_errs",N.default.errors);R_(t,s),n.var(e,(0,I._)`${s} === ${N.default.errors}`)}function E_(t){(0,Gt.checkUnknownRules)(t),vR(t)}function R_(t,e){if(t.opts.jtd)return w_(t,[],!1,e);let r=(0,x_.getSchemaTypes)(t.schema),n=(0,x_.coerceAndCheckDataType)(t,r);w_(t,r,!n,e)}function vR(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Gt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function xR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Gt.checkStrictMode)(t,"default is ignored in the schema root")}function bR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,dR.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function wR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function z_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,I._)`${N.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,I.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,I._)`${N.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function $R(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,I._)`${N.default.errors} === 0`,()=>e.return(N.default.data),()=>e.throw((0,I._)`new ${o}(${N.default.vErrors})`)):(e.assign((0,I._)`${n}.errors`,N.default.vErrors),s.unevaluated&&SR(t),e.return((0,I._)`${N.default.errors} === 0`))}function SR({gen:t,evaluated:e,props:r,items:n}){r instanceof I.Name&&t.assign((0,I._)`${e}.props`,r),n instanceof I.Name&&t.assign((0,I._)`${e}.items`,n)}function w_(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Gt.schemaHasRulesButRef)(s,l))){o.block(()=>A_(t,"$ref",l.all.$ref.definition));return}c.jtd||kR(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,wl.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ea.checkDataType)(p.type,i,c.strictNumbers)),$_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,ea.reportTypeError)(t)),o.endIf()):$_(t,p),a||o.if((0,I._)`${N.default.errors} === ${n||0}`))}}function $_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,lR.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,wl.shouldUseRule)(n,s)&&A_(t,s.keyword,s.definition,e.type)})}function kR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(TR(t,e),t.opts.allowUnionTypes||PR(t,e),ER(t,t.dataTypes))}function TR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{C_(t.dataTypes,r)||$l(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),zR(t,e)}}function PR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&$l(t,"use allowUnionTypes to allow union type keyword")}function ER(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,wl.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>RR(e,i))&&$l(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function RR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function C_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function zR(t,e){let r=[];for(let n of t.dataTypes)C_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function $l(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Gt.checkStrictMode)(t,e,t.opts.strictTypes)}var ta=class{constructor(e,r,n){if((0,as.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Gt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",I_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,as.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",N.default.errors))}result(e,r,n){this.failResult((0,I.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,I.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,I._)`${r} !== undefined && (${(0,I.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?is.reportExtraError:is.reportError)(this,this.def.error,r)}$dataError(){(0,is.reportError)(this,this.def.$dataError||is.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,is.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=I.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=I.nil,r=I.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,I.or)((0,I._)`${o} === undefined`,r)),e!==I.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==I.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,I.or)(i(),a());function i(){if(n.length){if(!(r instanceof I.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,I._)`${(0,ea.checkDataTypes)(c,r,s.opts.strictNumbers,ea.DataType.Wrong)}`}return I.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,I._)`!${c}(${r})`}return I.nil}}subschema(e,r){let n=(0,bl.getSubschema)(this.it,e);(0,bl.extendSubschemaData)(n,this.it,e),(0,bl.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return yR(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Gt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Gt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,I.Name)),!0}};hr.KeywordCxt=ta;function A_(t,e,r,n){let o=new ta(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,as.funcKeywordCode)(o,r):"macro"in r?(0,as.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,as.funcKeywordCode)(o,r)}var CR=/^\/(?:[^~]|~0|~1)*$/,AR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return N.default.rootData;if(t[0]==="/"){if(!CR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=N.default.rootData}else{let u=AR.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,I._)`${s}${(0,I.getProperty)((0,Gt.unescapeJsonPointer)(u))}`,i=(0,I._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}hr.getData=I_});var ra=E(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});var Sl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kl.default=Sl});var us=E(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var Tl=ss(),Pl=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Tl.resolveUrl)(e,r,n),this.missingSchema=(0,Tl.normalizeId)((0,Tl.getFullPath)(e,this.missingRef))}};El.default=Pl});var oa=E(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.resolveSchema=pt.getCompilingSchema=pt.resolveRef=pt.compileSchema=pt.SchemaEnv=void 0;var xt=B(),IR=ra(),en=Ht(),bt=ss(),D_=oe(),DR=cs(),Un=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,bt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};pt.SchemaEnv=Un;function zl(t){let e=O_.call(this,t);if(e)return e;let r=(0,bt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new xt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:IR.default,code:(0,xt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:en.default.data,parentData:en.default.parentData,parentDataProperty:en.default.parentDataProperty,dataNames:[en.default.data],dataPathArr:[xt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,xt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:xt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,DR.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(en.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${en.default.self}`,`${en.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:g,items:y}=u;f.evaluated={props:g instanceof xt.Name?void 0:g,items:y instanceof xt.Name?void 0:y,dynamicProps:g instanceof xt.Name,dynamicItems:y instanceof xt.Name},f.source&&(f.source.evaluated=(0,xt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}pt.compileSchema=zl;function OR(t,e,r){var n;r=(0,bt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=jR.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Un({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=MR.call(this,s)}pt.resolveRef=OR;function MR(t){return(0,bt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:zl.call(this,t)}function O_(t){for(let e of this._compilations)if(NR(e,t))return e}pt.getCompilingSchema=O_;function NR(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function jR(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||na.call(this,t,e)}function na(t,e){let r=this.opts.uriResolver.parse(e),n=(0,bt._getFullPath)(this.opts.uriResolver,r),o=(0,bt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Rl.call(this,r,t);let s=(0,bt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=na.call(this,t,i);return typeof a?.schema!="object"?void 0:Rl.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||zl.call(this,i),s===(0,bt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,bt.resolveUrl)(this.opts.uriResolver,o,u)),new Un({schema:a,schemaId:c,root:t,baseId:o})}return Rl.call(this,r,i)}}pt.resolveSchema=na;var LR=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Rl(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,D_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!LR.has(a)&&u&&(e=(0,bt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,D_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,bt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=na.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Un({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var M_=E((QF,ZR)=>{ZR.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Al=E((YF,Z_)=>{"use strict";var qR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),j_=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Cl(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var FR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function N_(t){return t.length=0,!0}function UR(t,e,r){if(t.length){let n=Cl(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function VR(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=UR;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=N_}else{o.push(u);continue}}return o.length&&(a===N_?r.zone=o.join(""):i?n.push(o.join("")):n.push(Cl(o))),r.address=n.join(""),r}function L_(t){if(WR(t,":")<2)return{host:t,isIPV6:!1};let e=VR(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function WR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function BR(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function HR(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function GR(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!j_(r)){let n=L_(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Z_.exports={nonSimpleDomain:FR,recomposeAuthority:GR,normalizeComponentEncoding:HR,removeDotSegments:BR,isIPv4:j_,isUUID:qR,normalizeIPv6:L_,stringArrayToHexStripped:Cl}});var W_=E((XF,V_)=>{"use strict";var{isUUID:JR}=Al(),KR=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,QR=["http","https","ws","wss","urn","urn:uuid"];function YR(t){return QR.indexOf(t)!==-1}function Il(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function q_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function F_(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function XR(t){return t.secure=Il(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ez(t){if((t.port===(Il(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function tz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(KR);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Dl(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function rz(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Dl(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function nz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!JR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function oz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var U_={scheme:"http",domainHost:!0,parse:q_,serialize:F_},sz={scheme:"https",domainHost:U_.domainHost,parse:q_,serialize:F_},sa={scheme:"ws",domainHost:!0,parse:XR,serialize:ez},iz={scheme:"wss",domainHost:sa.domainHost,parse:sa.parse,serialize:sa.serialize},az={scheme:"urn",parse:tz,serialize:rz,skipNormalize:!0},cz={scheme:"urn:uuid",parse:nz,serialize:oz,skipNormalize:!0},ia={http:U_,https:sz,ws:sa,wss:iz,urn:az,"urn:uuid":cz};Object.setPrototypeOf(ia,null);function Dl(t){return t&&(ia[t]||ia[t.toLowerCase()])||void 0}V_.exports={wsIsSecure:Il,SCHEMES:ia,isValidSchemeName:YR,getSchemeHandler:Dl}});var G_=E((e9,ca)=>{"use strict";var{normalizeIPv6:uz,removeDotSegments:ls,recomposeAuthority:lz,normalizeComponentEncoding:aa,isIPv4:dz,nonSimpleDomain:pz}=Al(),{SCHEMES:fz,getSchemeHandler:B_}=W_();function mz(t,e){return typeof t=="string"?t=It(Jt(t,e),e):typeof t=="object"&&(t=Jt(It(t,e),e)),t}function hz(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=H_(Jt(t,n),Jt(e,n),n,!0);return n.skipEscape=!0,It(o,n)}function H_(t,e,r,n){let o={};return n||(t=Jt(It(t,r),r),e=Jt(It(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ls(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ls(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ls(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ls(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function gz(t,e,r){return typeof t=="string"?(t=unescape(t),t=It(aa(Jt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=It(aa(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=It(aa(Jt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=It(aa(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function It(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=B_(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=lz(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=ls(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var yz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Jt(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(yz);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(dz(n.host)===!1){let c=uz(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=B_(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&pz(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Ol={SCHEMES:fz,normalize:mz,resolve:hz,resolveComponent:H_,equal:gz,serialize:It,parse:Jt};ca.exports=Ol;ca.exports.default=Ol;ca.exports.fastUri=Ol});var K_=E(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var J_=G_();J_.code='require("ajv/dist/runtime/uri").default';Ml.default=J_});var ov=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var _z=cs();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return _z.KeywordCxt}});var Vn=B();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Vn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Vn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Vn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Vn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Vn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Vn.CodeGen}});var vz=ra(),tv=us(),xz=dl(),ds=oa(),bz=B(),ps=ss(),ua=os(),jl=oe(),Q_=M_(),wz=K_(),rv=(t,e)=>new RegExp(t,e);rv.code="new RegExp";var $z=["removeAdditional","useDefaults","coerceTypes"],Sz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),kz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Tz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Y_=200;function Pz(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,g,y,m,b,_,w,k,P,U,Z,j,Se;let Q=t.strict,sn=(e=t.code)===null||e===void 0?void 0:e.optimize,eo=sn===!0||sn===void 0?1:sn||0,ip=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:rv,qb=(o=t.uriResolver)!==null&&o!==void 0?o:wz.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Q)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Q)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Q)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Q)!==null&&p!==void 0?p:"log",strictRequired:(g=(f=t.strictRequired)!==null&&f!==void 0?f:Q)!==null&&g!==void 0?g:!1,code:t.code?{...t.code,optimize:eo,regExp:ip}:{optimize:eo,regExp:ip},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:Y_,loopEnum:(m=t.loopEnum)!==null&&m!==void 0?m:Y_,meta:(b=t.meta)!==null&&b!==void 0?b:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(P=t.addUsedSchema)!==null&&P!==void 0?P:!0,validateSchema:(U=t.validateSchema)!==null&&U!==void 0?U:!0,validateFormats:(Z=t.validateFormats)!==null&&Z!==void 0?Z:!0,unicodeRegExp:(j=t.unicodeRegExp)!==null&&j!==void 0?j:!0,int32range:(Se=t.int32range)!==null&&Se!==void 0?Se:!0,uriResolver:qb}}var fs=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Pz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new bz.ValueScope({scope:{},prefixes:Sz,es5:r,lines:n}),this.logger=Iz(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,xz.getRules)(),X_.call(this,kz,e,"NOT SUPPORTED"),X_.call(this,Tz,e,"DEPRECATED","warn"),this._metaOpts=Cz.call(this),e.formats&&Rz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&zz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ez.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Q_;n==="id"&&(o={...Q_},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof tv.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ps.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ev.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ds.SchemaEnv({schema:{},schemaId:n});if(r=ds.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ev.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,ps.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Oz.call(this,n,r),!r)return(0,jl.eachItem)(n,s=>Nl.call(this,s)),this;Nz.call(this,r);let o={...r,type:(0,ua.getJSONTypes)(r.type),schemaType:(0,ua.getJSONTypes)(r.schemaType)};return(0,jl.eachItem)(n,o.type.length===0?s=>Nl.call(this,s,o):s=>o.type.forEach(i=>Nl.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=nv(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,ps.normalizeId)(i||n);let u=ps.getSchemaRefs.call(this,e,n);return c=new ds.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ds.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{ds.compileSchema.call(this,e)}finally{this.opts=r}}};fs.ValidationError=vz.default;fs.MissingRefError=tv.default;Ae.default=fs;function X_(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function ev(t){return t=(0,ps.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ez(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Rz(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function zz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function Cz(){let t={...this.opts};for(let e of $z)delete t[e];return t}var Az={log(){},warn(){},error(){}};function Iz(t){if(t===!1)return Az;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Dz=/^[a-z_$][a-z0-9_$:-]*$/i;function Oz(t,e){let{RULES:r}=this;if((0,jl.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Dz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Nl(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ua.getJSONTypes)(e.type),schemaType:(0,ua.getJSONTypes)(e.schemaType)}};e.before?Mz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Mz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Nz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=nv(e)),t.validateSchema=this.compile(e,!0))}var jz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function nv(t){return{anyOf:[t,jz]}}});var sv=E(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var Lz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ll.default=Lz});var uv=E(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.callRef=tn.getValidate=void 0;var Zz=us(),iv=dt(),Xe=B(),Wn=Ht(),av=oa(),la=oe(),qz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=av.resolveRef.call(c,u,o,r);if(l===void 0)throw new Zz.default(n.opts.uriResolver,o,r);if(l instanceof av.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return da(t,i,s,s.$async);let g=e.scopeValue("root",{ref:u});return da(t,(0,Xe._)`${g}.validate`,u,u.$async)}function p(g){let y=cv(t,g);da(t,y,g,g.$async)}function f(g){let y=e.scopeValue("schema",a.code.source===!0?{ref:g,code:(0,Xe.stringify)(g)}:{ref:g}),m=e.name("valid"),b=t.subschema({schema:g,dataTypes:[],schemaPath:Xe.nil,topSchemaRef:y,errSchemaPath:r},m);t.mergeEvaluated(b),t.ok(m)}}};function cv(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Xe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}tn.getValidate=cv;function da(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Wn.default.this:Xe.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let g=o.let("valid");o.try(()=>{o.code((0,Xe._)`await ${(0,iv.callValidateCode)(t,e,u)}`),f(e),i||o.assign(g,!0)},y=>{o.if((0,Xe._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),p(y),i||o.assign(g,!1)}),t.ok(g)}function d(){t.result((0,iv.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(g){let y=(0,Xe._)`${g}.errors`;o.assign(Wn.default.vErrors,(0,Xe._)`${Wn.default.vErrors} === null ? ${y} : ${Wn.default.vErrors}.concat(${y})`),o.assign(Wn.default.errors,(0,Xe._)`${Wn.default.vErrors}.length`)}function f(g){var y;if(!s.opts.unevaluated)return;let m=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=la.mergeEvaluated.props(o,m.props,s.props));else{let b=o.var("props",(0,Xe._)`${g}.evaluated.props`);s.props=la.mergeEvaluated.props(o,b,s.props,Xe.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=la.mergeEvaluated.items(o,m.items,s.items));else{let b=o.var("items",(0,Xe._)`${g}.evaluated.items`);s.items=la.mergeEvaluated.items(o,b,s.items,Xe.Name)}}}tn.callRef=da;tn.default=qz});var lv=E(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var Fz=sv(),Uz=uv(),Vz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Fz.default,Uz.default];Zl.default=Vz});var dv=E(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var pa=B(),gr=pa.operators,fa={maximum:{okStr:"<=",ok:gr.LTE,fail:gr.GT},minimum:{okStr:">=",ok:gr.GTE,fail:gr.LT},exclusiveMaximum:{okStr:"<",ok:gr.LT,fail:gr.GTE},exclusiveMinimum:{okStr:">",ok:gr.GT,fail:gr.LTE}},Wz={message:({keyword:t,schemaCode:e})=>(0,pa.str)`must be ${fa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pa._)`{comparison: ${fa[t].okStr}, limit: ${e}}`},Bz={keyword:Object.keys(fa),type:"number",schemaType:"number",$data:!0,error:Wz,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,pa._)`${r} ${fa[e].fail} ${n} || isNaN(${r})`)}};ql.default=Bz});var pv=E(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var ms=B(),Hz={message:({schemaCode:t})=>(0,ms.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ms._)`{multipleOf: ${t}}`},Gz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Hz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ms._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ms._)`${i} !== parseInt(${i})`;t.fail$data((0,ms._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Fl.default=Gz});var mv=E(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});function fv(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Ul.default=fv;fv.code='require("ajv/dist/runtime/ucs2length").default'});var hv=E(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var rn=B(),Jz=oe(),Kz=mv(),Qz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,rn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,rn._)`{limit: ${t}}`},Yz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Qz,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?rn.operators.GT:rn.operators.LT,i=o.opts.unicode===!1?(0,rn._)`${r}.length`:(0,rn._)`${(0,Jz.useFunc)(t.gen,Kz.default)}(${r})`;t.fail$data((0,rn._)`${i} ${s} ${n}`)}};Vl.default=Yz});var gv=E(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var Xz=dt(),ma=B(),eC={message:({schemaCode:t})=>(0,ma.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ma._)`{pattern: ${t}}`},tC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:eC,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,ma._)`(new RegExp(${o}, ${i}))`:(0,Xz.usePattern)(t,n);t.fail$data((0,ma._)`!${a}.test(${e})`)}};Wl.default=tC});var yv=E(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var hs=B(),rC={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,hs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,hs._)`{limit: ${t}}`},nC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:rC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?hs.operators.GT:hs.operators.LT;t.fail$data((0,hs._)`Object.keys(${r}).length ${o} ${n}`)}};Bl.default=nC});var _v=E(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var gs=dt(),ys=B(),oC=oe(),sC={message:({params:{missingProperty:t}})=>(0,ys.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ys._)`{missingProperty: ${t}}`},iC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:sC,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:g}=t.it;for(let y of r)if(f?.[y]===void 0&&!g.has(y)){let m=i.schemaEnv.baseId+i.errSchemaPath,b=`required property "${y}" is not defined at "${m}" (strictRequired)`;(0,oC.checkStrictMode)(i,b,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ys.nil,d);else for(let f of r)(0,gs.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let g=e.let("valid",!0);t.block$data(g,()=>p(f,g)),t.ok(g)}else e.if((0,gs.checkMissingProp)(t,r,f)),(0,gs.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,gs.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,g){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(g,(0,gs.propertyInData)(e,o,f,a.ownProperties)),e.if((0,ys.not)(g),()=>{t.error(),e.break()})},ys.nil)}}};Hl.default=iC});var vv=E(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var _s=B(),aC={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,_s.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,_s._)`{limit: ${t}}`},cC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:aC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?_s.operators.GT:_s.operators.LT;t.fail$data((0,_s._)`${r}.length ${o} ${n}`)}};Gl.default=cC});var ha=E(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var xv=vl();xv.code='require("ajv/dist/runtime/equal").default';Jl.default=xv});var bv=E(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Kl=os(),Ie=B(),uC=oe(),lC=ha(),dC={message:({params:{i:t,j:e}})=>(0,Ie.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ie._)`{i: ${t}, j: ${e}}`},pC={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:dC,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Kl.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ie._)`${i} === false`),t.ok(c);function l(){let g=e.let("i",(0,Ie._)`${r}.length`),y=e.let("j");t.setParams({i:g,j:y}),e.assign(c,!0),e.if((0,Ie._)`${g} > 1`,()=>(d()?p:f)(g,y))}function d(){return u.length>0&&!u.some(g=>g==="object"||g==="array")}function p(g,y){let m=e.name("item"),b=(0,Kl.checkDataTypes)(u,m,a.opts.strictNumbers,Kl.DataType.Wrong),_=e.const("indices",(0,Ie._)`{}`);e.for((0,Ie._)`;${g}--;`,()=>{e.let(m,(0,Ie._)`${r}[${g}]`),e.if(b,(0,Ie._)`continue`),u.length>1&&e.if((0,Ie._)`typeof ${m} == "string"`,(0,Ie._)`${m} += "_"`),e.if((0,Ie._)`typeof ${_}[${m}] == "number"`,()=>{e.assign(y,(0,Ie._)`${_}[${m}]`),t.error(),e.assign(c,!1).break()}).code((0,Ie._)`${_}[${m}] = ${g}`)})}function f(g,y){let m=(0,uC.useFunc)(e,lC.default),b=e.name("outer");e.label(b).for((0,Ie._)`;${g}--;`,()=>e.for((0,Ie._)`${y} = ${g}; ${y}--;`,()=>e.if((0,Ie._)`${m}(${r}[${g}], ${r}[${y}])`,()=>{t.error(),e.assign(c,!1).break(b)})))}}};Ql.default=pC});var wv=E(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var Yl=B(),fC=oe(),mC=ha(),hC={message:"must be equal to constant",params:({schemaCode:t})=>(0,Yl._)`{allowedValue: ${t}}`},gC={keyword:"const",$data:!0,error:hC,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Yl._)`!${(0,fC.useFunc)(e,mC.default)}(${r}, ${o})`):t.fail((0,Yl._)`${s} !== ${r}`)}};Xl.default=gC});var $v=E(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var vs=B(),yC=oe(),_C=ha(),vC={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,vs._)`{allowedValues: ${t}}`},xC={keyword:"enum",schemaType:"array",$data:!0,error:vC,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,yC.useFunc)(e,_C.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,vs.or)(...o.map((g,y)=>p(f,y)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,vs._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,g){let y=o[g];return typeof y=="object"&&y!==null?(0,vs._)`${u()}(${r}, ${f}[${g}])`:(0,vs._)`${r} === ${y}`}}};ed.default=xC});var Sv=E(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var bC=dv(),wC=pv(),$C=hv(),SC=gv(),kC=yv(),TC=_v(),PC=vv(),EC=bv(),RC=wv(),zC=$v(),CC=[bC.default,wC.default,$C.default,SC.default,kC.default,TC.default,PC.default,EC.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},RC.default,zC.default];td.default=CC});var nd=E(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.validateAdditionalItems=void 0;var nn=B(),rd=oe(),AC={message:({params:{len:t}})=>(0,nn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,nn._)`{limit: ${t}}`},IC={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:AC,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,rd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}kv(t,n)}};function kv(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,nn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,nn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,rd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,nn._)`${a} <= ${e.length}`);r.if((0,nn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:rd.Type.Num},u),i.allErrors||r.if((0,nn.not)(u),()=>r.break())})}}xs.validateAdditionalItems=kv;xs.default=IC});var od=E(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.validateTuple=void 0;var Tv=B(),ga=oe(),DC=dt(),OC={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Pv(t,"additionalItems",e);r.items=!0,!(0,ga.alwaysValidSchema)(r,e)&&t.ok((0,DC.validateArray)(t))}};function Pv(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ga.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Tv._)`${s}.length`);r.forEach((d,p)=>{(0,ga.alwaysValidSchema)(a,d)||(n.if((0,Tv._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,g=r.length,y=g===d.minItems&&(g===d.maxItems||d[e]===!1);if(p.strictTuples&&!y){let m=`"${i}" is ${g}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ga.checkStrictMode)(a,m,p.strictTuples)}}}bs.validateTuple=Pv;bs.default=OC});var Ev=E(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var MC=od(),NC={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,MC.validateTuple)(t,"items")};sd.default=NC});var zv=E(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var Rv=B(),jC=oe(),LC=dt(),ZC=nd(),qC={message:({params:{len:t}})=>(0,Rv.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Rv._)`{limit: ${t}}`},FC={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qC,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,jC.alwaysValidSchema)(n,e)&&(o?(0,ZC.validateAdditionalItems)(t,o):t.ok((0,LC.validateArray)(t)))}};id.default=FC});var Cv=E(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var ft=B(),ya=oe(),UC={message:({params:{min:t,max:e}})=>e===void 0?(0,ft.str)`must contain at least ${t} valid item(s)`:(0,ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ft._)`{minContains: ${t}}`:(0,ft._)`{minContains: ${t}, maxContains: ${e}}`},VC={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:UC,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ya.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ya.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ya.alwaysValidSchema)(s,r)){let y=(0,ft._)`${l} >= ${i}`;a!==void 0&&(y=(0,ft._)`${y} && ${l} <= ${a}`),t.pass(y);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ft._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let y=e.name("_valid"),m=e.let("count",0);f(y,()=>e.if(y,()=>g(m)))}function f(y,m){e.forRange("i",0,l,b=>{t.subschema({keyword:"contains",dataProp:b,dataPropType:ya.Type.Num,compositeRule:!0},y),m()})}function g(y){e.code((0,ft._)`${y}++`),a===void 0?e.if((0,ft._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ft._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ft._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};ad.default=VC});var Dv=E(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.validateSchemaDeps=Dt.validatePropertyDeps=Dt.error=void 0;var cd=B(),WC=oe(),ws=dt();Dt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,cd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,cd._)`{property: ${t},
3
+ var SS=Object.create;var Ic=Object.defineProperty;var $S=Object.getOwnPropertyDescriptor;var kS=Object.getOwnPropertyNames;var PS=Object.getPrototypeOf,TS=Object.prototype.hasOwnProperty;var an=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ze=(t,e)=>{for(var r in e)Ic(t,r,{get:e[r],enumerable:!0})},ES=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kS(e))!TS.call(t,o)&&o!==r&&Ic(t,o,{get:()=>e[o],enumerable:!(n=$S(e,o))||n.enumerable});return t};var Jp=(t,e,r)=>(r=t!=null?SS(PS(t)):{},ES(e||!t||!t.__esModule?Ic(r,"default",{value:t,enumerable:!0}):r,t));var Gp,fo,Yp,Qp,Xp,ef,tf,mo,rf,Us,nf,of,sf,af,cf,uf,qs,Ac,Cc,yN,lf,ln,Dc,zc,df,pf,Vs,xr,Oc,ff,mf,dn,Nt=an(()=>{"use strict";Gp="4.9.0",fo="http://localhost:11434",Yp="llama3",Qp=".agestra/.jobs",Xp=".agestra/traces",ef=".agestra/worktrees",tf=".agestra/sessions",mo=".agestra/workspace",rf="individual",Us="debates",nf="synthesis",of="issue",sf=".agestra/workers",af=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),cf=2,uf=6e4,qs=20,Ac=5e4,Cc=10,yN=Object.freeze([3,5,10]),lf=Object.freeze(["agree","disagree","abstain","revise"]),ln="votes",Dc=2,zc=2,df=1440*60*1e3,pf=3600*1e3,Vs=Object.freeze(["ko","zh","ja","en"]),xr="ko",Oc="en",ff="[REDACTED]",mf=["","--- REQUIRED RESPONSE FORMAT ---","Respond with JSON only, matching exactly this shape:",'{ "agrees": true | false, "feedback": "specific issues or why you agree", "suggestions": "concrete changes if you disagree (optional, may be omitted)" }',"No prose, markdown, or explanation outside the JSON object. The JSON must be the entire response or wrapped in a single ```json code fence.","-------------------------------"].join(`
4
+ `),dn=Object.freeze({auto:Object.freeze({name:"auto",description:"Auto-detect build profile from project structure (package.json scripts, tsconfig, vitest config, etc.).",command:"npx",args:Object.freeze([])}),tsc:Object.freeze({name:"tsc",description:"TypeScript project-references build via `npx tsc -b --noEmit`.",command:"npx",args:Object.freeze(["tsc","-b","--noEmit"])}),vitest:Object.freeze({name:"vitest",description:"Run the Vitest unit-test suite in CI mode.",command:"npx",args:Object.freeze(["vitest","run","--reporter=dot"])}),"npm-build":Object.freeze({name:"npm-build",description:"Run the project's `npm run build` script.",command:"npm",args:Object.freeze(["run","build"])}),"npm-test":Object.freeze({name:"npm-test",description:"Run the project's `npm test` script.",command:"npm",args:Object.freeze(["test","--","--run"])})})});import{execFileSync as RS}from"child_process";function pn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return RS("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0}),{delivered:!0}}catch{try{return process.kill(t),{delivered:!0}}catch{return{delivered:!1}}}try{return process.kill(-t,"SIGTERM"),{delivered:!0}}catch{try{return process.kill(t,"SIGTERM"),{delivered:!0}}catch{return{delivered:!1}}}}function er(t,e=3e3){let r=t.pid;if(r)pn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e)}var ho=an(()=>{"use strict"});import{execFileSync as IS,spawn as AS}from"child_process";import{existsSync as CS}from"fs";function zS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:DS.has(t.toLowerCase())}function OS(t){if(t.includes("\0"))throw new Error(`Windows shim arg contains null byte: ${JSON.stringify(t)}`);if(t.includes("%"))throw new Error(`Windows shim arg contains '%' which would trigger cmd.exe env expansion: ${JSON.stringify(t)}`);return/[\s"&^<>|()!]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function MS(t){let e=t.toLowerCase();if(fn.has(e))return fn.get(e)??null;try{let n=IS("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return fn.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return fn.set(e,a),a}let i=`${n[0]}.ps1`;if(CS(i)){let a={type:"powershell",path:i};return fn.set(e,a),a}}catch{}return fn.set(e,null),null}function Lt(t,e){if(!zS(t))return{command:t,args:e};let r=MS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>OS(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function ze(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c}=t;return new Promise((u,l)=>{let d=Lt(e,r),p=AS(d.command,d.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),f="",m="",g=0,y=0,_=!1,S=null,v=!1,k=()=>{!v&&g+y>a&&(_=!0,v=!0,er(p))};p.stdout.on("data",Z=>{g+=Z.length,g<=a&&(f+=Z.toString()),k()}),p.stderr.on("data",Z=>{y+=Z.length;let De=Z.toString();if(y<=a&&(m+=De),k(),!v&&c){let Y=c(De);Y&&(S=Y,v=!0,er(p))}}),i&&p.stdin&&(p.stdin.write(i),p.stdin.end());let x=()=>{er(p),l(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`))},z=setTimeout(x,n),O=()=>{clearTimeout(z),z=setTimeout(x,n)};p.stdout.on("data",O),p.stderr.on("data",O),p.on("close",Z=>{if(clearTimeout(z),S){l(S);return}u({stdout:f,stderr:m,exitCode:Z??1,truncated:_})}),p.on("error",Z=>{clearTimeout(z),l(new Error(`CLI spawn error: ${Z.message}`))})})}var DS,fn,mn=an(()=>{"use strict";ho();DS=new Set(["codex","gemini","npm","npx"]),fn=new Map});import{writeFileSync as rk,mkdirSync as _o,openSync as Fc,writeSync as Zc,fsyncSync as Rf,closeSync as Uc,renameSync as nk,unlinkSync as ok,appendFileSync as sk}from"fs";import{dirname as bo,join as ik}from"path";import{randomUUID as ak}from"crypto";function se(t,e){let r=bo(t);_o(r,{recursive:!0});let n=ik(r,`.tmp-${ak().slice(0,8)}`);try{rk(n,e,"utf-8"),nk(n,t)}catch(o){try{ok(n)}catch{}throw o}}function Ue(t,e){se(t,JSON.stringify(e,null,2))}function ri(t,e){let r=bo(t);_o(r,{recursive:!0});let n=Fc(t,"a");try{Zc(n,e),Rf(n)}finally{Uc(n)}}var ti,ni=an(()=>{"use strict";ti=class{buffer=new Map;flushTimer=null;flushIntervalMs;maxBufferSize;auditFsync;destroyed=!1;constructor(e){this.flushIntervalMs=e?.flushIntervalMs??2e3,this.maxBufferSize=e?.maxBufferSize??100,this.auditFsync=e?.auditFsync??!0,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer&&typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}append(e,r,n){if(this.destroyed)throw new Error("DurableAppendWriter has been destroyed");if(n==="audit"){if(this.auditFsync)ri(e,r);else{let s=bo(e);_o(s,{recursive:!0}),sk(e,r)}return}let o=this.buffer.get(e);o||(o=[],this.buffer.set(e,o)),o.push(r),o.length>=this.maxBufferSize&&this.flushFile(e),this.flushIntervalMs===0&&this.flushFile(e)}flush(){for(let e of this.buffer.keys())this.flushFile(e)}panicFlush(){for(let[e,r]of this.buffer)if(r.length!==0)try{let n=bo(e);_o(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join("")),Rf(o)}finally{Uc(o)}}catch{}this.buffer.clear()}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush())}flushFile(e){let r=this.buffer.get(e);if(!r||r.length===0)return;let n=bo(e);_o(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join(""))}finally{Uc(o)}this.buffer.delete(e)}}});import{existsSync as If,realpathSync as ck}from"fs";import{basename as uk,dirname as lk,isAbsolute as Df,join as dk,normalize as pk,resolve as qc,relative as fk}from"path";function mk(t){return t===""||!t.startsWith("..")&&!Df(t)}function Af(t){let e=[],r=qc(t);for(;!If(r);){let o=lk(r);if(o===r)break;e.unshift(uk(r)),r=o}let n=If(r)?ck(r):r;return e.reduce((o,s)=>dk(o,s),n)}function zf(t,e){let r=Af(e),n=Af(t),o=fk(r,n);return mk(o)}function Vc(t,e){let r=qc(e,t);return zf(r,e)}function ht(t,e){let r=qc(e,t);if(!zf(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Me(t,e){if(t.length===0)throw new Error("Filename must not be empty");if(t.includes("\0"))throw new Error(`Filename contains null byte: ${JSON.stringify(t)}`);if(t.includes("/")||t.includes("\\"))throw new Error(`Filename must not contain path separators: ${JSON.stringify(t)}`);if(t.includes(".."))throw new Error(`Filename must not contain '..': ${JSON.stringify(t)}`);return ht(t,e)}function Bt(t,e){if(Df(t)){let r=pk(t);if(!Vc(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return ht(t,e)}function oi(t){return hk.test(t)}function si(t,e){if(!t||typeof t!="string")throw new tt(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new tt(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new tt(t,"command must not contain path separators");if(!Cf.has(t))throw new tt(t,`command is not in the allowlist (${[...Cf].join(", ")})`);for(let r of e){if(typeof r!="string")throw new tt(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new tt(t,`arg contains null byte: ${JSON.stringify(r)}`);if(gk.has(r))throw new tt(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var hk,Cf,gk,tt,wo=an(()=>{"use strict";hk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Cf=new Set(["gemini","codex","npx","node","npm","tsc"]),gk=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),tt=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});var jf={};Ze(jf,{CLI_PROVIDERS:()=>Of,resolveCliConfig:()=>Mf});import{readFileSync as Bc}from"fs";import{join as rt}from"path";import{spawn as yk}from"child_process";function Mf(t){let e=vk[t.provider]??t.provider;return Of[e]??null}function Fr(t,e){let r=rt(t,"status.json"),n=JSON.parse(Bc(r,"utf-8"));Ue(r,{...n,...e})}async function _k(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(Bc(rt(t,"job.json"),"utf-8"))}catch{try{Ue(rt(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Mf(e);r||(Fr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Fr(t,{state:"running",startedAt:new Date().toISOString()});let s=Bc(rt(t,"prompt.txt"),"utf-8"),i=o(s);try{si(n,i)}catch(c){let u=c instanceof tt?c.message:`Argv rejected: ${c.message}`;Fr(t,{state:"error",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),u);return}let a;if(e.cwd)try{a=ht(e.cwd,process.cwd())}catch(c){Fr(t,{state:"error",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Lt(n,i),l=yk(u.command,u.args,{cwd:a,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",y=>{f+=y.length,f<=10485760&&(d+=y.toString())}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let g=setTimeout(()=>{er(l),se(rt(t,"output.txt"),d),se(rt(t,"error.txt"),p),Fr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",y=>{clearTimeout(g),se(rt(t,"output.txt"),d),se(rt(t,"error.txt"),p);let _=d.trim().length>0;Fr(t,{state:y===0||_?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()}),c()}),l.on("error",y=>{clearTimeout(g);let _=y.code==="ENOENT"?"missing_cli":"error";se(rt(t,"error.txt"),y.message),Fr(t,{state:_,completedAt:new Date().toISOString()}),c()})})}var vk,Of,bk,Nf=an(()=>{"use strict";ni();ho();wo();mn();vk={"gemini-cli":"gemini","codex-cli":"codex"},Of={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--full-auto","--ephemeral",t]}};bk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");bk&&_k().catch(()=>process.exit(1))});var as=E(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.regexpCode=ne.getEsmExportName=ne.getProperty=ne.safeStringify=ne.stringify=ne.strConcat=ne.addCodeArg=ne.str=ne._=ne.nil=ne._Code=ne.Name=ne.IDENTIFIER=ne._CodeOrName=void 0;var ss=class{};ne._CodeOrName=ss;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gr=class extends ss{constructor(e){if(super(),!ne.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ne.Name=Gr;var lt=class extends ss{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Gr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ne._Code=lt;ne.nil=new lt("");function Nv(t,...e){let r=[t[0]],n=0;for(;n<e.length;)$l(r,e[n]),r.push(t[++n]);return new lt(r)}ne._=Nv;var Sl=new lt("+");function Lv(t,...e){let r=[is(t[0])],n=0;for(;n<e.length;)r.push(Sl),$l(r,e[n]),r.push(Sl,is(t[++n]));return yR(r),new lt(r)}ne.str=Lv;function $l(t,e){e instanceof lt?t.push(...e._items):e instanceof Gr?t.push(e):t.push(bR(e))}ne.addCodeArg=$l;function yR(t){let e=1;for(;e<t.length-1;){if(t[e]===Sl){let r=vR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function vR(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Gr||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Gr))return`"${t}${e.slice(1)}`}function _R(t,e){return e.emptyStr()?t:t.emptyStr()?e:Lv`${t}${e}`}ne.strConcat=_R;function bR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:is(Array.isArray(t)?t.join(","):t)}function wR(t){return new lt(is(t))}ne.stringify=wR;function is(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ne.safeStringify=is;function xR(t){return typeof t=="string"&&ne.IDENTIFIER.test(t)?new lt(`.${t}`):Nv`[${t}]`}ne.getProperty=xR;function SR(t){if(typeof t=="string"&&ne.IDENTIFIER.test(t))return new lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ne.getEsmExportName=SR;function $R(t){return new lt(t.toString())}ne.regexpCode=$R});var Tl=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ye=as(),kl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},da;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(da||(Qe.UsedValueState=da={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var pa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=pa;var fa=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Qe.ValueScopeName=fa;var kR=(0,Ye._)`\n`,Pl=class extends pa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?kR:Ye.nil}}get(){return this._scope}name(e){return new fa(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,da.Started);let l=r(u);if(l){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ye._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ye._)`${s}${l}${this.opts._n}`;else throw new kl(u);c.set(u,da.Completed)})}return s}};Qe.ValueScope=Pl});var H=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var te=as(),_t=Tl(),fr=as();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return fr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return fr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return fr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return fr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return fr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return fr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return fr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return fr.Name}});var ya=Tl();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return ya.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return ya.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return ya.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return ya.varKinds}});K.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Kt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},El=class extends Kt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?_t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Un(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},ma=class extends Kt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Un(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return ga(e,this.rhs)}},Rl=class extends ma{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Il=class extends Kt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Al=class extends Kt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Cl=class extends Kt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Dl=class extends Kt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Un(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},cs=class extends Kt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(PR(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Xr(e,r.names),{})}},Jt=class extends cs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zl=class extends cs{},Zn=class extends Jt{};Zn.kind="else";var Yr=class t extends Jt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Zn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Fv(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Un(this.condition,e,r),this}get names(){let e=super.names;return ga(e,this.condition),this.else&&Xr(e,this.else.names),e}};Yr.kind="if";var Qr=class extends Jt{};Qr.kind="for";var Ol=class extends Qr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Un(this.iteration,e,r),this}get names(){return Xr(super.names,this.iteration.names)}},Ml=class extends Qr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?_t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ga(super.names,this.from);return ga(e,this.to)}},ha=class extends Qr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Un(this.iterable,e,r),this}get names(){return Xr(super.names,this.iterable.names)}},us=class extends Jt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};us.kind="func";var ls=class extends cs{render(e){return"return "+super.render(e)}};ls.kind="return";var jl=class extends Jt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Xr(e,this.catch.names),this.finally&&Xr(e,this.finally.names),e}},ds=class extends Jt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ds.kind="catch";var ps=class extends Jt{render(e){return"finally"+super.render(e)}};ps.kind="finally";var Nl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
5
+ `:""},this._extScope=e,this._scope=new _t.Scope({parent:e}),this._nodes=[new zl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new El(e,s,n)),s}const(e,r,n){return this._def(_t.varKinds.const,e,r,n)}let(e,r,n){return this._def(_t.varKinds.let,e,r,n)}var(e,r,n){return this._def(_t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ma(e,r,n))}add(e,r){return this._leafNode(new Rl(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Dl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new Yr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Yr(e))}else(){return this._elseNode(new Zn)}endIf(){return this._endBlockNode(Yr,Zn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ol(e),r)}forRange(e,r,n,o,s=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let i=this._scope.toName(e);return this._for(new Ml(s,i,r,n),()=>o(i))}forOf(e,r,n,o=_t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new ha("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new ha("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Qr)}label(e){return this._leafNode(new Il(e))}break(e){return this._leafNode(new Al(e))}return(e){let r=new ls;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ls)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new jl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ds(s),r(s)}return n&&(this._currNode=o.finally=new ps,this.code(n)),this._endBlockNode(ds,ps)}throw(e){return this._leafNode(new Cl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=te.nil,n,o){return this._blockNode(new us(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(us)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Yr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=Nl;function Xr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ga(t,e){return e instanceof te._CodeOrName?Xr(t,e.names):t}function Un(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function PR(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Fv(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${Ll(t)}`}K.not=Fv;var TR=Zv(K.operators.AND);function ER(...t){return t.reduce(TR)}K.and=ER;var RR=Zv(K.operators.OR);function IR(...t){return t.reduce(RR)}K.or=IR;function Zv(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${Ll(e)} ${t} ${Ll(r)}`}function Ll(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var oe=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var le=H(),AR=as();function CR(t){let e={};for(let r of t)e[r]=!0;return e}J.toHash=CR;function DR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vv(t,e),!Bv(e,t.self.RULES.all))}J.alwaysValidSchema=DR;function Vv(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Kv(t,`unknown keyword: "${s}"`)}J.checkUnknownRules=Vv;function Bv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}J.schemaHasRules=Bv;function zR(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}J.schemaHasRulesButRef=zR;function OR({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}J.schemaRefOrVal=OR;function MR(t){return Wv(decodeURIComponent(t))}J.unescapeFragment=MR;function jR(t){return encodeURIComponent(Zl(t))}J.escapeFragment=jR;function Zl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=Zl;function Wv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=Wv;function NR(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}J.eachItem=NR;function Uv({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}J.mergeEvaluated={props:Uv({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),Ul(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Hv}),items:Uv({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Hv(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&Ul(t,r,e),r}J.evaluatedPropsToName=Hv;function Ul(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}J.setEvaluated=Ul;var qv={};function LR(t,e){return t.scopeValue("func",{ref:e,code:qv[e.code]||(qv[e.code]=new AR._Code(e.code))})}J.useFunc=LR;var Fl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Fl||(J.Type=Fl={}));function FR(t,e,r){if(t instanceof le.Name){let n=e===Fl.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+Zl(t)}J.getErrorPath=FR;function Kv(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}J.checkStrictMode=Kv});var Gt=E(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var Ne=H(),ZR={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};ql.default=ZR});var fs=E(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var re=H(),va=oe(),Be=Gt();Le.keywordError={message:({keyword:t})=>(0,re.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,re.str)`"${t}" keyword must be ${e} ($data)`:(0,re.str)`"${t}" keyword is invalid ($data)`};function UR(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Yv(t,e,r);n??(i||a)?Jv(s,c):Gv(o,(0,re._)`[${c}]`)}Le.reportError=UR;function qR(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Yv(t,e,r);Jv(o,a),s||i||Gv(n,Be.default.vErrors)}Le.reportExtraError=qR;function VR(t,e){t.assign(Be.default.errors,e),t.if((0,re._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,re._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Le.resetErrorsCount=VR;function BR({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Be.default.errors,a=>{t.const(i,(0,re._)`${Be.default.vErrors}[${a}]`),t.if((0,re._)`${i}.instancePath === undefined`,()=>t.assign((0,re._)`${i}.instancePath`,(0,re.strConcat)(Be.default.instancePath,s.errorPath))),t.assign((0,re._)`${i}.schemaPath`,(0,re.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,re._)`${i}.schema`,r),t.assign((0,re._)`${i}.data`,n))})}Le.extendErrors=BR;function Jv(t,e){let r=t.const("err",e);t.if((0,re._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Be.default.vErrors}.push(${r})`),t.code((0,re._)`${Be.default.errors}++`)}function Gv(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,re._)`new ${t.ValidationError}(${e})`):(r.assign((0,re._)`${n}.errors`,e),r.return(!1))}var en={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function Yv(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:WR(t,e,r)}function WR(t,e,r={}){let{gen:n,it:o}=t,s=[HR(o,r),KR(t,r)];return JR(t,e,s),n.object(...s)}function HR({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,va.getErrorPath)(e,va.Type.Str)}`:t;return[Be.default.instancePath,(0,re.strConcat)(Be.default.instancePath,r)]}function KR({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,re.str)`${e}/${t}`;return r&&(o=(0,re.str)`${o}${(0,va.getErrorPath)(r,va.Type.Str)}`),[en.schemaPath,o]}function JR(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([en.keyword,o],[en.params,typeof e=="function"?e(t):e||(0,re._)`{}`]),c.messages&&n.push([en.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([en.schema,i],[en.parentSchema,(0,re._)`${l}${d}`],[Be.default.data,s]),u&&n.push([en.propertyName,u])}});var Xv=E(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.boolOrEmptySchema=qn.topBoolOrEmptySchema=void 0;var GR=fs(),YR=H(),QR=Gt(),XR={message:"boolean schema is false"};function eI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Qv(t,!1):typeof r=="object"&&r.$async===!0?e.return(QR.default.data):(e.assign((0,YR._)`${n}.errors`,null),e.return(!0))}qn.topBoolOrEmptySchema=eI;function tI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Qv(t)):r.var(e,!0)}qn.boolOrEmptySchema=tI;function Qv(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,GR.reportError)(o,XR,void 0,e)}});var Vl=E(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.getRules=Vn.isJSONType=void 0;var rI=["string","number","integer","boolean","null","object","array"],nI=new Set(rI);function oI(t){return typeof t=="string"&&nI.has(t)}Vn.isJSONType=oI;function sI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Vn.getRules=sI});var Bl=E(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.shouldUseRule=mr.shouldUseGroup=mr.schemaHasRulesForType=void 0;function iI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&e_(t,n)}mr.schemaHasRulesForType=iI;function e_(t,e){return e.rules.some(r=>t_(t,r))}mr.shouldUseGroup=e_;function t_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}mr.shouldUseRule=t_});var ms=E(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.reportTypeError=Fe.checkDataTypes=Fe.checkDataType=Fe.coerceAndCheckDataType=Fe.getJSONTypes=Fe.getSchemaTypes=Fe.DataType=void 0;var aI=Vl(),cI=Bl(),uI=fs(),q=H(),r_=oe(),Bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bn||(Fe.DataType=Bn={}));function lI(t){let e=n_(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Fe.getSchemaTypes=lI;function n_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(aI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=n_;function dI(t,e){let{gen:r,data:n,opts:o}=t,s=pI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,cI.schemaHasRulesForType)(t,e[0]));if(i){let a=Hl(e,n,o.strictNumbers,Bn.Wrong);r.if(a,()=>{s.length?fI(t,e,s):Kl(t)})}return i}Fe.coerceAndCheckDataType=dI;var o_=new Set(["string","number","integer","boolean","null"]);function pI(t,e){return e?t.filter(r=>o_.has(r)||e==="array"&&r==="array"):[]}function fI(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(Hl(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(o_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Kl(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),mI(t,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
6
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,q._)`+${o}`);return;case"integer":n.elseIf((0,q._)`${i} === "boolean" || ${o} === null
7
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,q._)`+${o}`);return;case"boolean":n.elseIf((0,q._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,q._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,q._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,q._)`${i} === "string" || ${i} === "number"
8
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function mI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function Wl(t,e,r,n=Bn.Correct){let o=n===Bn.Correct?q.operators.EQ:q.operators.NEQ,s;switch(t){case"null":return(0,q._)`${e} ${o} null`;case"array":s=(0,q._)`Array.isArray(${e})`;break;case"object":s=(0,q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${e} ${o} ${t}`}return n===Bn.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${e} == "number"`,a,r?(0,q._)`isFinite(${e})`:q.nil)}}Fe.checkDataType=Wl;function Hl(t,e,r,n){if(t.length===1)return Wl(t[0],e,r,n);let o,s=(0,r_.toHash)(t);if(s.array&&s.object){let i=(0,q._)`typeof ${e} != "object"`;o=s.null?i:(0,q._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,Wl(i,e,r,n));return o}Fe.checkDataTypes=Hl;var hI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function Kl(t){let e=gI(t);(0,uI.reportError)(e,hI)}Fe.reportTypeError=Kl;function gI(t){let{gen:e,data:r,schema:n}=t,o=(0,r_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var i_=E(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.assignDefaults=void 0;var Wn=H(),yI=oe();function vI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)s_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>s_(t,s,o.default))}_a.assignDefaults=vI;function s_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Wn._)`${s}${(0,Wn.getProperty)(e)}`;if(o){(0,yI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Wn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Wn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Wn._)`${a} = ${(0,Wn.stringify)(r)}`)}});var dt=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),Jl=oe(),hr=Gt(),_I=oe();function bI(t,e){let{gen:r,data:n,it:o}=t;r.if(Yl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=bI;function wI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Yl(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=wI;function xI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=xI;function a_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=a_;function Gl(t,e,r){return(0,ge._)`${a_(t)}.call(${e}, ${r})`}ue.isOwnProperty=Gl;function SI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Gl(t,e,r)}`:o}ue.propertyInData=SI;function Yl(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Gl(t,e,r))):o}ue.noPropertyInData=Yl;function c_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=c_;function $I(t,e){return c_(e).filter(r=>!(0,Jl.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=$I;function kI({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[hr.default.instancePath,(0,ge.strConcat)(hr.default.instancePath,s)],[hr.default.parentData,i.parentData],[hr.default.parentDataProperty,i.parentDataProperty],[hr.default.rootData,hr.default.rootData]];i.opts.dynamicRef&&d.push([hr.default.dynamicAnchors,hr.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=kI;var PI=(0,ge._)`new RegExp`;function TI({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?PI:(0,_I.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=TI;function EI(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Jl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=EI;function RI(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Jl.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=RI});var d_=E(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;var We=H(),tn=Gt(),II=dt(),AI=fs();function CI(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=l_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ct.macroKeywordCode=CI;function DI(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;OI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=l_(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&u_(t),y(()=>t.error());else{let _=e.async?f():m();e.modifying&&u_(t),y(()=>zI(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,We._)`await `),S=>n.assign(d,!1).if((0,We._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,We._)`${S}.errors`),()=>n.throw(S))),_}function m(){let _=(0,We._)`${l}.errors`;return n.assign(_,null),g(We.nil),_}function g(_=e.async?(0,We._)`await `:We.nil){let S=c.opts.passContext?tn.default.this:tn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${_}${(0,II.callValidateCode)(t,l,S,v)}`,e.modifying)}function y(_){var S;n.if((0,We.not)((S=e.valid)!==null&&S!==void 0?S:d),_)}}Ct.funcKeywordCode=DI;function u_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function zI(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(tn.default.vErrors,(0,We._)`${tn.default.vErrors} === null ? ${e} : ${tn.default.vErrors}.concat(${e})`).assign(tn.default.errors,(0,We._)`${tn.default.vErrors}.length`),(0,AI.extendErrors)(t)},()=>t.error())}function OI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function l_(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,We.stringify)(r)})}function MI(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ct.validSchemaType=MI;function jI({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ct.validateKeywordUsage=jI});var f_=E(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.extendSubschemaMode=gr.extendSubschemaData=gr.getSubschema=void 0;var Dt=H(),p_=oe();function NI(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Dt._)`${t.schemaPath}${(0,Dt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Dt._)`${t.schemaPath}${(0,Dt.getProperty)(e)}${(0,Dt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,p_.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}gr.getSubschema=NI;function LI(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Dt._)`${e.data}${(0,Dt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Dt.str)`${u}${(0,p_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Dt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Dt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}gr.extendSubschemaData=LI;function FI(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}gr.extendSubschemaMode=FI});var Ql=E((S4,m_)=>{"use strict";m_.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var g_=E(($4,h_)=>{"use strict";var yr=h_.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};ba(e,n,o,t,"",t)};yr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ba(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in yr.arrayKeywords)for(var p=0;p<d.length;p++)ba(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in yr.propsKeywords){if(d&&typeof d=="object")for(var f in d)ba(t,e,r,d[f],o+"/"+l+"/"+ZI(f),s,o,l,n,f)}else(l in yr.keywords||t.allKeys&&!(l in yr.skipKeywords))&&ba(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function ZI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var hs=E(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var UI=oe(),qI=Ql(),VI=g_(),BI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function WI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Xl(t):e?y_(t)<=e:!1}Xe.inlineRef=WI;var HI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Xl(t){for(let e in t){if(HI.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Xl)||typeof r=="object"&&Xl(r))return!0}return!1}function y_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!BI.has(r)&&(typeof t[r]=="object"&&(0,UI.eachItem)(t[r],n=>e+=y_(n)),e===1/0))return 1/0}return e}function v_(t,e="",r){r!==!1&&(e=Hn(e));let n=t.parse(e);return __(t,n)}Xe.getFullPath=v_;function __(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=__;var KI=/#\/?$/;function Hn(t){return t?t.replace(KI,""):""}Xe.normalizeId=Hn;function JI(t,e,r){return r=Hn(r),t.resolve(e,r)}Xe.resolveUrl=JI;var GI=/^[a-z_][-a-z0-9._]*$/i;function YI(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Hn(t[r]||e),s={"":o},i=v_(n,o,!1),a={},c=new Set;return VI(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,y=s[m];typeof d[r]=="string"&&(y=_.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[p]=y;function _(v){let k=this.opts.uriResolver.resolve;if(v=Hn(y?k(y,v):v),c.has(v))throw l(v);c.add(v);let x=this.refs[v];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,v):v!==Hn(g)&&(v[0]==="#"?(u(d,a[v],v),a[v]=d):this.refs[v]=g),v}function S(v){if(typeof v=="string"){if(!GI.test(v))throw new Error(`invalid anchor "${v}"`);_.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!qI(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Xe.getSchemaRefs=YI});var vs=E(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.getData=vr.KeywordCxt=vr.validateFunctionCode=void 0;var $_=Xv(),b_=ms(),td=Bl(),wa=ms(),QI=i_(),ys=d_(),ed=f_(),D=H(),F=Gt(),XI=hs(),Yt=oe(),gs=fs();function eA(t){if(T_(t)&&(E_(t),P_(t))){nA(t);return}k_(t,()=>(0,$_.topBoolOrEmptySchema)(t))}vr.validateFunctionCode=eA;function k_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,D._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,D._)`"use strict"; ${w_(r,o)}`),rA(t,o),t.code(s)}):t.func(e,(0,D._)`${F.default.data}, ${tA(o)}`,n.$async,()=>t.code(w_(r,o)).code(s))}function tA(t){return(0,D._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,D._)`, ${F.default.dynamicAnchors}={}`:D.nil}}={}`}function rA(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,D._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,D._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,D._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,D._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,D._)`""`),t.var(F.default.parentData,(0,D._)`undefined`),t.var(F.default.parentDataProperty,(0,D._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`{}`)})}function nA(t){let{schema:e,opts:r,gen:n}=t;k_(t,()=>{r.$comment&&e.$comment&&I_(t),cA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&oA(t),R_(t),dA(t)})}function oA(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,D._)`${r}.evaluated`),e.if((0,D._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,D._)`${t.evaluated}.props`,(0,D._)`undefined`)),e.if((0,D._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,D._)`${t.evaluated}.items`,(0,D._)`undefined`))}function w_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function sA(t,e){if(T_(t)&&(E_(t),P_(t))){iA(t,e);return}(0,$_.boolOrEmptySchema)(t,e)}function P_({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function T_(t){return typeof t.schema!="boolean"}function iA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&I_(t),uA(t),lA(t);let s=n.const("_errs",F.default.errors);R_(t,s),n.var(e,(0,D._)`${s} === ${F.default.errors}`)}function E_(t){(0,Yt.checkUnknownRules)(t),aA(t)}function R_(t,e){if(t.opts.jtd)return x_(t,[],!1,e);let r=(0,b_.getSchemaTypes)(t.schema),n=(0,b_.coerceAndCheckDataType)(t,r);x_(t,r,!n,e)}function aA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Yt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function cA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Yt.checkStrictMode)(t,"default is ignored in the schema root")}function uA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,XI.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function lA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function I_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,D._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,D.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,D._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function dA(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,D._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,D._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,D._)`${n}.errors`,F.default.vErrors),s.unevaluated&&pA(t),e.return((0,D._)`${F.default.errors} === 0`))}function pA({gen:t,evaluated:e,props:r,items:n}){r instanceof D.Name&&t.assign((0,D._)`${e}.props`,r),n instanceof D.Name&&t.assign((0,D._)`${e}.items`,n)}function x_(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Yt.schemaHasRulesButRef)(s,l))){o.block(()=>C_(t,"$ref",l.all.$ref.definition));return}c.jtd||fA(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,td.shouldUseGroup)(s,p)&&(p.type?(o.if((0,wa.checkDataType)(p.type,i,c.strictNumbers)),S_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,wa.reportTypeError)(t)),o.endIf()):S_(t,p),a||o.if((0,D._)`${F.default.errors} === ${n||0}`))}}function S_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,QI.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,td.shouldUseRule)(n,s)&&C_(t,s.keyword,s.definition,e.type)})}function fA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(mA(t,e),t.opts.allowUnionTypes||hA(t,e),gA(t,t.dataTypes))}function mA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{A_(t.dataTypes,r)||rd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),vA(t,e)}}function hA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&rd(t,"use allowUnionTypes to allow union type keyword")}function gA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,td.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>yA(e,i))&&rd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function yA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function A_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function vA(t,e){let r=[];for(let n of t.dataTypes)A_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function rd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Yt.checkStrictMode)(t,e,t.opts.strictTypes)}var xa=class{constructor(e,r,n){if((0,ys.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Yt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",D_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ys.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",F.default.errors))}result(e,r,n){this.failResult((0,D.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,D.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?gs.reportExtraError:gs.reportError)(this,this.def.error,r)}$dataError(){(0,gs.reportError)(this,this.def.$dataError||gs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,gs.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=D.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,D.or)((0,D._)`${o} === undefined`,r)),e!==D.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==D.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,D.or)(i(),a());function i(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,wa.checkDataTypes)(c,r,s.opts.strictNumbers,wa.DataType.Wrong)}`}return D.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(e,r){let n=(0,ed.getSubschema)(this.it,e);(0,ed.extendSubschemaData)(n,this.it,e),(0,ed.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return sA(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Yt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Yt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,D.Name)),!0}};vr.KeywordCxt=xa;function C_(t,e,r,n){let o=new xa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ys.funcKeywordCode)(o,r):"macro"in r?(0,ys.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ys.funcKeywordCode)(o,r)}var _A=/^\/(?:[^~]|~0|~1)*$/,bA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function D_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!_A.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=bA.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,D._)`${s}${(0,D.getProperty)((0,Yt.unescapeJsonPointer)(u))}`,i=(0,D._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}vr.getData=D_});var Sa=E(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var nd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};od.default=nd});var _s=E(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var sd=hs(),id=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,sd.resolveUrl)(e,r,n),this.missingSchema=(0,sd.normalizeId)((0,sd.getFullPath)(e,this.missingRef))}};ad.default=id});var ka=E(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.resolveSchema=pt.getCompilingSchema=pt.resolveRef=pt.compileSchema=pt.SchemaEnv=void 0;var bt=H(),wA=Sa(),rn=Gt(),wt=hs(),z_=oe(),xA=vs(),Kn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,wt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};pt.SchemaEnv=Kn;function ud(t){let e=O_.call(this,t);if(e)return e;let r=(0,wt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new bt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:wA.default,code:(0,bt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:rn.default.data,parentData:rn.default.parentData,parentDataProperty:rn.default.parentDataProperty,dataNames:[rn.default.data],dataPathArr:[bt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,bt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:bt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,bt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,xA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(rn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${rn.default.self}`,`${rn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof bt.Name?void 0:m,items:g instanceof bt.Name?void 0:g,dynamicProps:m instanceof bt.Name,dynamicItems:g instanceof bt.Name},f.source&&(f.source.evaluated=(0,bt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}pt.compileSchema=ud;function SA(t,e,r){var n;r=(0,wt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=PA.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Kn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=$A.call(this,s)}pt.resolveRef=SA;function $A(t){return(0,wt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ud.call(this,t)}function O_(t){for(let e of this._compilations)if(kA(e,t))return e}pt.getCompilingSchema=O_;function kA(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function PA(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||$a.call(this,t,e)}function $a(t,e){let r=this.opts.uriResolver.parse(e),n=(0,wt._getFullPath)(this.opts.uriResolver,r),o=(0,wt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return cd.call(this,r,t);let s=(0,wt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=$a.call(this,t,i);return typeof a?.schema!="object"?void 0:cd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ud.call(this,i),s===(0,wt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,wt.resolveUrl)(this.opts.uriResolver,o,u)),new Kn({schema:a,schemaId:c,root:t,baseId:o})}return cd.call(this,r,i)}}pt.resolveSchema=$a;var TA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function cd(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,z_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!TA.has(a)&&u&&(e=(0,wt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,z_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,wt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=$a.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Kn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var M_=E((I4,EA)=>{EA.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var dd=E((A4,F_)=>{"use strict";var RA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),N_=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function ld(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var IA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function j_(t){return t.length=0,!0}function AA(t,e,r){if(t.length){let n=ld(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function CA(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=AA;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=j_}else{o.push(u);continue}}return o.length&&(a===j_?r.zone=o.join(""):i?n.push(o.join("")):n.push(ld(o))),r.address=n.join(""),r}function L_(t){if(DA(t,":")<2)return{host:t,isIPV6:!1};let e=CA(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function DA(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function zA(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function OA(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function MA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!N_(r)){let n=L_(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}F_.exports={nonSimpleDomain:IA,recomposeAuthority:MA,normalizeComponentEncoding:OA,removeDotSegments:zA,isIPv4:N_,isUUID:RA,normalizeIPv6:L_,stringArrayToHexStripped:ld}});var B_=E((C4,V_)=>{"use strict";var{isUUID:jA}=dd(),NA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,LA=["http","https","ws","wss","urn","urn:uuid"];function FA(t){return LA.indexOf(t)!==-1}function pd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Z_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function U_(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ZA(t){return t.secure=pd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function UA(t){if((t.port===(pd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function qA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(NA);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=fd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function VA(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=fd(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function BA(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!jA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function WA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var q_={scheme:"http",domainHost:!0,parse:Z_,serialize:U_},HA={scheme:"https",domainHost:q_.domainHost,parse:Z_,serialize:U_},Pa={scheme:"ws",domainHost:!0,parse:ZA,serialize:UA},KA={scheme:"wss",domainHost:Pa.domainHost,parse:Pa.parse,serialize:Pa.serialize},JA={scheme:"urn",parse:qA,serialize:VA,skipNormalize:!0},GA={scheme:"urn:uuid",parse:BA,serialize:WA,skipNormalize:!0},Ta={http:q_,https:HA,ws:Pa,wss:KA,urn:JA,"urn:uuid":GA};Object.setPrototypeOf(Ta,null);function fd(t){return t&&(Ta[t]||Ta[t.toLowerCase()])||void 0}V_.exports={wsIsSecure:pd,SCHEMES:Ta,isValidSchemeName:FA,getSchemeHandler:fd}});var K_=E((D4,Ra)=>{"use strict";var{normalizeIPv6:YA,removeDotSegments:bs,recomposeAuthority:QA,normalizeComponentEncoding:Ea,isIPv4:XA,nonSimpleDomain:eC}=dd(),{SCHEMES:tC,getSchemeHandler:W_}=B_();function rC(t,e){return typeof t=="string"?t=zt(Qt(t,e),e):typeof t=="object"&&(t=Qt(zt(t,e),e)),t}function nC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=H_(Qt(t,n),Qt(e,n),n,!0);return n.skipEscape=!0,zt(o,n)}function H_(t,e,r,n){let o={};return n||(t=Qt(zt(t,r),r),e=Qt(zt(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=bs(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=bs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=bs(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=bs(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function oC(t,e,r){return typeof t=="string"?(t=unescape(t),t=zt(Ea(Qt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=zt(Ea(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=zt(Ea(Qt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=zt(Ea(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function zt(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=W_(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=QA(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=bs(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var sC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Qt(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(sC);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(XA(n.host)===!1){let c=YA(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=W_(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&eC(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var md={SCHEMES:tC,normalize:rC,resolve:nC,resolveComponent:H_,equal:oC,serialize:zt,parse:Qt};Ra.exports=md;Ra.exports.default=md;Ra.exports.fastUri=md});var G_=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var J_=K_();J_.code='require("ajv/dist/runtime/uri").default';hd.default=J_});var ob=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var iC=vs();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return iC.KeywordCxt}});var Jn=H();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Jn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Jn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Jn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Jn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Jn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Jn.CodeGen}});var aC=Sa(),tb=_s(),cC=Vl(),ws=ka(),uC=H(),xs=hs(),Ia=ms(),yd=oe(),Y_=M_(),lC=G_(),rb=(t,e)=>new RegExp(t,e);rb.code="new RegExp";var dC=["removeAdditional","useDefaults","coerceTypes"],pC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),fC={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},mC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Q_=200;function hC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,y,_,S,v,k,x,z,O,Z,De;let Y=t.strict,kt=(e=t.code)===null||e===void 0?void 0:e.optimize,wr=kt===!0||kt===void 0?1:kt||0,Ls=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:rb,Fs=(o=t.uriResolver)!==null&&o!==void 0?o:lC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Y)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Y)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Y)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Y)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:Y)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:wr,regExp:Ls}:{optimize:wr,regExp:Ls},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Q_,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Q_,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(v=t.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(z=t.validateSchema)!==null&&z!==void 0?z:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(Z=t.unicodeRegExp)!==null&&Z!==void 0?Z:!0,int32range:(De=t.int32range)!==null&&De!==void 0?De:!0,uriResolver:Fs}}var Ss=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...hC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new uC.ValueScope({scope:{},prefixes:pC,es5:r,lines:n}),this.logger=wC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,cC.getRules)(),X_.call(this,fC,e,"NOT SUPPORTED"),X_.call(this,mC,e,"DEPRECATED","warn"),this._metaOpts=_C.call(this),e.formats&&yC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&vC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),gC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Y_;n==="id"&&(o={...Y_},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof tb.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,xs.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=eb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ws.SchemaEnv({schema:{},schemaId:n});if(r=ws.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=eb.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,xs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(SC.call(this,n,r),!r)return(0,yd.eachItem)(n,s=>gd.call(this,s)),this;kC.call(this,r);let o={...r,type:(0,Ia.getJSONTypes)(r.type),schemaType:(0,Ia.getJSONTypes)(r.schemaType)};return(0,yd.eachItem)(n,o.type.length===0?s=>gd.call(this,s,o):s=>o.type.forEach(i=>gd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=nb(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,xs.normalizeId)(i||n);let u=xs.getSchemaRefs.call(this,e,n);return c=new ws.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ws.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{ws.compileSchema.call(this,e)}finally{this.opts=r}}};Ss.ValidationError=aC.default;Ss.MissingRefError=tb.default;Ae.default=Ss;function X_(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function eb(t){return t=(0,xs.normalizeId)(t),this.schemas[t]||this.refs[t]}function gC(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function yC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function vC(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function _C(){let t={...this.opts};for(let e of dC)delete t[e];return t}var bC={log(){},warn(){},error(){}};function wC(t){if(t===!1)return bC;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var xC=/^[a-z_$][a-z0-9_$:-]*$/i;function SC(t,e){let{RULES:r}=this;if((0,yd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!xC.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function gd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Ia.getJSONTypes)(e.type),schemaType:(0,Ia.getJSONTypes)(e.schemaType)}};e.before?$C.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function $C(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function kC(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=nb(e)),t.validateSchema=this.compile(e,!0))}var PC={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function nb(t){return{anyOf:[t,PC]}}});var sb=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var TC={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vd.default=TC});var ub=E(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.callRef=nn.getValidate=void 0;var EC=_s(),ib=dt(),et=H(),Gn=Gt(),ab=ka(),Aa=oe(),RC={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=ab.resolveRef.call(c,u,o,r);if(l===void 0)throw new EC.default(n.opts.uriResolver,o,r);if(l instanceof ab.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Ca(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Ca(t,(0,et._)`${m}.validate`,u,u.$async)}function p(m){let g=cb(t,m);Ca(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,et.stringify)(m)}:{ref:m}),y=e.name("valid"),_=t.subschema({schema:m,dataTypes:[],schemaPath:et.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function cb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}nn.getValidate=cb;function Ca(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Gn.default.this:et.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,ib.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,et._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,ib.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,et._)`${m}.errors`;o.assign(Gn.default.vErrors,(0,et._)`${Gn.default.vErrors} === null ? ${g} : ${Gn.default.vErrors}.concat(${g})`),o.assign(Gn.default.errors,(0,et._)`${Gn.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Aa.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,et._)`${m}.evaluated.props`);s.props=Aa.mergeEvaluated.props(o,_,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Aa.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,et._)`${m}.evaluated.items`);s.items=Aa.mergeEvaluated.items(o,_,s.items,et.Name)}}}nn.callRef=Ca;nn.default=RC});var lb=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var IC=sb(),AC=ub(),CC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",IC.default,AC.default];_d.default=CC});var db=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Da=H(),_r=Da.operators,za={maximum:{okStr:"<=",ok:_r.LTE,fail:_r.GT},minimum:{okStr:">=",ok:_r.GTE,fail:_r.LT},exclusiveMaximum:{okStr:"<",ok:_r.LT,fail:_r.GTE},exclusiveMinimum:{okStr:">",ok:_r.GT,fail:_r.LTE}},DC={message:({keyword:t,schemaCode:e})=>(0,Da.str)`must be ${za[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Da._)`{comparison: ${za[t].okStr}, limit: ${e}}`},zC={keyword:Object.keys(za),type:"number",schemaType:"number",$data:!0,error:DC,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Da._)`${r} ${za[e].fail} ${n} || isNaN(${r})`)}};bd.default=zC});var pb=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var $s=H(),OC={message:({schemaCode:t})=>(0,$s.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$s._)`{multipleOf: ${t}}`},MC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:OC,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,$s._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,$s._)`${i} !== parseInt(${i})`;t.fail$data((0,$s._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wd.default=MC});var mb=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});function fb(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}xd.default=fb;fb.code='require("ajv/dist/runtime/ucs2length").default'});var hb=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var on=H(),jC=oe(),NC=mb(),LC={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,on.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,on._)`{limit: ${t}}`},FC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:LC,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?on.operators.GT:on.operators.LT,i=o.opts.unicode===!1?(0,on._)`${r}.length`:(0,on._)`${(0,jC.useFunc)(t.gen,NC.default)}(${r})`;t.fail$data((0,on._)`${i} ${s} ${n}`)}};Sd.default=FC});var gb=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var ZC=dt(),Oa=H(),UC={message:({schemaCode:t})=>(0,Oa.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Oa._)`{pattern: ${t}}`},qC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:UC,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,Oa._)`(new RegExp(${o}, ${i}))`:(0,ZC.usePattern)(t,n);t.fail$data((0,Oa._)`!${a}.test(${e})`)}};$d.default=qC});var yb=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var ks=H(),VC={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ks.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ks._)`{limit: ${t}}`},BC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:VC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ks.operators.GT:ks.operators.LT;t.fail$data((0,ks._)`Object.keys(${r}).length ${o} ${n}`)}};kd.default=BC});var vb=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Ps=dt(),Ts=H(),WC=oe(),HC={message:({params:{missingProperty:t}})=>(0,Ts.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ts._)`{missingProperty: ${t}}`},KC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:HC,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(f?.[g]===void 0&&!m.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,WC.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ts.nil,d);else for(let f of r)(0,Ps.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Ps.checkMissingProp)(t,r,f)),(0,Ps.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ps.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ps.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Ts.not)(m),()=>{t.error(),e.break()})},Ts.nil)}}};Pd.default=KC});var _b=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Es=H(),JC={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Es.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Es._)`{limit: ${t}}`},GC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:JC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Es.operators.GT:Es.operators.LT;t.fail$data((0,Es._)`${r}.length ${o} ${n}`)}};Td.default=GC});var Ma=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var bb=Ql();bb.code='require("ajv/dist/runtime/equal").default';Ed.default=bb});var wb=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var Rd=ms(),Ce=H(),YC=oe(),QC=Ma(),XC={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},eD={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:XC,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Rd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ce._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Ce._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Ce._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let y=e.name("item"),_=(0,Rd.checkDataTypes)(u,y,a.opts.strictNumbers,Rd.DataType.Wrong),S=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${m}--;`,()=>{e.let(y,(0,Ce._)`${r}[${m}]`),e.if(_,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${y} == "string"`,(0,Ce._)`${y} += "_"`),e.if((0,Ce._)`typeof ${S}[${y}] == "number"`,()=>{e.assign(g,(0,Ce._)`${S}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ce._)`${S}[${y}] = ${m}`)})}function f(m,g){let y=(0,YC.useFunc)(e,QC.default),_=e.name("outer");e.label(_).for((0,Ce._)`;${m}--;`,()=>e.for((0,Ce._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Ce._)`${y}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Id.default=eD});var xb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Ad=H(),tD=oe(),rD=Ma(),nD={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ad._)`{allowedValue: ${t}}`},oD={keyword:"const",$data:!0,error:nD,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ad._)`!${(0,tD.useFunc)(e,rD.default)}(${r}, ${o})`):t.fail((0,Ad._)`${s} !== ${r}`)}};Cd.default=oD});var Sb=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Rs=H(),sD=oe(),iD=Ma(),aD={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Rs._)`{allowedValues: ${t}}`},cD={keyword:"enum",schemaType:"array",$data:!0,error:aD,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,sD.useFunc)(e,iD.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Rs.or)(...o.map((m,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Rs._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Rs._)`${u()}(${r}, ${f}[${m}])`:(0,Rs._)`${r} === ${g}`}}};Dd.default=cD});var $b=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var uD=db(),lD=pb(),dD=hb(),pD=gb(),fD=yb(),mD=vb(),hD=_b(),gD=wb(),yD=xb(),vD=Sb(),_D=[uD.default,lD.default,dD.default,pD.default,fD.default,mD.default,hD.default,gD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yD.default,vD.default];zd.default=_D});var Md=E(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.validateAdditionalItems=void 0;var sn=H(),Od=oe(),bD={message:({params:{len:t}})=>(0,sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sn._)`{limit: ${t}}`},wD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:bD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Od.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}kb(t,n)}};function kb(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,sn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Od.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,sn._)`${a} <= ${e.length}`);r.if((0,sn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Od.Type.Num},u),i.allErrors||r.if((0,sn.not)(u),()=>r.break())})}}Is.validateAdditionalItems=kb;Is.default=wD});var jd=E(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.validateTuple=void 0;var Pb=H(),ja=oe(),xD=dt(),SD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Tb(t,"additionalItems",e);r.items=!0,!(0,ja.alwaysValidSchema)(r,e)&&t.ok((0,xD.validateArray)(t))}};function Tb(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ja.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Pb._)`${s}.length`);r.forEach((d,p)=>{(0,ja.alwaysValidSchema)(a,d)||(n.if((0,Pb._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,g=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ja.checkStrictMode)(a,y,p.strictTuples)}}}As.validateTuple=Tb;As.default=SD});var Eb=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var $D=jd(),kD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,$D.validateTuple)(t,"items")};Nd.default=kD});var Ib=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Rb=H(),PD=oe(),TD=dt(),ED=Md(),RD={message:({params:{len:t}})=>(0,Rb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Rb._)`{limit: ${t}}`},ID={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:RD,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,PD.alwaysValidSchema)(n,e)&&(o?(0,ED.validateAdditionalItems)(t,o):t.ok((0,TD.validateArray)(t)))}};Ld.default=ID});var Ab=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var ft=H(),Na=oe(),AD={message:({params:{min:t,max:e}})=>e===void 0?(0,ft.str)`must contain at least ${t} valid item(s)`:(0,ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ft._)`{minContains: ${t}}`:(0,ft._)`{minContains: ${t}, maxContains: ${e}}`},CD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:AD,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Na.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Na.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Na.alwaysValidSchema)(s,r)){let g=(0,ft._)`${l} >= ${i}`;a!==void 0&&(g=(0,ft._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ft._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),y=e.let("count",0);f(g,()=>e.if(g,()=>m(y)))}function f(g,y){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Na.Type.Num,compositeRule:!0},g),y()})}function m(g){e.code((0,ft._)`${g}++`),a===void 0?e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ft._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Fd.default=CD});var zb=E(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var Zd=H(),DD=oe(),Cs=dt();Ot.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zd._)`{property: ${t},
9
9
  missingProperty: ${n},
10
10
  depsCount: ${e},
11
- deps: ${r}}`};var BC={keyword:"dependencies",type:"object",schemaType:"object",error:Dt.error,code(t){let[e,r]=HC(t);Av(t,e),Iv(t,r)}};function HC({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Av(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,ws.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,ws.checkReportMissingProp)(t,u)}):(r.if((0,cd._)`${c} && (${(0,ws.checkMissingProp)(t,a,s)})`),(0,ws.reportMissingProp)(t,s),r.else())}}Dt.validatePropertyDeps=Av;function Iv(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,WC.alwaysValidSchema)(s,e[a])||(r.if((0,ws.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Dt.validateSchemaDeps=Iv;Dt.default=BC});var Mv=E(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var Ov=B(),GC=oe(),JC={message:"property name must be valid",params:({params:t})=>(0,Ov._)`{propertyName: ${t.propertyName}}`},KC={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:JC,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,GC.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Ov.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};ud.default=KC});var dd=E(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var _a=dt(),wt=B(),QC=Ht(),va=oe(),YC={message:"must NOT have additional properties",params:({params:t})=>(0,wt._)`{additionalProperty: ${t.additionalProperty}}`},XC={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:YC,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,va.alwaysValidSchema)(i,r))return;let u=(0,_a.allSchemaProperties)(n.properties),l=(0,_a.allSchemaProperties)(n.patternProperties);d(),t.ok((0,wt._)`${s} === ${QC.default.errors}`);function d(){e.forIn("key",o,m=>{!u.length&&!l.length?g(m):e.if(p(m),()=>g(m))})}function p(m){let b;if(u.length>8){let _=(0,va.schemaRefOrVal)(i,n.properties,"properties");b=(0,_a.isOwnProperty)(e,_,m)}else u.length?b=(0,wt.or)(...u.map(_=>(0,wt._)`${m} === ${_}`)):b=wt.nil;return l.length&&(b=(0,wt.or)(b,...l.map(_=>(0,wt._)`${(0,_a.usePattern)(t,_)}.test(${m})`))),(0,wt.not)(b)}function f(m){e.code((0,wt._)`delete ${o}[${m}]`)}function g(m){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(m);return}if(r===!1){t.setParams({additionalProperty:m}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,va.alwaysValidSchema)(i,r)){let b=e.name("valid");c.removeAdditional==="failing"?(y(m,b,!1),e.if((0,wt.not)(b),()=>{t.reset(),f(m)})):(y(m,b),a||e.if((0,wt.not)(b),()=>e.break()))}}function y(m,b,_){let w={keyword:"additionalProperties",dataProp:m,dataPropType:va.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,b)}}};ld.default=XC});var Lv=E(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var eA=cs(),Nv=dt(),pd=oe(),jv=dd(),tA={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&jv.default.code(new eA.KeywordCxt(s,jv.default,"additionalProperties"));let i=(0,Nv.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=pd.mergeEvaluated.props(e,(0,pd.toHash)(i),s.props));let a=i.filter(d=>!(0,pd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Nv.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};fd.default=tA});var Uv=E(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Zv=dt(),xa=B(),qv=oe(),Fv=oe(),rA={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Zv.allSchemaProperties)(r),c=a.filter(y=>(0,qv.alwaysValidSchema)(s,r[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof xa.Name)&&(s.props=(0,Fv.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let y of a)u&&f(y),s.allErrors?g(y):(e.var(l,!0),g(y),e.if(l))}function f(y){for(let m in u)new RegExp(y).test(m)&&(0,qv.checkStrictMode)(s,`property ${m} matches pattern ${y} (use allowMatchingProperties)`)}function g(y){e.forIn("key",n,m=>{e.if((0,xa._)`${(0,Zv.usePattern)(t,y)}.test(${m})`,()=>{let b=c.includes(y);b||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:m,dataPropType:Fv.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,xa._)`${d}[${m}]`,!0):!b&&!s.allErrors&&e.if((0,xa.not)(l),()=>e.break())})})}}};md.default=rA});var Vv=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var nA=oe(),oA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,nA.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};hd.default=oA});var Wv=E(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var sA=dt(),iA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:sA.validateUnion,error:{message:"must match a schema in anyOf"}};gd.default=iA});var Bv=E(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var ba=B(),aA=oe(),cA={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ba._)`{passingSchemas: ${t.passing}}`},uA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:cA,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,aA.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,ba._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ba._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,ba.Name)})})}}};yd.default=uA});var Hv=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var lA=oe(),dA={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,lA.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};_d.default=dA});var Kv=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var wa=B(),Jv=oe(),pA={message:({params:t})=>(0,wa.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,wa._)`{failingKeyword: ${t.ifClause}}`},fA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:pA,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Jv.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Gv(n,"then"),s=Gv(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,wa.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,wa._)`${l}`):t.setParams({ifClause:l})}}}};function Gv(t,e){let r=t.schema[e];return r!==void 0&&!(0,Jv.alwaysValidSchema)(t,r)}vd.default=fA});var Qv=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var mA=oe(),hA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,mA.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};xd.default=hA});var Yv=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var gA=nd(),yA=Ev(),_A=od(),vA=zv(),xA=Cv(),bA=Dv(),wA=Mv(),$A=dd(),SA=Lv(),kA=Uv(),TA=Vv(),PA=Wv(),EA=Bv(),RA=Hv(),zA=Kv(),CA=Qv();function AA(t=!1){let e=[TA.default,PA.default,EA.default,RA.default,zA.default,CA.default,wA.default,$A.default,bA.default,SA.default,kA.default];return t?e.push(yA.default,vA.default):e.push(gA.default,_A.default),e.push(xA.default),e}bd.default=AA});var Xv=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var Te=B(),IA={message:({schemaCode:t})=>(0,Te.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Te._)`{format: ${t}}`},DA={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:IA,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let g=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=r.const("fDef",(0,Te._)`${g}[${i}]`),m=r.let("fType"),b=r.let("format");r.if((0,Te._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(m,(0,Te._)`${y}.type || "string"`).assign(b,(0,Te._)`${y}.validate`),()=>r.assign(m,(0,Te._)`"string"`).assign(b,y)),t.fail$data((0,Te.or)(_(),w()));function _(){return c.strictSchema===!1?Te.nil:(0,Te._)`${i} && !${b}`}function w(){let k=l.$async?(0,Te._)`(${y}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,Te._)`${b}(${n})`,P=(0,Te._)`(typeof ${b} == "function" ? ${k} : ${b}.test(${n}))`;return(0,Te._)`${b} && ${b} !== true && ${m} === ${e} && !${P}`}}function f(){let g=d.formats[s];if(!g){_();return}if(g===!0)return;let[y,m,b]=w(g);y===e&&t.pass(k());function _(){if(c.strictSchema===!1){d.logger.warn(P());return}throw new Error(P());function P(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(P){let U=P instanceof RegExp?(0,Te.regexpCode)(P):c.code.formats?(0,Te._)`${c.code.formats}${(0,Te.getProperty)(s)}`:void 0,Z=r.scopeValue("formats",{key:s,ref:P,code:U});return typeof P=="object"&&!(P instanceof RegExp)?[P.type||"string",P.validate,(0,Te._)`${Z}.validate`]:["string",P,Z]}function k(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Te._)`await ${b}(${n})`}return typeof m=="function"?(0,Te._)`${b}(${n})`:(0,Te._)`${b}.test(${n})`}}}};wd.default=DA});var ex=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var OA=Xv(),MA=[OA.default];$d.default=MA});var tx=E(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.contentVocabulary=Bn.metadataVocabulary=void 0;Bn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Bn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var nx=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var NA=lv(),jA=Sv(),LA=Yv(),ZA=ex(),rx=tx(),qA=[NA.default,jA.default,(0,LA.default)(),ZA.default,rx.metadataVocabulary,rx.contentVocabulary];Sd.default=qA});var sx=E($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.DiscrError=void 0;var ox;(function(t){t.Tag="tag",t.Mapping="mapping"})(ox||($a.DiscrError=ox={}))});var ax=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Hn=B(),kd=sx(),ix=oa(),FA=us(),UA=oe(),VA={message:({params:{discrError:t,tagName:e}})=>t===kd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Hn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},WA={keyword:"discriminator",type:"object",schemaType:"object",error:VA,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Hn._)`${r}${(0,Hn.getProperty)(a)}`);e.if((0,Hn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:kd.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let g in f)e.elseIf((0,Hn._)`${u} === ${g}`),e.assign(c,d(f[g]));e.else(),t.error(!1,{discrError:kd.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let g=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:f},g);return t.mergeEvaluated(y,Hn.Name),g}function p(){var f;let g={},y=b(o),m=!0;for(let k=0;k<i.length;k++){let P=i[k];if(P?.$ref&&!(0,UA.schemaHasRulesButRef)(P,s.self.RULES)){let Z=P.$ref;if(P=ix.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Z),P instanceof ix.SchemaEnv&&(P=P.schema),P===void 0)throw new FA.default(s.opts.uriResolver,s.baseId,Z)}let U=(f=P?.properties)===null||f===void 0?void 0:f[a];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);m=m&&(y||b(P)),_(U,k)}if(!m)throw new Error(`discriminator: "${a}" must be required`);return g;function b({required:k}){return Array.isArray(k)&&k.includes(a)}function _(k,P){if(k.const)w(k.const,P);else if(k.enum)for(let U of k.enum)w(U,P);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(k,P){if(typeof k!="string"||k in g)throw new Error(`discriminator: "${a}" values must be unique strings`);g[k]=P}}}};Td.default=WA});var cx=E((F9,BA)=>{BA.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Ed=E((ye,Pd)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var HA=ov(),GA=nx(),JA=ax(),ux=cx(),KA=["/properties"],Sa="http://json-schema.org/draft-07/schema",Gn=class extends HA.default{_addVocabularies(){super._addVocabularies(),GA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(JA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ux,KA):ux;this.addMetaSchema(e,Sa,!1),this.refs["http://json-schema.org/schema"]=Sa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Sa)?Sa:void 0)}};ye.Ajv=Gn;Pd.exports=ye=Gn;Pd.exports.Ajv=Gn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Gn;var QA=cs();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return QA.KeywordCxt}});var Jn=B();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Jn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Jn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Jn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Jn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Jn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Jn.CodeGen}});var YA=ra();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return YA.default}});var XA=us();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return XA.default}})});var yx=E(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.formatNames=Mt.fastFormats=Mt.fullFormats=void 0;function Ot(t,e){return{validate:t,compare:e}}Mt.fullFormats={date:Ot(fx,Ad),time:Ot(zd(!0),Id),"date-time":Ot(lx(!0),hx),"iso-time":Ot(zd(),mx),"iso-date-time":Ot(lx(),gx),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:sI,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:pI,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:iI,int32:{type:"number",validate:uI},int64:{type:"number",validate:lI},float:{type:"number",validate:px},double:{type:"number",validate:px},password:!0,binary:!0};Mt.fastFormats={...Mt.fullFormats,date:Ot(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ad),time:Ot(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Id),"date-time":Ot(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,hx),"iso-time":Ot(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mx),"iso-date-time":Ot(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gx),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Mt.formatNames=Object.keys(Mt.fullFormats);function eI(t){return t%4===0&&(t%100!==0||t%400===0)}var tI=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,rI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fx(t){let e=tI.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&eI(r)?29:rI[n])}function Ad(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Rd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function zd(t){return function(r){let n=Rd.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function Id(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function mx(t,e){if(!(t&&e))return;let r=Rd.exec(t),n=Rd.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Cd=/t|\s/i;function lx(t){let e=zd(t);return function(n){let o=n.split(Cd);return o.length===2&&fx(o[0])&&e(o[1])}}function hx(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function gx(t,e){if(!(t&&e))return;let[r,n]=t.split(Cd),[o,s]=e.split(Cd),i=Ad(r,o);if(i!==void 0)return i||Id(n,s)}var nI=/\/|:/,oI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function sI(t){return nI.test(t)&&oI.test(t)}var dx=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function iI(t){return dx.lastIndex=0,dx.test(t)}var aI=-(2**31),cI=2**31-1;function uI(t){return Number.isInteger(t)&&t<=cI&&t>=aI}function lI(t){return Number.isInteger(t)}function px(){return!0}var dI=/[^\\]\\Z/;function pI(t){if(dI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var _x=E(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.formatLimitDefinition=void 0;var fI=Ed(),$t=B(),yr=$t.operators,ka={formatMaximum:{okStr:"<=",ok:yr.LTE,fail:yr.GT},formatMinimum:{okStr:">=",ok:yr.GTE,fail:yr.LT},formatExclusiveMaximum:{okStr:"<",ok:yr.LT,fail:yr.GTE},formatExclusiveMinimum:{okStr:">",ok:yr.GT,fail:yr.LTE}},mI={message:({keyword:t,schemaCode:e})=>(0,$t.str)`should be ${ka[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$t._)`{comparison: ${ka[t].okStr}, limit: ${e}}`};Kn.formatLimitDefinition={keyword:Object.keys(ka),type:"string",schemaType:"string",$data:!0,error:mI,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new fI.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,$t._)`${p}[${c.schemaCode}]`);t.fail$data((0,$t.or)((0,$t._)`typeof ${f} != "object"`,(0,$t._)`${f} instanceof RegExp`,(0,$t._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let g=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,$t._)`${i.code.formats}${(0,$t.getProperty)(p)}`:void 0});t.fail$data(d(g))}function d(p){return(0,$t._)`${p}.compare(${r}, ${n}) ${ka[o].fail} 0`}},dependencies:["format"]};var hI=t=>(t.addKeyword(Kn.formatLimitDefinition),t);Kn.default=hI});var wx=E(($s,bx)=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var Qn=yx(),gI=_x(),Dd=B(),vx=new Dd.Name("fullFormats"),yI=new Dd.Name("fastFormats"),Od=(t,e={keywords:!0})=>{if(Array.isArray(e))return xx(t,e,Qn.fullFormats,vx),t;let[r,n]=e.mode==="fast"?[Qn.fastFormats,yI]:[Qn.fullFormats,vx],o=e.formats||Qn.formatNames;return xx(t,o,r,n),e.keywords&&(0,gI.default)(t),t};Od.get=(t,e="full")=>{let n=(e==="fast"?Qn.fastFormats:Qn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function xx(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Dd._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}bx.exports=$s=Od;Object.defineProperty($s,"__esModule",{value:!0});$s.default=Od});import{readFileSync as LD}from"fs";import{join as Xa}from"path";import{fileURLToPath as ZD}from"url";var cn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},ks=class extends cn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},me=class extends cn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var un=class extends cn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},Be=class extends cn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var wp={ollama:{tier:"tool"},"claude-cli":{tier:"agent",maxComplexity:"complex"},"gemini-cli":{tier:"agent",maxComplexity:"complex"},"codex-cli":{tier:"agent",maxComplexity:"complex"},"claude-host":{tier:"agent",maxComplexity:"complex"},"codex-host":{tier:"agent",maxComplexity:"complex"},"gemini-host":{tier:"agent",maxComplexity:"complex"}},rw={ollama:{invocation:"http",roles:["participant","tool"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"claude-cli":{invocation:"cli",roles:["participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"codex-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"claude-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"codex-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0}};function rc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Ps(t,e,r,n=t){let o=wp[n]??wp[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=rc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function Qt(t,e){let r=rw[t.type],n=r?.roles?[...r.roles]:["participant"];return{id:t.id,type:t.type,invocation:r?.invocation??"unknown",roles:n,supportsAutonomousExecution:r?.supportsAutonomousExecution??!1,supportsReadOnlyChat:r?.supportsReadOnlyChat??!0,supportsToolUse:e?.supportsToolUse??r?.supportsToolUse??!1}}var Es={low:0,medium:.5,high:.7},nw={chat:"low",simple_review:"low",code_review:"medium",code_generation:"medium",design:"medium",writing:"medium",analysis:"medium",ideation:"medium",debate_turn:"medium",architecture:"high",cross_validate:"high",complex_refactor:"high"};function $p(t,e){return e?.[t]??nw[t]??"low"}function Rs(t,e,r=Es){return t>=r[e]}var zs=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.getAll().find(n=>n.type==="claude-host"||n.type==="claude-cli")}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new ks(e);return r}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(e=>e.isAvailable())}getAvailableDescriptors(){return this.getAvailable().map(e=>this.getDescriptor(e.id))}getByCapability(e){return this.getAvailable().filter(r=>r.getCapabilities().strengths.includes(e))}has(e){return this.providers.has(e)}getCapability(e){let r=this.get(e);return Ps(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??Qt(r,r.getCapabilities())}getByTier(e){return this.getAvailable().filter(r=>this.getCapability(r.id).tier===e)}getByRole(e){return this.getAvailable().filter(r=>this.getDescriptor(r.id).roles.includes(e))}getBestForTask(e,r,n,o){let s=this.getAvailable();if(s.length===0)return;if(!r)return s[0];let i=n??$p(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let g=p.split(":")[0],y=c.get(g)??{totalScore:0,count:0};y.totalScore+=f.avgScore*f.count,y.count+=f.count,c.set(g,y)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let g=f.totalScore/f.count;return Rs(g,i,o)});if(u.length===0)return;let l,d=-1;for(let p of u){let f=`${p.id}:${e}`,g=a.get(f);g&&g.avgScore>d&&(d=g.avgScore,l=p)}return l??u[0]}};var h={};We(h,{BRAND:()=>Rw,DIRTY:()=>br,EMPTY_PATH:()=>aw,INVALID:()=>D,NEVER:()=>f$,OK:()=>Oe,ParseStatus:()=>Ee,Schema:()=>V,ZodAny:()=>er,ZodArray:()=>qt,ZodBigInt:()=>$r,ZodBoolean:()=>Sr,ZodBranded:()=>oo,ZodCatch:()=>Or,ZodDate:()=>kr,ZodDefault:()=>Dr,ZodDiscriminatedUnion:()=>Is,ZodEffects:()=>st,ZodEnum:()=>Ar,ZodError:()=>He,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Os,ZodIntersection:()=>Rr,ZodIssueCode:()=>$,ZodLazy:()=>zr,ZodLiteral:()=>Cr,ZodMap:()=>vn,ZodNaN:()=>bn,ZodNativeEnum:()=>Ir,ZodNever:()=>mt,ZodNull:()=>Pr,ZodNullable:()=>Pt,ZodNumber:()=>wr,ZodObject:()=>Ge,ZodOptional:()=>nt,ZodParsedType:()=>R,ZodPipeline:()=>so,ZodPromise:()=>tr,ZodReadonly:()=>Mr,ZodRecord:()=>Ds,ZodSchema:()=>V,ZodSet:()=>xn,ZodString:()=>Xt,ZodSymbol:()=>yn,ZodTransformer:()=>st,ZodTuple:()=>Tt,ZodType:()=>V,ZodUndefined:()=>Tr,ZodUnion:()=>Er,ZodUnknown:()=>Zt,ZodVoid:()=>_n,addIssueToContext:()=>T,any:()=>jw,array:()=>Fw,bigint:()=>Iw,boolean:()=>Dp,coerce:()=>p$,custom:()=>Cp,date:()=>Dw,datetimeRegex:()=>Rp,defaultErrorMap:()=>jt,discriminatedUnion:()=>Bw,effect:()=>o$,enum:()=>t$,function:()=>Yw,getErrorMap:()=>mn,getParsedType:()=>kt,instanceof:()=>Cw,intersection:()=>Hw,isAborted:()=>Cs,isAsync:()=>hn,isDirty:()=>As,isValid:()=>Yt,late:()=>zw,lazy:()=>Xw,literal:()=>e$,makeIssue:()=>no,map:()=>Kw,nan:()=>Aw,nativeEnum:()=>r$,never:()=>Zw,null:()=>Nw,nullable:()=>i$,number:()=>Ip,object:()=>Uw,objectUtil:()=>nc,oboolean:()=>d$,onumber:()=>l$,optional:()=>s$,ostring:()=>u$,pipeline:()=>c$,preprocess:()=>a$,promise:()=>n$,quotelessJson:()=>ow,record:()=>Jw,set:()=>Qw,setErrorMap:()=>iw,strictObject:()=>Vw,string:()=>Ap,symbol:()=>Ow,transformer:()=>o$,tuple:()=>Gw,undefined:()=>Mw,union:()=>Ww,unknown:()=>Lw,util:()=>K,void:()=>qw});var K;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var nc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(nc||(nc={}));var R=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var $=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ow=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),He=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};He.create=t=>new He(t);var sw=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,K.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${K.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${K.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${K.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:K.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case $.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,K.assertNever(t)}return{message:r}},jt=sw;var Sp=jt;function iw(t){Sp=t}function mn(){return Sp}var no=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},aw=[];function T(t,e){let r=mn(),n=no({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===jt?void 0:jt].filter(o=>!!o)});t.common.issues.push(n)}var Ee=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return D;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return D;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},D=Object.freeze({status:"aborted"}),br=t=>({status:"dirty",value:t}),Oe=t=>({status:"valid",value:t}),Cs=t=>t.status==="aborted",As=t=>t.status==="dirty",Yt=t=>t.status==="valid",hn=t=>typeof Promise<"u"&&t instanceof Promise;var C;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(C||(C={}));var ot=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},kp=(t,e)=>{if(Yt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new He(t.common.issues);return this._error=r,this._error}}};function L(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var V=class{get description(){return this._def.description}_getType(e){return kt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(hn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return kp(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Yt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Yt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(hn(o)?o:Promise.resolve(o));return kp(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:$.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new st({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return nt.create(this,this._def)}nullable(){return Pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return qt.create(this)}promise(){return tr.create(this,this._def)}or(e){return Er.create([this,e],this._def)}and(e){return Rr.create(this,e,this._def)}transform(e){return new st({...L(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Dr({...L(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new oo({typeName:S.ZodBranded,type:this,...L(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Or({...L(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return so.create(this,e)}readonly(){return Mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cw=/^c[^\s-]{8,}$/i,uw=/^[0-9a-z]+$/,lw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,pw=/^[a-z0-9_-]{21}$/i,fw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,hw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oc,yw=/^(?:(?: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])$/,_w=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,vw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,xw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ww=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pp="((\\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])))",$w=new RegExp(`^${Pp}$`);function Ep(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Sw(t){return new RegExp(`^${Ep(t)}$`)}function Rp(t){let e=`${Pp}T${Ep(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function kw(t,e){return!!((e==="v4"||!e)&&yw.test(t)||(e==="v6"||!e)&&vw.test(t))}function Tw(t,e){if(!fw.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Pw(t,e){return!!((e==="v4"||!e)&&_w.test(t)||(e==="v6"||!e)&&xw.test(t))}var Xt=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.string,received:s.parsedType}),D}let n=new Ee,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")hw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")oc||(oc=new RegExp(gw,"u")),oc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")dw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")pw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")cw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")uw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")lw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:$.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:$.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Rp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?$w.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Sw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?mw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?kw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Tw(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Pw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?bw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ww.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):K.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...C.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...C.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...C.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...C.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...C.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...C.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...C.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...C.errToObj(r)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Xt.create=t=>new Xt({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...L(t)});function Ew(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var wr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.number,received:s.parsedType}),D}let n,o=new Ee;for(let s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Ew(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_finite,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,C.toString(r))}gt(e,r){return this.setLimit("min",e,!1,C.toString(r))}lte(e,r){return this.setLimit("max",e,!0,C.toString(r))}lt(e,r){return this.setLimit("max",e,!1,C.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};wr.create=t=>new wr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...L(t)});var $r=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,o=new Ee;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.bigint,received:r.parsedType}),D}gte(e,r){return this.setLimit("min",e,!0,C.toString(r))}gt(e,r){return this.setLimit("min",e,!1,C.toString(r))}lte(e,r){return this.setLimit("max",e,!0,C.toString(r))}lt(e,r){return this.setLimit("max",e,!1,C.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};$r.create=t=>new $r({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...L(t)});var Sr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.boolean,received:n.parsedType}),D}return Oe(e.data)}};Sr.create=t=>new Sr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...L(t)});var kr=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.date,received:s.parsedType}),D}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_date}),D}let n=new Ee,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):K.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};kr.create=t=>new kr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...L(t)});var yn=class extends V{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.symbol,received:n.parsedType}),D}return Oe(e.data)}};yn.create=t=>new yn({typeName:S.ZodSymbol,...L(t)});var Tr=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.undefined,received:n.parsedType}),D}return Oe(e.data)}};Tr.create=t=>new Tr({typeName:S.ZodUndefined,...L(t)});var Pr=class extends V{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.null,received:n.parsedType}),D}return Oe(e.data)}};Pr.create=t=>new Pr({typeName:S.ZodNull,...L(t)});var er=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}};er.create=t=>new er({typeName:S.ZodAny,...L(t)});var Zt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oe(e.data)}};Zt.create=t=>new Zt({typeName:S.ZodUnknown,...L(t)});var mt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.never,received:r.parsedType}),D}};mt.create=t=>new mt({typeName:S.ZodNever,...L(t)});var _n=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.void,received:n.parsedType}),D}return Oe(e.data)}};_n.create=t=>new _n({typeName:S.ZodVoid,...L(t)});var qt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:$.invalid_type,expected:R.array,received:r.parsedType}),D;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?$.too_big:$.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new ot(r,i,r.path,a)))).then(i=>Ee.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ot(r,i,r.path,a)));return Ee.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:C.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:C.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:C.toString(r)}})}nonempty(e){return this.min(1,e)}};qt.create=(t,e)=>new qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...L(e)});function gn(t){if(t instanceof Ge){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=nt.create(gn(n))}return new Ge({...t._def,shape:()=>e})}else return t instanceof qt?new qt({...t._def,type:gn(t.element)}):t instanceof nt?nt.create(gn(t.unwrap())):t instanceof Pt?Pt.create(gn(t.unwrap())):t instanceof Tt?Tt.create(t.items.map(e=>gn(e))):t}var Ge=class t extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=K.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:$.invalid_type,expected:R.object,received:u.parsedType}),D}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ot(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(T(o,{code:$.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ot(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Ee.mergeObjectSync(n,u)):Ee.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:C.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of K.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of K.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return gn(this)}partial(e){let r={};for(let n of K.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of K.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof nt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return zp(K.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...L(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:S.ZodObject,...L(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...L(e)});var Er=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new He(a.ctx.common.issues));return T(r,{code:$.invalid_union,unionErrors:i}),D}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new He(c));return T(r,{code:$.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};Er.create=(t,e)=>new Er({options:t,typeName:S.ZodUnion,...L(e)});var Lt=t=>t instanceof zr?Lt(t.schema):t instanceof st?Lt(t.innerType()):t instanceof Cr?[t.value]:t instanceof Ar?t.options:t instanceof Ir?K.objectValues(t.enum):t instanceof Dr?Lt(t._def.innerType):t instanceof Tr?[void 0]:t instanceof Pr?[null]:t instanceof nt?[void 0,...Lt(t.unwrap())]:t instanceof Pt?[null,...Lt(t.unwrap())]:t instanceof oo||t instanceof Mr?Lt(t.unwrap()):t instanceof Or?Lt(t._def.innerType):[],Is=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:$.invalid_type,expected:R.object,received:r.parsedType}),D;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Lt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...L(n)})}};function sc(t,e){let r=kt(t),n=kt(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=K.objectKeys(e),s=K.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=sc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=sc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Rr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Cs(s)||Cs(i))return D;let a=sc(s.value,i.value);return a.valid?((As(s)||As(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:$.invalid_intersection_types}),D)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Rr.create=(t,e,r)=>new Rr({left:t,right:e,typeName:S.ZodIntersection,...L(r)});var Tt=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:$.invalid_type,expected:R.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return T(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ot(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ee.mergeArray(r,i)):Ee.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Tt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tt({items:t,typeName:S.ZodTuple,rest:null,...L(e)})};var Ds=class t extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:$.invalid_type,expected:R.object,received:n.parsedType}),D;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ot(n,a,n.path,a)),value:i._parse(new ot(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ee.mergeObjectAsync(r,o):Ee.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof V?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...L(n)}):new t({keyType:Xt.create(),valueType:e,typeName:S.ZodRecord,...L(r)})}},vn=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:$.invalid_type,expected:R.map,received:n.parsedType}),D;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new ot(n,a,n.path,[u,"key"])),value:s._parse(new ot(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return D;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return D;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};vn.create=(t,e,r)=>new vn({valueType:e,keyType:t,typeName:S.ZodMap,...L(r)});var xn=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:$.invalid_type,expected:R.set,received:n.parsedType}),D;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return D;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new ot(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:C.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:C.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};xn.create=(t,e)=>new xn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...L(e)});var Os=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:$.invalid_type,expected:R.function,received:r.parsedType}),D;function n(a,c){return no({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,mn(),jt].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return no({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,mn(),jt].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof tr){let a=this;return Oe(async function(...c){let u=new He([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Oe(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new He([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new He([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Tt.create(e).rest(Zt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Tt.create([]).rest(Zt.create()),returns:r||Zt.create(),typeName:S.ZodFunction,...L(n)})}},zr=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};zr.create=(t,e)=>new zr({getter:t,typeName:S.ZodLazy,...L(e)});var Cr=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:e.data}}get value(){return this._def.value}};Cr.create=(t,e)=>new Cr({value:t,typeName:S.ZodLiteral,...L(e)});function zp(t,e){return new Ar({values:t,typeName:S.ZodEnum,...L(e)})}var Ar=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:K.joinValues(n),received:r.parsedType,code:$.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:$.invalid_enum_value,options:n}),D}return Oe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ar.create=zp;var Ir=class extends V{_parse(e){let r=K.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=K.objectValues(r);return T(n,{expected:K.joinValues(o),received:n.parsedType,code:$.invalid_type}),D}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=K.objectValues(r);return T(n,{received:n.data,code:$.invalid_enum_value,options:o}),D}return Oe(e.data)}get enum(){return this._def.values}};Ir.create=(t,e)=>new Ir({values:t,typeName:S.ZodNativeEnum,...L(e)});var tr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:$.invalid_type,expected:R.promise,received:r.parsedType}),D;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Oe(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};tr.create=(t,e)=>new tr({type:t,typeName:S.ZodPromise,...L(e)});var st=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?br(c.value):r.value==="dirty"?br(c.value):c});{if(r.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?br(a.value):r.value==="dirty"?br(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Yt(i))return D;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Yt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):D);K.assertNever(o)}};st.create=(t,e,r)=>new st({schema:t,typeName:S.ZodEffects,effect:e,...L(r)});st.createWithPreprocess=(t,e,r)=>new st({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...L(r)});var nt=class extends V{_parse(e){return this._getType(e)===R.undefined?Oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nt.create=(t,e)=>new nt({innerType:t,typeName:S.ZodOptional,...L(e)});var Pt=class extends V{_parse(e){return this._getType(e)===R.null?Oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Pt.create=(t,e)=>new Pt({innerType:t,typeName:S.ZodNullable,...L(e)});var Dr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Dr.create=(t,e)=>new Dr({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...L(e)});var Or=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return hn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new He(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new He(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Or.create=(t,e)=>new Or({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...L(e)});var bn=class extends V{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.nan,received:n.parsedType}),D}return{status:"valid",value:e.data}}};bn.create=t=>new bn({typeName:S.ZodNaN,...L(t)});var Rw=Symbol("zod_brand"),oo=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},so=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?D:s.status==="dirty"?(r.dirty(),br(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?D:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:S.ZodPipeline})}},Mr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Yt(o)&&(o.value=Object.freeze(o.value)),o);return hn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:S.ZodReadonly,...L(e)});function Tp(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Cp(t,e={},r){return t?er.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Tp(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Tp(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):er.create()}var zw={object:Ge.lazycreate},S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));var Cw=(t,e={message:`Input not instance of ${t.name}`})=>Cp(r=>r instanceof t,e),Ap=Xt.create,Ip=wr.create,Aw=bn.create,Iw=$r.create,Dp=Sr.create,Dw=kr.create,Ow=yn.create,Mw=Tr.create,Nw=Pr.create,jw=er.create,Lw=Zt.create,Zw=mt.create,qw=_n.create,Fw=qt.create,Uw=Ge.create,Vw=Ge.strictCreate,Ww=Er.create,Bw=Is.create,Hw=Rr.create,Gw=Tt.create,Jw=Ds.create,Kw=vn.create,Qw=xn.create,Yw=Os.create,Xw=zr.create,e$=Cr.create,t$=Ar.create,r$=Ir.create,n$=tr.create,o$=st.create,s$=nt.create,i$=Pt.create,a$=st.createWithPreprocess,c$=so.create,u$=()=>Ap().optional(),l$=()=>Ip().optional(),d$=()=>Dp().optional(),p$={string:(t=>Xt.create({...t,coerce:!0})),number:(t=>wr.create({...t,coerce:!0})),boolean:(t=>Sr.create({...t,coerce:!0})),bigint:(t=>$r.create({...t,coerce:!0})),date:(t=>kr.create({...t,coerce:!0}))};var f$=D;var m$=h.enum(["read-only","workspace-write","full-auto"]),h$=m$.default("read-only"),g$=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:h$,config:h.record(h.unknown()).default({})}),y$=h.enum(["default-only","auto"]).default("default-only"),_$=h.object({defaultProvider:h.string().optional(),selectionPolicy:y$,providers:h.array(g$).min(1,"At least one provider required")});function rr(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":return"workspace-write";default:return"read-only"}}function Ms(t){return t==="workspace-write"||t==="full-auto"}function Op(t){let e=_$.parse(t);return{defaultProvider:e.defaultProvider,selectionPolicy:e.selectionPolicy,providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}js();uo();ro();fn();vr();import{mkdirSync as Bp,readFileSync as Et,readdirSync as pc,existsSync as nr,unlinkSync as F$,rmdirSync as U$}from"fs";import{join as ce}from"path";import{spawn as Hp}from"child_process";import{randomUUID as V$}from"crypto";function jr(t,e){let r=ce(t,"status.json"),n=JSON.parse(Et(r,"utf-8"));it(r,{...n,...e})}var qs=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;constructor(e=process.cwd(),r){this.jobsDir=ce(e,lp),Bp(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7}submit(e){let r=`${e.provider}-${Date.now()}-${V$().slice(0,6)}`,n=ce(this.jobsDir,r);Bp(n,{recursive:!0});let o={id:r,provider:e.provider,prompt:e.prompt,timeout:e.timeout??3e5,createdAt:new Date().toISOString(),cwd:process.cwd()},s={id:r,state:"queued",provider:e.provider};return it(ce(n,"job.json"),o),it(ce(n,"status.json"),s),ie(ce(n,"prompt.txt"),e.prompt),this.statusCache.set(r,s),this.spawnWorker(n),this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!Ls(e))return null;let r=["completed","error","timed_out","cancelled","missing_cli"],n=this.statusCache.get(e);if(n&&r.includes(n.state))return n;let o=ce(this.jobsDir,e,"status.json");if(!nr(o))return null;let s=JSON.parse(Et(o,"utf-8"));if(s.state==="queued"){let i=ce(this.jobsDir,e,"job.json");try{let a=JSON.parse(Et(i,"utf-8"));if(Date.now()-new Date(a.createdAt).getTime()>6e4){let u={...s,state:"error",completedAt:new Date().toISOString()};return it(o,u),ie(ce(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,u),u}}catch{}}return this.statusCache.set(e,s),s}getResult(e){if(!Ls(e))return null;let r=this.getStatus(e);if(!r)return null;let n=ce(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode},s=ce(n,"output.txt");nr(s)&&(o.output=Et(s,"utf-8"));let i=ce(n,"error.txt");return nr(i)&&(o.error=Et(i,"utf-8")),o}listJobs(){if(!nr(this.jobsDir))return[];let e=pc(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory()),r=[];for(let n of e){let o=ce(this.jobsDir,n.name,"status.json");nr(o)&&r.push(JSON.parse(Et(o,"utf-8")))}return r}cancel(e){if(!Ls(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&dn(r.pid);let n=ce(this.jobsDir,e),o={...r,state:"cancelled",completedAt:new Date().toISOString()};return it(ce(n,"status.json"),o),this.statusCache.set(e,o),!0}cleanup(){if(!nr(this.jobsDir))return 0;let e=pc(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory()),r=[];for(let u of e){let l=ce(this.jobsDir,u.name,"status.json"),d=ce(this.jobsDir,u.name,"job.json");if(!nr(l))continue;let p=JSON.parse(Et(l,"utf-8")),f=null;try{f=JSON.parse(Et(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}let n=["completed","error","timed_out","cancelled","missing_cli"],o=r.filter(u=>n.includes(u.status.state)).sort((u,l)=>{let d=u.descriptor?.createdAt??"",p=l.descriptor?.createdAt??"";return d.localeCompare(p)}),s=0,i=Date.now(),a=this.maxAgeDays*24*60*60*1e3,c=r.length;for(let u of o){let d=(u.descriptor?.createdAt?i-new Date(u.descriptor.createdAt).getTime():1/0)>a,p=c-s>this.maxJobs;if(!d&&!p)continue;let f=ce(this.jobsDir,u.name);try{let g=pc(f);for(let y of g)F$(ce(f,y));U$(f),this.statusCache.delete(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(nr(r)){let n=Hp(process.execPath,[r,e],{detached:!0,stdio:"ignore"});if(n.pid)try{jr(e,{pid:n.pid})}catch{}n.on("error",o=>{o.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(Wp(),Vp)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Et(ce(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){jr(e,{state:"missing_cli",completedAt:new Date().toISOString()}),ie(ce(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Et(ce(e,"prompt.txt"),"utf-8"),c=i(a);jr(e,{state:"running",startedAt:new Date().toISOString()});let u=Nt(s,c),l=Hp(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,g=0;l.stdout.on("data",m=>{f+=m.length,f<=10485760&&(d+=m.toString())}),l.stderr.on("data",m=>{g+=m.length,g<=10485760&&(p+=m.toString())});let y=setTimeout(()=>{Kt(l),ie(ce(e,"output.txt"),d),ie(ce(e,"error.txt"),p),jr(e,{state:"timed_out",completedAt:new Date().toISOString()})},n.timeout);l.on("close",m=>{clearTimeout(y),ie(ce(e,"output.txt"),d),ie(ce(e,"error.txt"),p);let b=d.trim().length>0;jr(e,{state:m===0||b?"completed":"error",exitCode:m??1,completedAt:new Date().toISOString()})}),l.on("error",m=>{clearTimeout(y);let b=m.code==="ENOENT"?"missing_cli":"error";ie(ce(e,"error.txt"),m.message),jr(e,{state:b,completedAt:new Date().toISOString()})})}).catch(()=>{try{jr(e,{state:"error",completedAt:new Date().toISOString()}),ie(ce(e,"error.txt"),"Failed to load job worker module")}catch{}})}};js();vr();import{mkdirSync as W$,readdirSync as Gp,readFileSync as B$,unlinkSync as H$}from"fs";import{join as lo}from"path";function Jp(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}function G$(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function J$(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var Fs=class{tracesDir;writer;constructor(e,r){this.tracesDir=lo(e,dp),W$(this.tracesDir,{recursive:!0}),this.writer=new Ns(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Jp(new Date(r.timestamp)),o=lo(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
12
- `,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=B$(i,"utf-8").split(`
13
- `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);J$(u)?o.push(u):G$(u)&&n.push(u)}catch{}}for(let i of o){let a=n.find(c=>c.traceId===i.traceId&&c.providerId===i.providerId);a&&(a.quality=i.quality)}let s=n;return e.providerId&&(s=s.filter(i=>i.providerId===e.providerId)),e.task&&(s=s.filter(i=>i.task===e.task)),e.traceId&&(s=s.filter(i=>i.traceId===e.traceId)),e.successOnly&&(s=s.filter(i=>i.response.success)),e.failedOnly&&(s=s.filter(i=>!i.response.success)),e.limit!==void 0&&(s=s.slice(0,e.limit)),s}updateQuality(e,r,n){let o=new Date,s={type:"quality_update",traceId:e,providerId:r,timestamp:o.toISOString(),quality:n},i=Jp(o),a=lo(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(s)+`
14
- `,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let s of r){if(!s.quality)continue;let i=`${s.providerId}:${s.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=s.quality.score,a.count+=1,a.totalLatency+=s.latencyMs,n.set(i,a)}let o=new Map;for(let[s,i]of n)o.set(s,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return o}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,o;try{o=Gp(this.tracesDir)}catch{return 0}for(let s of o){if(!s.endsWith(".jsonl"))continue;let i=s.replace(".jsonl",""),a=new Date(i+"T00:00:00.000Z");isNaN(a.getTime())||a<r&&(H$(lo(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=Gp(this.tracesDir).filter(n=>n.endsWith(".jsonl")).sort()}catch{return[]}if(e!==void 0){let n=new Date;n.setDate(n.getDate()-e),r=r.filter(o=>{let s=o.replace(".jsonl",""),i=new Date(s+"T00:00:00.000Z");return!isNaN(i.getTime())&&i>=n})}return r.map(n=>lo(this.tracesDir,n))}};var K$=/[;|&`$(){}!><\n\r\\]/,Us=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),Q$=new Set(["rm","sudo","chmod","chown","mkfs","dd","curl","wget","kill","pkill","killall","mv","cp","sh","bash","zsh","python","perl","ruby","node","npm","npx","eval","exec","source"]);function Kp(t){if(K$.test(t))return{valid:!1,error:"Command contains shell metacharacters (piping, chaining, or subshell operators are not allowed)"};let e=t.split(/\s+/).filter(Boolean);if(e.length===0)return{valid:!1,error:"Empty command"};if(e[0].includes("/")||e[0].includes("\\"))return{valid:!1,error:"Command must not contain path separators (use bare command names only)"};for(let n=1;n<e.length;n++)if(e[n].includes("/")||e[n].includes("\\"))return{valid:!1,error:`Argument must not contain path separators: ${JSON.stringify(e[n])}`};let r=e[0];if(!Us.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...Us].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(Q$.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}vr();var Qp=[{type:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/,description:"AWS Access Key ID"},{type:"private_key",regex:/-----BEGIN\s+(RSA|EC|DSA|OPENSSH)?\s*PRIVATE KEY-----/,description:"Private key header"},{type:"password_assignment",regex:/(?:password|passwd|pwd)\s*[:=]\s*["']?[^\s"',;]{4,}["']?/i,description:"Password assignment"},{type:"api_key_assignment",regex:/(?:api[_-]?key|apikey|secret[_-]?key)\s*[:=]\s*["']?[^\s"',;]{8,}["']?/i,description:"API key assignment"},{type:"bearer_token",regex:/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/,description:"Bearer JWT token"},{type:"generic_secret",regex:/(?:token|secret|credential)\s*[:=]\s*["'][^"']{8,}["']/i,description:"Generic secret assignment"}],Yp=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function Xp(t){let e=Array.isArray(t)?t:t.split(`
15
- `),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of Qp){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!Yp.some(u=>u.test(a))){r.push({type:s.type,pattern:s.description,line:n+1,excerpt:o.length>80?o.slice(0,80)+"...":o});break}}}return{clean:r.length===0,findings:r}}function fc(t){if(t.length===0)return t;let e=t.split(`
16
- `);for(let r=0;r<e.length;r++){let n=e[r];for(let o of Qp){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>Yp.some(a=>a.test(i))?i:xp)}e[r]=n}return e.join(`
17
- `)}vr();import{execFileSync as Y$}from"child_process";import{existsSync as ef,rmSync as X$,mkdirSync as eS}from"fs";import{join as tf}from"path";var Vs=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=tf(e,pp)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=tf(this.worktreeBaseDir,r);eS(this.worktreeBaseDir,{recursive:!0}),ef(o)&&this.forceRemoveWorktree(o),this.gitSafe(["branch","-D",n]),this.git(["worktree","add","-b",n,o,"HEAD"]);let s={id:e,path:o,branch:n};return this.worktrees.set(e,s),s}remove(e){let r=this.worktrees.get(e);r&&(this.forceRemoveWorktree(r.path),this.gitSafe(["branch","-D",r.branch]),this.worktrees.delete(e))}get(e){return this.worktrees.get(e)}list(){return[...this.worktrees.values()]}listOrphans(){let e=this.gitSafe(["worktree","list","--porcelain"]);if(!e)return[];let r=[],n="",o="",s=()=>{n.includes(".agestra/worktrees")&&o.startsWith("agestra-worker/")&&([...this.worktrees.values()].some(a=>a.path===n)||r.push({path:n,branch:o})),n="",o=""};for(let i of e.split(`
18
- `))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?o=i.slice(18):i===""&&s();return n&&s(),r}cleanOrphans(){let e=this.listOrphans(),r=0;for(let n of e)this.forceRemoveWorktree(n.path),this.gitSafe(["branch","-D",n.branch]),r++;return r}forceRemoveWorktree(e){this.gitSafe(["worktree","remove",e])===null&&this.gitSafe(["worktree","remove","--force",e])===null&&(ef(e)&&X$(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return Y$("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var tS=["npm","node","git","tsc"];function rf(t){return{task:t.taskDescription,files:{readonly:t.filesToRead??[],readwrite:t.filesToModify??[]},constraints:t.constraints,success_criteria:t.successCriteria??[],permissions:{sandbox_root:t.workingDir,allowed_commands:[...tS]},timeout_minutes:t.timeoutMinutes??10}}function nf(t){let e=[];return(!t.task||t.task.trim().length===0)&&e.push("task must not be empty"),(!t.permissions.sandbox_root||t.permissions.sandbox_root.trim().length===0)&&e.push("permissions.sandbox_root must not be empty"),t.timeout_minutes<=0&&e.push("timeout_minutes must be positive"),{valid:e.length===0,errors:e}}var ke;(function(t){t.SPAWNING="SPAWNING",t.RUNNING="RUNNING",t.COLLECTING="COLLECTING",t.COMPLETED="COMPLETED",t.FAILED="FAILED",t.CANCELLING="CANCELLING",t.CANCELLED="CANCELLED",t.TIMEOUT="TIMEOUT"})(ke||(ke={}));var Ws=10,mc=2e4;import{spawn as aS}from"child_process";import{writeFileSync as gc,mkdirSync as cS,readFileSync as cf,existsSync as uf}from"fs";import{isAbsolute as lf,join as po,resolve as df}from"path";import{randomBytes as uS}from"crypto";import{execFileSync as lS}from"child_process";vr();fn();ro();uo();uo();import{readFileSync as of}from"fs";var hc=class{builders=new Map;register(e,r){this.builders.set(e,r)}has(e){return this.builders.has(e)}build(e,r,n,o){let s=this.builders.get(e);if(!s){let i=[...this.builders.keys()];throw new Error(`No CLI launch builder registered for provider "${e}". Known: [${i.join(", ")}]`)}return s(r,n,o)}knownProviders(){return[...this.builders.keys()]}};function rS(t,e,r){let n=sf(t,e,r);return{command:"codex",args:["exec","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function nS(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",sf(t,e,r)]}}function sf(t,e,r){let n=of(t,"utf-8"),o=oS(r,e);return["You are an autonomous coding worker operating in the current workspace.","Execute the task manifest below without asking for confirmation.","Stay within the workspace, respect read-only vs read-write boundaries, and summarize changes plus verification at the end.","",n,o].join(`
19
- `)}function af(){let t=new hc;return t.register("codex",rS),t.register("gemini",nS),t}function oS(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!lc(o,e));if(r.length===0)return"";let n=["Read-only file snapshots:","These files may live outside the worker sandbox root. Use the embedded contents below as authoritative context and do not attempt to edit them.",""];for(let o of r.slice(0,Ws))try{let s=of(o,"utf-8"),i=s.length>mc?`${s.slice(0,mc)}
20
- ...[truncated]`:s;n.push(`### File: ${o}`),n.push("```"),n.push(i),n.push("```"),n.push("")}catch(s){let i=s instanceof Error?s.message:String(s);n.push(`### File: ${o}`),n.push(`[unavailable: ${i}]`),n.push("")}return r.length>Ws&&(n.push(`...[${r.length-Ws} additional read-only files omitted]`),n.push("")),n.join(`
21
- `)}var fo=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=po(e,gp),this.worktreeManager=new Vs(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??af()}knownProviders(){let e=new Set;for(let r of this.cliBuilderRegistry.knownProviders())e.add(r);for(let r of this.providerPolicies.keys())e.add(r);return[...e]}activeWorkerCount(){let e=0;for(let r of this.workers.values()){let n=r.info.state;(n===ke.RUNNING||n===ke.COLLECTING)&&e++}return e}spawn(e){if(this.activeWorkerCount()>=3)throw new Error(`Worker quota exceeded: ${this.activeWorkerCount()}/${3} workers already active. Wait for existing workers to complete or call stop() before spawning a new one.`);let r=this.validateWorkingDirectory(e.workingDir),n=this.normalizeReadablePaths(e.filesToRead,r),o=this.normalizeWritablePaths(e.filesToModify,r);this.assertAutonomousExecutionAllowed(e.provider);let s=[e.taskDescription,e.constraints??""],i=Xp(s);if(!i.clean){let j=i.findings.map(Se=>Se.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${j}`)}let a=uS(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=po(this.workersBaseDir,c);cS(u,{recursive:!0});let l=rf({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=nf(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=po(u,"task-manifest.json");gc(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,g=po(u,"stdout.log"),y=po(u,"stderr.log"),m=f?.path??r,b=this.cliBuilderRegistry.build(e.provider,p,m,n),_=Nt(b.command,b.args),w=aS(_.command,_.args,{cwd:m,env:t.buildWorkerEnv(),detached:!0,stdio:[b.stdin?"pipe":"ignore","pipe","pipe"]}),k=[],P=[];w.stdout?.on("data",j=>k.push(j)),w.stderr?.on("data",j=>P.push(j)),b.stdin!==void 0&&w.stdin?.end(b.stdin),w.unref();let U={workerId:c,provider:e.provider,state:ke.RUNNING,pid:w.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},Z={info:U,process:w,workerDir:u,manifestPath:p,outputPath:g,errorPath:y};if(this.workers.set(c,Z),e.timeoutMinutes){let j=e.timeoutMinutes*6e4;setTimeout(()=>{if(Z.info.state===ke.RUNNING){Z.info.state=ke.TIMEOUT,Z.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let Q=Z.process?.pid;Q&&dn(Q)}},j).unref()}return w.on("close",j=>{Z.info.exitCode=j;try{gc(g,Buffer.concat(k).toString("utf-8")),gc(y,Buffer.concat(P).toString("utf-8"))}catch{}Z.info.state===ke.CANCELLING?Z.info.state=ke.CANCELLED:j===0?Z.info.state=ke.COLLECTING:(Z.info.state=ke.FAILED,Z.info.error=`Process exited with code ${j}`)}),U}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{uf(r.outputPath)&&(o=cf(r.outputPath,"utf-8").split(`
11
+ deps: ${r}}`};var zD={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=OD(t);Cb(t,e),Db(t,r)}};function OD({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Cb(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Cs.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Cs.checkReportMissingProp)(t,u)}):(r.if((0,Zd._)`${c} && (${(0,Cs.checkMissingProp)(t,a,s)})`),(0,Cs.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=Cb;function Db(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,DD.alwaysValidSchema)(s,e[a])||(r.if((0,Cs.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ot.validateSchemaDeps=Db;Ot.default=zD});var Mb=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Ob=H(),MD=oe(),jD={message:"property name must be valid",params:({params:t})=>(0,Ob._)`{propertyName: ${t.propertyName}}`},ND={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jD,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,MD.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Ob.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ud.default=ND});var Vd=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var La=dt(),xt=H(),LD=Gt(),Fa=oe(),FD={message:"must NOT have additional properties",params:({params:t})=>(0,xt._)`{additionalProperty: ${t.additionalProperty}}`},ZD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:FD,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Fa.alwaysValidSchema)(i,r))return;let u=(0,La.allSchemaProperties)(n.properties),l=(0,La.allSchemaProperties)(n.patternProperties);d(),t.ok((0,xt._)`${s} === ${LD.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let _;if(u.length>8){let S=(0,Fa.schemaRefOrVal)(i,n.properties,"properties");_=(0,La.isOwnProperty)(e,S,y)}else u.length?_=(0,xt.or)(...u.map(S=>(0,xt._)`${y} === ${S}`)):_=xt.nil;return l.length&&(_=(0,xt.or)(_,...l.map(S=>(0,xt._)`${(0,La.usePattern)(t,S)}.test(${y})`))),(0,xt.not)(_)}function f(y){e.code((0,xt._)`delete ${o}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Fa.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(y,_,!1),e.if((0,xt.not)(_),()=>{t.reset(),f(y)})):(g(y,_),a||e.if((0,xt.not)(_),()=>e.break()))}}function g(y,_,S){let v={keyword:"additionalProperties",dataProp:y,dataPropType:Fa.Type.Str};S===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(v,_)}}};qd.default=ZD});var Lb=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var UD=vs(),jb=dt(),Bd=oe(),Nb=Vd(),qD={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Nb.default.code(new UD.KeywordCxt(s,Nb.default,"additionalProperties"));let i=(0,jb.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Bd.mergeEvaluated.props(e,(0,Bd.toHash)(i),s.props));let a=i.filter(d=>!(0,Bd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,jb.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Wd.default=qD});var qb=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Fb=dt(),Za=H(),Zb=oe(),Ub=oe(),VD={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Fb.allSchemaProperties)(r),c=a.filter(g=>(0,Zb.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Za.Name)&&(s.props=(0,Ub.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?m(g):(e.var(l,!0),m(g),e.if(l))}function f(g){for(let y in u)new RegExp(g).test(y)&&(0,Zb.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,Za._)`${(0,Fb.usePattern)(t,g)}.test(${y})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Ub.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Za._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Za.not)(l),()=>e.break())})})}}};Hd.default=VD});var Vb=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var BD=oe(),WD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,BD.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Kd.default=WD});var Bb=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var HD=dt(),KD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:HD.validateUnion,error:{message:"must match a schema in anyOf"}};Jd.default=KD});var Wb=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var Ua=H(),JD=oe(),GD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ua._)`{passingSchemas: ${t.passing}}`},YD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:GD,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,JD.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ua._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ua._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ua.Name)})})}}};Gd.default=YD});var Hb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var QD=oe(),XD={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,QD.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Yd.default=XD});var Gb=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var qa=H(),Jb=oe(),ez={message:({params:t})=>(0,qa.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,qa._)`{failingKeyword: ${t.ifClause}}`},tz={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ez,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Jb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Kb(n,"then"),s=Kb(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,qa.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,qa._)`${l}`):t.setParams({ifClause:l})}}}};function Kb(t,e){let r=t.schema[e];return r!==void 0&&!(0,Jb.alwaysValidSchema)(t,r)}Qd.default=tz});var Yb=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var rz=oe(),nz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,rz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Xd.default=nz});var Qb=E(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var oz=Md(),sz=Eb(),iz=jd(),az=Ib(),cz=Ab(),uz=zb(),lz=Mb(),dz=Vd(),pz=Lb(),fz=qb(),mz=Vb(),hz=Bb(),gz=Wb(),yz=Hb(),vz=Gb(),_z=Yb();function bz(t=!1){let e=[mz.default,hz.default,gz.default,yz.default,vz.default,_z.default,lz.default,dz.default,uz.default,pz.default,fz.default];return t?e.push(sz.default,az.default):e.push(oz.default,iz.default),e.push(cz.default),e}ep.default=bz});var Xb=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ke=H(),wz={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},xz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:wz,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ke._)`${m}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(S(),v()));function S(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function v(){let k=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,x=(0,ke._)`(typeof ${_} == "function" ? ${k} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[g,y,_]=v(m);g===e&&t.pass(k());function S(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(x){let z=x instanceof RegExp?(0,ke.regexpCode)(x):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:x,code:z});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,ke._)`${O}.validate`]:["string",x,O]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof y=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};tp.default=xz});var ew=E(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var Sz=Xb(),$z=[Sz.default];rp.default=$z});var tw=E(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.contentVocabulary=Yn.metadataVocabulary=void 0;Yn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Yn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var nw=E(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var kz=lb(),Pz=$b(),Tz=Qb(),Ez=ew(),rw=tw(),Rz=[kz.default,Pz.default,(0,Tz.default)(),Ez.default,rw.metadataVocabulary,rw.contentVocabulary];np.default=Rz});var sw=E(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.DiscrError=void 0;var ow;(function(t){t.Tag="tag",t.Mapping="mapping"})(ow||(Va.DiscrError=ow={}))});var aw=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var Qn=H(),op=sw(),iw=ka(),Iz=_s(),Az=oe(),Cz={message:({params:{discrError:t,tagName:e}})=>t===op.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Qn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Dz={keyword:"discriminator",type:"object",schemaType:"object",error:Cz,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Qn._)`${r}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:op.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,Qn._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:op.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,Qn.Name),m}function p(){var f;let m={},g=_(o),y=!0;for(let k=0;k<i.length;k++){let x=i[k];if(x?.$ref&&!(0,Az.schemaHasRulesButRef)(x,s.self.RULES)){let O=x.$ref;if(x=iw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),x instanceof iw.SchemaEnv&&(x=x.schema),x===void 0)throw new Iz.default(s.opts.uriResolver,s.baseId,O)}let z=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||_(x)),S(z,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:k}){return Array.isArray(k)&&k.includes(a)}function S(k,x){if(k.const)v(k.const,x);else if(k.enum)for(let z of k.enum)v(z,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(k,x){if(typeof k!="string"||k in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[k]=x}}}};sp.default=Dz});var cw=E((wB,zz)=>{zz.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ap=E((ye,ip)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var Oz=ob(),Mz=nw(),jz=aw(),uw=cw(),Nz=["/properties"],Ba="http://json-schema.org/draft-07/schema",Xn=class extends Oz.default{_addVocabularies(){super._addVocabularies(),Mz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(jz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(uw,Nz):uw;this.addMetaSchema(e,Ba,!1),this.refs["http://json-schema.org/schema"]=Ba}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ba)?Ba:void 0)}};ye.Ajv=Xn;ip.exports=ye=Xn;ip.exports.Ajv=Xn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Xn;var Lz=vs();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return Lz.KeywordCxt}});var eo=H();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return eo._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return eo.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return eo.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return eo.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return eo.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return eo.CodeGen}});var Fz=Sa();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return Fz.default}});var Zz=_s();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return Zz.default}})});var yw=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.formatNames=jt.fastFormats=jt.fullFormats=void 0;function Mt(t,e){return{validate:t,compare:e}}jt.fullFormats={date:Mt(fw,dp),time:Mt(up(!0),pp),"date-time":Mt(lw(!0),hw),"iso-time":Mt(up(),mw),"iso-date-time":Mt(lw(),gw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Hz,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:eO,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:Kz,int32:{type:"number",validate:Yz},int64:{type:"number",validate:Qz},float:{type:"number",validate:pw},double:{type:"number",validate:pw},password:!0,binary:!0};jt.fastFormats={...jt.fullFormats,date:Mt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,dp),time:Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pp),"date-time":Mt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,hw),"iso-time":Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mw),"iso-date-time":Mt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gw),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};jt.formatNames=Object.keys(jt.fullFormats);function Uz(t){return t%4===0&&(t%100!==0||t%400===0)}var qz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Vz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fw(t){let e=qz.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Uz(r)?29:Vz[n])}function dp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var cp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function up(t){return function(r){let n=cp.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function pp(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function mw(t,e){if(!(t&&e))return;let r=cp.exec(t),n=cp.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var lp=/t|\s/i;function lw(t){let e=up(t);return function(n){let o=n.split(lp);return o.length===2&&fw(o[0])&&e(o[1])}}function hw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function gw(t,e){if(!(t&&e))return;let[r,n]=t.split(lp),[o,s]=e.split(lp),i=dp(r,o);if(i!==void 0)return i||pp(n,s)}var Bz=/\/|:/,Wz=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Hz(t){return Bz.test(t)&&Wz.test(t)}var dw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Kz(t){return dw.lastIndex=0,dw.test(t)}var Jz=-(2**31),Gz=2**31-1;function Yz(t){return Number.isInteger(t)&&t<=Gz&&t>=Jz}function Qz(t){return Number.isInteger(t)}function pw(){return!0}var Xz=/[^\\]\\Z/;function eO(t){if(Xz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var vw=E(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.formatLimitDefinition=void 0;var tO=ap(),St=H(),br=St.operators,Wa={formatMaximum:{okStr:"<=",ok:br.LTE,fail:br.GT},formatMinimum:{okStr:">=",ok:br.GTE,fail:br.LT},formatExclusiveMaximum:{okStr:"<",ok:br.LT,fail:br.GTE},formatExclusiveMinimum:{okStr:">",ok:br.GT,fail:br.LTE}},rO={message:({keyword:t,schemaCode:e})=>(0,St.str)`should be ${Wa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,St._)`{comparison: ${Wa[t].okStr}, limit: ${e}}`};to.formatLimitDefinition={keyword:Object.keys(Wa),type:"string",schemaType:"string",$data:!0,error:rO,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new tO.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,St._)`${p}[${c.schemaCode}]`);t.fail$data((0,St.or)((0,St._)`typeof ${f} != "object"`,(0,St._)`${f} instanceof RegExp`,(0,St._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,St._)`${i.code.formats}${(0,St.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,St._)`${p}.compare(${r}, ${n}) ${Wa[o].fail} 0`}},dependencies:["format"]};var nO=t=>(t.addKeyword(to.formatLimitDefinition),t);to.default=nO});var xw=E((Ds,ww)=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var ro=yw(),oO=vw(),fp=H(),_w=new fp.Name("fullFormats"),sO=new fp.Name("fastFormats"),mp=(t,e={keywords:!0})=>{if(Array.isArray(e))return bw(t,e,ro.fullFormats,_w),t;let[r,n]=e.mode==="fast"?[ro.fastFormats,sO]:[ro.fullFormats,_w],o=e.formats||ro.formatNames;return bw(t,o,r,n),e.keywords&&(0,oO.default)(t),t};mp.get=(t,e="full")=>{let n=(e==="fast"?ro.fastFormats:ro.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function bw(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,fp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}ww.exports=Ds=mp;Object.defineProperty(Ds,"__esModule",{value:!0});Ds.default=mp});import{readFileSync as lN}from"fs";import{join as Rc}from"path";import{fileURLToPath as dN}from"url";var cn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Zs=class extends cn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},me=class extends cn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var un=class extends cn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},He=class extends cn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var hf={ollama:{tier:"tool"},"claude-cli":{tier:"agent",maxComplexity:"complex"},"gemini-cli":{tier:"agent",maxComplexity:"complex"},"codex-cli":{tier:"agent",maxComplexity:"complex"},"claude-host":{tier:"agent",maxComplexity:"complex"},"codex-host":{tier:"agent",maxComplexity:"complex"},"gemini-host":{tier:"agent",maxComplexity:"complex"}},jS={ollama:{invocation:"http",roles:["participant","tool"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"claude-cli":{invocation:"cli",roles:["participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"codex-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"claude-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"codex-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0}};function Mc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Bs(t,e,r,n=t){let o=hf[n]??hf[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Mc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function tr(t,e){let r=jS[t.type],n=r?.roles?[...r.roles]:["participant"];return{id:t.id,type:t.type,invocation:r?.invocation??"unknown",roles:n,supportsAutonomousExecution:r?.supportsAutonomousExecution??!1,supportsReadOnlyChat:r?.supportsReadOnlyChat??!0,supportsToolUse:e?.supportsToolUse??r?.supportsToolUse??!1}}var Ws={low:0,medium:.5,high:.7},NS={chat:"low",simple_review:"low",code_review:"medium",code_generation:"medium",design:"medium",writing:"medium",analysis:"medium",ideation:"medium",debate_turn:"medium",architecture:"high",cross_validate:"high",complex_refactor:"high"};function gf(t,e){return e?.[t]??NS[t]??"low"}function Hs(t,e,r=Ws){return t>=r[e]}var Ks=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.getAll().find(n=>n.type==="claude-host"||n.type==="claude-cli")}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new Zs(e);return r}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(e=>e.isAvailable())}getAvailableDescriptors(){return this.getAvailable().map(e=>this.getDescriptor(e.id))}getByCapability(e){return this.getAvailable().filter(r=>r.getCapabilities().strengths.includes(e))}has(e){return this.providers.has(e)}getCapability(e){let r=this.get(e);return Bs(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??tr(r,r.getCapabilities())}getByTier(e){return this.getAvailable().filter(r=>this.getCapability(r.id).tier===e)}getByRole(e){return this.getAvailable().filter(r=>this.getDescriptor(r.id).roles.includes(e))}getBestForTask(e,r,n,o){let s=this.getAvailable();if(s.length===0)return;if(!r)return s[0];let i=n??gf(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],g=c.get(m)??{totalScore:0,count:0};g.totalScore+=f.avgScore*f.count,g.count+=f.count,c.set(m,g)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return Hs(m,i,o)});if(u.length===0)return;let l,d=-1;for(let p of u){let f=`${p.id}:${e}`,m=a.get(f);m&&m.avgScore>d&&(d=m.avgScore,l=p)}return l??u[0]}};var h={};Ze(h,{BRAND:()=>l$,DIRTY:()=>$r,EMPTY_PATH:()=>US,INVALID:()=>j,NEVER:()=>K$,OK:()=>Oe,ParseStatus:()=>Te,Schema:()=>B,ZodAny:()=>or,ZodArray:()=>qt,ZodBigInt:()=>Pr,ZodBoolean:()=>Tr,ZodBranded:()=>yo,ZodCatch:()=>Nr,ZodDate:()=>Er,ZodDefault:()=>jr,ZodDiscriminatedUnion:()=>Ys,ZodEffects:()=>it,ZodEnum:()=>Or,ZodError:()=>Ke,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>Xs,ZodIntersection:()=>Cr,ZodIssueCode:()=>$,ZodLazy:()=>Dr,ZodLiteral:()=>zr,ZodMap:()=>bn,ZodNaN:()=>xn,ZodNativeEnum:()=>Mr,ZodNever:()=>mt,ZodNull:()=>Ir,ZodNullable:()=>Et,ZodNumber:()=>kr,ZodObject:()=>Je,ZodOptional:()=>ot,ZodParsedType:()=>R,ZodPipeline:()=>vo,ZodPromise:()=>sr,ZodReadonly:()=>Lr,ZodRecord:()=>Qs,ZodSchema:()=>B,ZodSet:()=>wn,ZodString:()=>nr,ZodSymbol:()=>vn,ZodTransformer:()=>it,ZodTuple:()=>Tt,ZodType:()=>B,ZodUndefined:()=>Rr,ZodUnion:()=>Ar,ZodUnknown:()=>Ut,ZodVoid:()=>_n,addIssueToContext:()=>T,any:()=>_$,array:()=>S$,bigint:()=>m$,boolean:()=>Tf,coerce:()=>H$,custom:()=>$f,date:()=>h$,datetimeRegex:()=>xf,defaultErrorMap:()=>Ft,discriminatedUnion:()=>T$,effect:()=>L$,enum:()=>M$,function:()=>D$,getErrorMap:()=>hn,getParsedType:()=>Pt,instanceof:()=>p$,intersection:()=>E$,isAborted:()=>Js,isAsync:()=>gn,isDirty:()=>Gs,isValid:()=>rr,late:()=>d$,lazy:()=>z$,literal:()=>O$,makeIssue:()=>go,map:()=>A$,nan:()=>f$,nativeEnum:()=>j$,never:()=>w$,null:()=>v$,nullable:()=>Z$,number:()=>Pf,object:()=>$$,objectUtil:()=>jc,oboolean:()=>W$,onumber:()=>B$,optional:()=>F$,ostring:()=>V$,pipeline:()=>q$,preprocess:()=>U$,promise:()=>N$,quotelessJson:()=>LS,record:()=>I$,set:()=>C$,setErrorMap:()=>ZS,strictObject:()=>k$,string:()=>kf,symbol:()=>g$,transformer:()=>L$,tuple:()=>R$,undefined:()=>y$,union:()=>P$,unknown:()=>b$,util:()=>G,void:()=>x$});var G;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(G||(G={}));var jc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(jc||(jc={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pt=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var $=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),LS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ke=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ke.create=t=>new Ke(t);var FS=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,G.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${G.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${G.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${G.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:G.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case $.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,G.assertNever(t)}return{message:r}},Ft=FS;var yf=Ft;function ZS(t){yf=t}function hn(){return yf}var go=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},US=[];function T(t,e){let r=hn(),n=go({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ft?void 0:Ft].filter(o=>!!o)});t.common.issues.push(n)}var Te=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return j;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return j;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},j=Object.freeze({status:"aborted"}),$r=t=>({status:"dirty",value:t}),Oe=t=>({status:"valid",value:t}),Js=t=>t.status==="aborted",Gs=t=>t.status==="dirty",rr=t=>t.status==="valid",gn=t=>typeof Promise<"u"&&t instanceof Promise;var A;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(A||(A={}));var st=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},vf=(t,e)=>{if(rr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ke(t.common.issues);return this._error=r,this._error}}};function U(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var B=class{get description(){return this._def.description}_getType(e){return Pt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(gn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return vf(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return rr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>rr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(gn(o)?o:Promise.resolve(o));return vf(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:$.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new it({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ot.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return qt.create(this)}promise(){return sr.create(this,this._def)}or(e){return Ar.create([this,e],this._def)}and(e){return Cr.create(this,e,this._def)}transform(e){return new it({...U(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new jr({...U(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new yo({typeName:P.ZodBranded,type:this,...U(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Nr({...U(this._def),innerType:this,catchValue:r,typeName:P.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vo.create(this,e)}readonly(){return Lr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qS=/^c[^\s-]{8,}$/i,VS=/^[0-9a-z]+$/,BS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,WS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,HS=/^[a-z0-9_-]{21}$/i,KS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,JS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,GS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,YS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Nc,QS=/^(?:(?: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])$/,XS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,e$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,t$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,r$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,n$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bf="((\\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])))",o$=new RegExp(`^${bf}$`);function wf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function s$(t){return new RegExp(`^${wf(t)}$`)}function xf(t){let e=`${bf}T${wf(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function i$(t,e){return!!((e==="v4"||!e)&&QS.test(t)||(e==="v6"||!e)&&e$.test(t))}function a$(t,e){if(!KS.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function c$(t,e){return!!((e==="v4"||!e)&&XS.test(t)||(e==="v6"||!e)&&t$.test(t))}var nr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.string,received:s.parsedType}),j}let n=new Te,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")GS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Nc||(Nc=new RegExp(YS,"u")),Nc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")WS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")HS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")qS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")VS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")BS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:$.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:$.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?xf(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?o$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?s$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?JS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?i$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?a$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?c$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?r$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?n$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):G.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...A.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...A.errToObj(e)})}url(e){return this._addCheck({kind:"url",...A.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...A.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...A.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...A.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...A.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...A.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...A.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...A.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...A.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...A.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...A.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...A.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...A.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...A.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...A.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...A.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...A.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...A.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...A.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...A.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...A.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...A.errToObj(r)})}nonempty(e){return this.min(1,A.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};nr.create=t=>new nr({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...U(t)});function u$(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var kr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.number,received:s.parsedType}),j}let n,o=new Te;for(let s of this._def.checks)s.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?u$(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_finite,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:A.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:A.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};kr.create=t=>new kr({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...U(t)});var Pr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,o=new Te;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.bigint,received:r.parsedType}),j}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Pr.create=t=>new Pr({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...U(t)});var Tr=class extends B{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.boolean,received:n.parsedType}),j}return Oe(e.data)}};Tr.create=t=>new Tr({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...U(t)});var Er=class t extends B{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.date,received:s.parsedType}),j}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_date}),j}let n=new Te,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):G.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:A.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:A.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Er.create=t=>new Er({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...U(t)});var vn=class extends B{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.symbol,received:n.parsedType}),j}return Oe(e.data)}};vn.create=t=>new vn({typeName:P.ZodSymbol,...U(t)});var Rr=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.undefined,received:n.parsedType}),j}return Oe(e.data)}};Rr.create=t=>new Rr({typeName:P.ZodUndefined,...U(t)});var Ir=class extends B{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.null,received:n.parsedType}),j}return Oe(e.data)}};Ir.create=t=>new Ir({typeName:P.ZodNull,...U(t)});var or=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}};or.create=t=>new or({typeName:P.ZodAny,...U(t)});var Ut=class extends B{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oe(e.data)}};Ut.create=t=>new Ut({typeName:P.ZodUnknown,...U(t)});var mt=class extends B{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.never,received:r.parsedType}),j}};mt.create=t=>new mt({typeName:P.ZodNever,...U(t)});var _n=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.void,received:n.parsedType}),j}return Oe(e.data)}};_n.create=t=>new _n({typeName:P.ZodVoid,...U(t)});var qt=class t extends B{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:$.invalid_type,expected:R.array,received:r.parsedType}),j;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?$.too_big:$.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new st(r,i,r.path,a)))).then(i=>Te.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new st(r,i,r.path,a)));return Te.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:A.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:A.toString(r)}})}nonempty(e){return this.min(1,e)}};qt.create=(t,e)=>new qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...U(e)});function yn(t){if(t instanceof Je){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ot.create(yn(n))}return new Je({...t._def,shape:()=>e})}else return t instanceof qt?new qt({...t._def,type:yn(t.element)}):t instanceof ot?ot.create(yn(t.unwrap())):t instanceof Et?Et.create(yn(t.unwrap())):t instanceof Tt?Tt.create(t.items.map(e=>yn(e))):t}var Je=class t extends B{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=G.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:$.invalid_type,expected:R.object,received:u.parsedType}),j}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new st(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(T(o,{code:$.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new st(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Te.mergeObjectSync(n,u)):Te.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return A.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:A.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:P.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of G.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return yn(this)}partial(e){let r={};for(let n of G.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ot;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Sf(G.objectKeys(this.shape))}};Je.create=(t,e)=>new Je({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:P.ZodObject,...U(e)});Je.strictCreate=(t,e)=>new Je({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:P.ZodObject,...U(e)});Je.lazycreate=(t,e)=>new Je({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:P.ZodObject,...U(e)});var Ar=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ke(a.ctx.common.issues));return T(r,{code:$.invalid_union,unionErrors:i}),j}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ke(c));return T(r,{code:$.invalid_union,unionErrors:a}),j}}get options(){return this._def.options}};Ar.create=(t,e)=>new Ar({options:t,typeName:P.ZodUnion,...U(e)});var Zt=t=>t instanceof Dr?Zt(t.schema):t instanceof it?Zt(t.innerType()):t instanceof zr?[t.value]:t instanceof Or?t.options:t instanceof Mr?G.objectValues(t.enum):t instanceof jr?Zt(t._def.innerType):t instanceof Rr?[void 0]:t instanceof Ir?[null]:t instanceof ot?[void 0,...Zt(t.unwrap())]:t instanceof Et?[null,...Zt(t.unwrap())]:t instanceof yo||t instanceof Lr?Zt(t.unwrap()):t instanceof Nr?Zt(t._def.innerType):[],Ys=class t extends B{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:$.invalid_type,expected:R.object,received:r.parsedType}),j;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),j)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Zt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:P.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...U(n)})}};function Lc(t,e){let r=Pt(t),n=Pt(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=G.objectKeys(e),s=G.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Lc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Lc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Cr=class extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Js(s)||Js(i))return j;let a=Lc(s.value,i.value);return a.valid?((Gs(s)||Gs(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:$.invalid_intersection_types}),j)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Cr.create=(t,e,r)=>new Cr({left:t,right:e,typeName:P.ZodIntersection,...U(r)});var Tt=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:$.invalid_type,expected:R.array,received:n.parsedType}),j;if(n.data.length<this._def.items.length)return T(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),j;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new st(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Te.mergeArray(r,i)):Te.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Tt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tt({items:t,typeName:P.ZodTuple,rest:null,...U(e)})};var Qs=class t extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:$.invalid_type,expected:R.object,received:n.parsedType}),j;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new st(n,a,n.path,a)),value:i._parse(new st(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Te.mergeObjectAsync(r,o):Te.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof B?new t({keyType:e,valueType:r,typeName:P.ZodRecord,...U(n)}):new t({keyType:nr.create(),valueType:e,typeName:P.ZodRecord,...U(r)})}},bn=class extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:$.invalid_type,expected:R.map,received:n.parsedType}),j;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new st(n,a,n.path,[u,"key"])),value:s._parse(new st(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return j;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return j;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};bn.create=(t,e,r)=>new bn({valueType:e,keyType:t,typeName:P.ZodMap,...U(r)});var wn=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:$.invalid_type,expected:R.set,received:n.parsedType}),j;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return j;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new st(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:A.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};wn.create=(t,e)=>new wn({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...U(e)});var Xs=class t extends B{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:$.invalid_type,expected:R.function,received:r.parsedType}),j;function n(a,c){return go({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hn(),Ft].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return go({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hn(),Ft].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof sr){let a=this;return Oe(async function(...c){let u=new Ke([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Oe(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ke([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ke([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Tt.create(e).rest(Ut.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Tt.create([]).rest(Ut.create()),returns:r||Ut.create(),typeName:P.ZodFunction,...U(n)})}},Dr=class extends B{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Dr.create=(t,e)=>new Dr({getter:t,typeName:P.ZodLazy,...U(e)});var zr=class extends B{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),j}return{status:"valid",value:e.data}}get value(){return this._def.value}};zr.create=(t,e)=>new zr({value:t,typeName:P.ZodLiteral,...U(e)});function Sf(t,e){return new Or({values:t,typeName:P.ZodEnum,...U(e)})}var Or=class t extends B{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:G.joinValues(n),received:r.parsedType,code:$.invalid_type}),j}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:$.invalid_enum_value,options:n}),j}return Oe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Or.create=Sf;var Mr=class extends B{_parse(e){let r=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=G.objectValues(r);return T(n,{expected:G.joinValues(o),received:n.parsedType,code:$.invalid_type}),j}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=G.objectValues(r);return T(n,{received:n.data,code:$.invalid_enum_value,options:o}),j}return Oe(e.data)}get enum(){return this._def.values}};Mr.create=(t,e)=>new Mr({values:t,typeName:P.ZodNativeEnum,...U(e)});var sr=class extends B{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:$.invalid_type,expected:R.promise,received:r.parsedType}),j;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Oe(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};sr.create=(t,e)=>new sr({type:t,typeName:P.ZodPromise,...U(e)});var it=class extends B{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return j;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?j:c.status==="dirty"?$r(c.value):r.value==="dirty"?$r(c.value):c});{if(r.value==="aborted")return j;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?j:a.status==="dirty"?$r(a.value):r.value==="dirty"?$r(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?j:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?j:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!rr(i))return j;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>rr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):j);G.assertNever(o)}};it.create=(t,e,r)=>new it({schema:t,typeName:P.ZodEffects,effect:e,...U(r)});it.createWithPreprocess=(t,e,r)=>new it({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...U(r)});var ot=class extends B{_parse(e){return this._getType(e)===R.undefined?Oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ot.create=(t,e)=>new ot({innerType:t,typeName:P.ZodOptional,...U(e)});var Et=class extends B{_parse(e){return this._getType(e)===R.null?Oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(t,e)=>new Et({innerType:t,typeName:P.ZodNullable,...U(e)});var jr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};jr.create=(t,e)=>new jr({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...U(e)});var Nr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return gn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...U(e)});var xn=class extends B{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.nan,received:n.parsedType}),j}return{status:"valid",value:e.data}}};xn.create=t=>new xn({typeName:P.ZodNaN,...U(t)});var l$=Symbol("zod_brand"),yo=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vo=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?j:s.status==="dirty"?(r.dirty(),$r(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?j:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:P.ZodPipeline})}},Lr=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(rr(o)&&(o.value=Object.freeze(o.value)),o);return gn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Lr.create=(t,e)=>new Lr({innerType:t,typeName:P.ZodReadonly,...U(e)});function _f(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function $f(t,e={},r){return t?or.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=_f(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=_f(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):or.create()}var d$={object:Je.lazycreate},P;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(P||(P={}));var p$=(t,e={message:`Input not instance of ${t.name}`})=>$f(r=>r instanceof t,e),kf=nr.create,Pf=kr.create,f$=xn.create,m$=Pr.create,Tf=Tr.create,h$=Er.create,g$=vn.create,y$=Rr.create,v$=Ir.create,_$=or.create,b$=Ut.create,w$=mt.create,x$=_n.create,S$=qt.create,$$=Je.create,k$=Je.strictCreate,P$=Ar.create,T$=Ys.create,E$=Cr.create,R$=Tt.create,I$=Qs.create,A$=bn.create,C$=wn.create,D$=Xs.create,z$=Dr.create,O$=zr.create,M$=Or.create,j$=Mr.create,N$=sr.create,L$=it.create,F$=ot.create,Z$=Et.create,U$=it.createWithPreprocess,q$=vo.create,V$=()=>kf().optional(),B$=()=>Pf().optional(),W$=()=>Tf().optional(),H$={string:(t=>nr.create({...t,coerce:!0})),number:(t=>kr.create({...t,coerce:!0})),boolean:(t=>Tr.create({...t,coerce:!0})),bigint:(t=>Pr.create({...t,coerce:!0})),date:(t=>Er.create({...t,coerce:!0}))};var K$=j;Nt();var J$=h.enum(["read-only","workspace-write","full-auto"]),G$=J$.default("read-only"),Y$=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:G$,config:h.record(h.unknown()).default({})}),Q$=h.enum(["default-only","auto"]).default("default-only"),X$=h.object({defaultProvider:h.string().optional(),selectionPolicy:Q$,locale:h.string().optional(),providers:h.array(Y$).min(1,"At least one provider required")});function Vt(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":return"workspace-write";default:return"read-only"}}function ei(t){return t==="workspace-write"||t==="full-auto"}function ek(t){return Vs.includes(t)}function tk(t){if(t!==void 0)return ek(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${xr}`),xr)}function Ef(t){let e=X$.parse(t);return{defaultProvider:e.defaultProvider,selectionPolicy:e.selectionPolicy,locale:tk(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}ni();wo();ho();mn();Nt();import{mkdirSync as Lf,readFileSync as Rt,readdirSync as Wc,existsSync as ir,unlinkSync as kk,rmdirSync as Pk}from"fs";import{join as ce}from"path";import{spawn as Ff}from"child_process";import{randomUUID as Tk}from"crypto";function Zr(t,e){let r=ce(t,"status.json"),n=JSON.parse(Rt(r,"utf-8"));Ue(r,{...n,...e})}var ii=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;constructor(e=process.cwd(),r){this.jobsDir=ce(e,Qp),Lf(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7}submit(e){let r=`${e.provider}-${Date.now()}-${Tk().slice(0,6)}`,n=ce(this.jobsDir,r);Lf(n,{recursive:!0});let o={id:r,provider:e.provider,prompt:e.prompt,timeout:e.timeout??3e5,createdAt:new Date().toISOString(),cwd:process.cwd()},s={id:r,state:"queued",provider:e.provider};return Ue(ce(n,"job.json"),o),Ue(ce(n,"status.json"),s),se(ce(n,"prompt.txt"),e.prompt),this.statusCache.set(r,s),this.spawnWorker(n),this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!oi(e))return null;let r=["completed","error","timed_out","cancelled","missing_cli"],n=this.statusCache.get(e);if(n&&r.includes(n.state))return n;let o=ce(this.jobsDir,e,"status.json");if(!ir(o))return null;let s=JSON.parse(Rt(o,"utf-8"));if(s.state==="queued"){let i=ce(this.jobsDir,e,"job.json");try{let a=JSON.parse(Rt(i,"utf-8"));if(Date.now()-new Date(a.createdAt).getTime()>6e4){let u={...s,state:"error",completedAt:new Date().toISOString()};return Ue(o,u),se(ce(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,u),u}}catch{}}return this.statusCache.set(e,s),s}getResult(e){if(!oi(e))return null;let r=this.getStatus(e);if(!r)return null;let n=ce(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode},s=ce(n,"output.txt");ir(s)&&(o.output=Rt(s,"utf-8"));let i=ce(n,"error.txt");return ir(i)&&(o.error=Rt(i,"utf-8")),o}listJobs(){if(!ir(this.jobsDir))return[];let e=Wc(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory()),r=[];for(let n of e){let o=ce(this.jobsDir,n.name,"status.json");ir(o)&&r.push(JSON.parse(Rt(o,"utf-8")))}return r}cancel(e){if(!oi(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&pn(r.pid);let n=ce(this.jobsDir,e),o={...r,state:"cancelled",completedAt:new Date().toISOString()};return Ue(ce(n,"status.json"),o),this.statusCache.set(e,o),!0}cleanup(){if(!ir(this.jobsDir))return 0;let e=Wc(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory()),r=[];for(let u of e){let l=ce(this.jobsDir,u.name,"status.json"),d=ce(this.jobsDir,u.name,"job.json");if(!ir(l))continue;let p=JSON.parse(Rt(l,"utf-8")),f=null;try{f=JSON.parse(Rt(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}let n=["completed","error","timed_out","cancelled","missing_cli"],o=r.filter(u=>n.includes(u.status.state)).sort((u,l)=>{let d=u.descriptor?.createdAt??"",p=l.descriptor?.createdAt??"";return d.localeCompare(p)}),s=0,i=Date.now(),a=this.maxAgeDays*24*60*60*1e3,c=r.length;for(let u of o){let d=(u.descriptor?.createdAt?i-new Date(u.descriptor.createdAt).getTime():1/0)>a,p=c-s>this.maxJobs;if(!d&&!p)continue;let f=ce(this.jobsDir,u.name);try{let m=Wc(f);for(let g of m)kk(ce(f,g));Pk(f),this.statusCache.delete(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(ir(r)){let n=Ff(process.execPath,[r,e],{detached:!0,stdio:"ignore"});if(n.pid)try{Zr(e,{pid:n.pid})}catch{}n.on("error",o=>{o.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(Nf(),jf)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Rt(ce(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){Zr(e,{state:"missing_cli",completedAt:new Date().toISOString()}),se(ce(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Rt(ce(e,"prompt.txt"),"utf-8"),c=i(a);Zr(e,{state:"running",startedAt:new Date().toISOString()});let u=Lt(s,c),l=Ff(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",y=>{f+=y.length,f<=10485760&&(d+=y.toString())}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let g=setTimeout(()=>{er(l),se(ce(e,"output.txt"),d),se(ce(e,"error.txt"),p),Zr(e,{state:"timed_out",completedAt:new Date().toISOString()})},n.timeout);l.on("close",y=>{clearTimeout(g),se(ce(e,"output.txt"),d),se(ce(e,"error.txt"),p);let _=d.trim().length>0;Zr(e,{state:y===0||_?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()})}),l.on("error",y=>{clearTimeout(g);let _=y.code==="ENOENT"?"missing_cli":"error";se(ce(e,"error.txt"),y.message),Zr(e,{state:_,completedAt:new Date().toISOString()})})}).catch(()=>{try{Zr(e,{state:"error",completedAt:new Date().toISOString()}),se(ce(e,"error.txt"),"Failed to load job worker module")}catch{}})}};ni();Nt();import{mkdirSync as Ek,readdirSync as Zf,readFileSync as Rk,unlinkSync as Ik}from"fs";import{join as xo}from"path";function Uf(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}function Ak(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function Ck(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var ai=class{tracesDir;writer;constructor(e,r){this.tracesDir=xo(e,Xp),Ek(this.tracesDir,{recursive:!0}),this.writer=new ti(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Uf(new Date(r.timestamp)),o=xo(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
12
+ `,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=Rk(i,"utf-8").split(`
13
+ `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);Ck(u)?o.push(u):Ak(u)&&n.push(u)}catch{}}for(let i of o){let a=n.find(c=>c.traceId===i.traceId&&c.providerId===i.providerId);a&&(a.quality=i.quality)}let s=n;return e.providerId&&(s=s.filter(i=>i.providerId===e.providerId)),e.task&&(s=s.filter(i=>i.task===e.task)),e.traceId&&(s=s.filter(i=>i.traceId===e.traceId)),e.successOnly&&(s=s.filter(i=>i.response.success)),e.failedOnly&&(s=s.filter(i=>!i.response.success)),e.limit!==void 0&&(s=s.slice(0,e.limit)),s}updateQuality(e,r,n){let o=new Date,s={type:"quality_update",traceId:e,providerId:r,timestamp:o.toISOString(),quality:n},i=Uf(o),a=xo(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(s)+`
14
+ `,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let s of r){if(!s.quality)continue;let i=`${s.providerId}:${s.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=s.quality.score,a.count+=1,a.totalLatency+=s.latencyMs,n.set(i,a)}let o=new Map;for(let[s,i]of n)o.set(s,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return o}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,o;try{o=Zf(this.tracesDir)}catch{return 0}for(let s of o){if(!s.endsWith(".jsonl"))continue;let i=s.replace(".jsonl",""),a=new Date(i+"T00:00:00.000Z");isNaN(a.getTime())||a<r&&(Ik(xo(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=Zf(this.tracesDir).filter(n=>n.endsWith(".jsonl")).sort()}catch{return[]}if(e!==void 0){let n=new Date;n.setDate(n.getDate()-e),r=r.filter(o=>{let s=o.replace(".jsonl",""),i=new Date(s+"T00:00:00.000Z");return!isNaN(i.getTime())&&i>=n})}return r.map(n=>xo(this.tracesDir,n))}};var Dk=/[;|&`$(){}!><\n\r\\]/,ci=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),zk=new Set(["rm","sudo","chmod","chown","mkfs","dd","curl","wget","kill","pkill","killall","mv","cp","sh","bash","zsh","python","perl","ruby","node","npm","npx","eval","exec","source"]);function qf(t){if(Dk.test(t))return{valid:!1,error:"Command contains shell metacharacters (piping, chaining, or subshell operators are not allowed)"};let e=t.split(/\s+/).filter(Boolean);if(e.length===0)return{valid:!1,error:"Empty command"};if(e[0].includes("/")||e[0].includes("\\"))return{valid:!1,error:"Command must not contain path separators (use bare command names only)"};for(let n=1;n<e.length;n++)if(e[n].includes("/")||e[n].includes("\\"))return{valid:!1,error:`Argument must not contain path separators: ${JSON.stringify(e[n])}`};let r=e[0];if(!ci.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...ci].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(zk.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}Nt();var Vf=[{type:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/,description:"AWS Access Key ID"},{type:"private_key",regex:/-----BEGIN\s+(RSA|EC|DSA|OPENSSH)?\s*PRIVATE KEY-----/,description:"Private key header"},{type:"password_assignment",regex:/(?:password|passwd|pwd)\s*[:=]\s*["']?[^\s"',;]{4,}["']?/i,description:"Password assignment"},{type:"api_key_assignment",regex:/(?:api[_-]?key|apikey|secret[_-]?key)\s*[:=]\s*["']?[^\s"',;]{8,}["']?/i,description:"API key assignment"},{type:"bearer_token",regex:/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/,description:"Bearer JWT token"},{type:"generic_secret",regex:/(?:token|secret|credential)\s*[:=]\s*["'][^"']{8,}["']/i,description:"Generic secret assignment"}],Bf=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function Wf(t){let e=Array.isArray(t)?t:t.split(`
15
+ `),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of Vf){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!Bf.some(u=>u.test(a))){r.push({type:s.type,pattern:s.description,line:n+1,excerpt:o.length>80?o.slice(0,80)+"...":o});break}}}return{clean:r.length===0,findings:r}}function Hc(t){if(t.length===0)return t;let e=t.split(`
16
+ `);for(let r=0;r<e.length;r++){let n=e[r];for(let o of Vf){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>Bf.some(a=>a.test(i))?i:ff)}e[r]=n}return e.join(`
17
+ `)}Nt();import{execFileSync as Ok}from"child_process";import{existsSync as Hf,rmSync as Mk,mkdirSync as jk}from"fs";import{join as Kf}from"path";var ui=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=Kf(e,ef)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=Kf(this.worktreeBaseDir,r);jk(this.worktreeBaseDir,{recursive:!0}),Hf(o)&&this.forceRemoveWorktree(o),this.gitSafe(["branch","-D",n]),this.git(["worktree","add","-b",n,o,"HEAD"]);let s={id:e,path:o,branch:n};return this.worktrees.set(e,s),s}remove(e){let r=this.worktrees.get(e);r&&(this.forceRemoveWorktree(r.path),this.gitSafe(["branch","-D",r.branch]),this.worktrees.delete(e))}get(e){return this.worktrees.get(e)}list(){return[...this.worktrees.values()]}listOrphans(){let e=this.gitSafe(["worktree","list","--porcelain"]);if(!e)return[];let r=[],n="",o="",s=()=>{n.includes(".agestra/worktrees")&&o.startsWith("agestra-worker/")&&([...this.worktrees.values()].some(a=>a.path===n)||r.push({path:n,branch:o})),n="",o=""};for(let i of e.split(`
18
+ `))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?o=i.slice(18):i===""&&s();return n&&s(),r}cleanOrphans(){let e=this.listOrphans(),r=0;for(let n of e)this.forceRemoveWorktree(n.path),this.gitSafe(["branch","-D",n.branch]),r++;return r}forceRemoveWorktree(e){this.gitSafe(["worktree","remove",e])===null&&this.gitSafe(["worktree","remove","--force",e])===null&&(Hf(e)&&Mk(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return Ok("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var Nk=["npm","node","git","tsc"];function Jf(t){return{task:t.taskDescription,files:{readonly:t.filesToRead??[],readwrite:t.filesToModify??[]},constraints:t.constraints,success_criteria:t.successCriteria??[],permissions:{sandbox_root:t.workingDir,allowed_commands:[...Nk]},timeout_minutes:t.timeoutMinutes??10}}function Gf(t){let e=[];return(!t.task||t.task.trim().length===0)&&e.push("task must not be empty"),(!t.permissions.sandbox_root||t.permissions.sandbox_root.trim().length===0)&&e.push("permissions.sandbox_root must not be empty"),t.timeout_minutes<=0&&e.push("timeout_minutes must be positive"),{valid:e.length===0,errors:e}}var $e;(function(t){t.SPAWNING="SPAWNING",t.RUNNING="RUNNING",t.COLLECTING="COLLECTING",t.COMPLETED="COMPLETED",t.FAILED="FAILED",t.CANCELLING="CANCELLING",t.CANCELLED="CANCELLED",t.TIMEOUT="TIMEOUT"})($e||($e={}));var li=10,Kc=2e4;import{spawn as Vk}from"child_process";import{writeFileSync as Gc,mkdirSync as Bk,readFileSync as em,existsSync as tm}from"fs";import{isAbsolute as rm,join as So,resolve as nm}from"path";import{randomBytes as Wk}from"crypto";import{execFileSync as Hk}from"child_process";Nt();mn();ho();wo();wo();import{readFileSync as Yf}from"fs";var Jc=class{builders=new Map;register(e,r){this.builders.set(e,r)}has(e){return this.builders.has(e)}build(e,r,n,o){let s=this.builders.get(e);if(!s){let i=[...this.builders.keys()];throw new Error(`No CLI launch builder registered for provider "${e}". Known: [${i.join(", ")}]`)}return s(r,n,o)}knownProviders(){return[...this.builders.keys()]}};function Lk(t,e,r){let n=Qf(t,e,r);return{command:"codex",args:["exec","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function Fk(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",Qf(t,e,r)]}}function Qf(t,e,r){let n=Yf(t,"utf-8"),o=Zk(r,e);return["You are an autonomous coding worker operating in the current workspace.","Execute the task manifest below without asking for confirmation.","Stay within the workspace, respect read-only vs read-write boundaries, and summarize changes plus verification at the end.","",n,o].join(`
19
+ `)}function Xf(){let t=new Jc;return t.register("codex",Lk),t.register("gemini",Fk),t}function Zk(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!Vc(o,e));if(r.length===0)return"";let n=["Read-only file snapshots:","These files may live outside the worker sandbox root. Use the embedded contents below as authoritative context and do not attempt to edit them.",""];for(let o of r.slice(0,li))try{let s=Yf(o,"utf-8"),i=s.length>Kc?`${s.slice(0,Kc)}
20
+ ...[truncated]`:s;n.push(`### File: ${o}`),n.push("```"),n.push(i),n.push("```"),n.push("")}catch(s){let i=s instanceof Error?s.message:String(s);n.push(`### File: ${o}`),n.push(`[unavailable: ${i}]`),n.push("")}return r.length>li&&(n.push(`...[${r.length-li} additional read-only files omitted]`),n.push("")),n.join(`
21
+ `)}var $o=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=So(e,sf),this.worktreeManager=new ui(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??Xf()}knownProviders(){let e=new Set;for(let r of this.cliBuilderRegistry.knownProviders())e.add(r);for(let r of this.providerPolicies.keys())e.add(r);return[...e]}activeWorkerCount(){let e=0;for(let r of this.workers.values()){let n=r.info.state;(n===$e.RUNNING||n===$e.COLLECTING)&&e++}return e}spawn(e){if(this.activeWorkerCount()>=3)throw new Error(`Worker quota exceeded: ${this.activeWorkerCount()}/${3} workers already active. Wait for existing workers to complete or call stop() before spawning a new one.`);let r=this.validateWorkingDirectory(e.workingDir),n=this.normalizeReadablePaths(e.filesToRead,r),o=this.normalizeWritablePaths(e.filesToModify,r);this.assertAutonomousExecutionAllowed(e.provider);let s=[e.taskDescription,e.constraints??""],i=Wf(s);if(!i.clean){let Z=i.findings.map(De=>De.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${Z}`)}let a=Wk(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=So(this.workersBaseDir,c);Bk(u,{recursive:!0});let l=Jf({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=Gf(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=So(u,"task-manifest.json");Gc(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=So(u,"stdout.log"),g=So(u,"stderr.log"),y=f?.path??r,_=this.cliBuilderRegistry.build(e.provider,p,y,n),S=Lt(_.command,_.args),v=Vk(S.command,S.args,{cwd:y,env:t.buildWorkerEnv(),detached:!0,stdio:[_.stdin?"pipe":"ignore","pipe","pipe"]}),k=[],x=[];v.stdout?.on("data",Z=>k.push(Z)),v.stderr?.on("data",Z=>x.push(Z)),_.stdin!==void 0&&v.stdin?.end(_.stdin),v.unref();let z={workerId:c,provider:e.provider,state:$e.RUNNING,pid:v.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},O={info:z,process:v,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,O),e.timeoutMinutes){let Z=e.timeoutMinutes*6e4;setTimeout(()=>{if(O.info.state===$e.RUNNING){O.info.state=$e.TIMEOUT,O.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let Y=O.process?.pid;Y&&pn(Y)}},Z).unref()}return v.on("close",Z=>{O.info.exitCode=Z;try{Gc(m,Buffer.concat(k).toString("utf-8")),Gc(g,Buffer.concat(x).toString("utf-8"))}catch{}O.info.state===$e.CANCELLING?O.info.state=$e.CANCELLED:Z===0?O.info.state=$e.COLLECTING:(O.info.state=$e.FAILED,O.info.error=`Process exited with code ${Z}`)}),z}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{tm(r.outputPath)&&(o=em(r.outputPath,"utf-8").split(`
22
22
  `).slice(-20).join(`
23
- `))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:fc(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{uf(r.outputPath)&&(n=cf(r.outputPath,"utf-8"))}catch{}n=fc(n);let o=null;try{r.info.worktreePath&&(o=this.reviewChanges(r.info.workerId))}catch{o=null}return r.info.state===ke.COLLECTING&&(r.info.state=ke.COMPLETED),{workerId:r.info.workerId,state:r.info.state,exitCode:r.info.exitCode,outputFull:n,gitDiff:o?.fullDiff??"",filesChanged:o?.filesChanged??[],worktreeBranch:r.info.worktreeBranch}}stop(e){let r=this.workers.get(e);if(!r||!r.process||r.info.state!==ke.RUNNING)return;r.info.state=ke.CANCELLING;let n=r.process.pid;if(n)dn(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===ke.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=ke.CANCELLED}},5e3)}listAll(){return[...this.workers.values()].map(e=>({...e.info}))}reviewChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);if(!r.info.worktreePath)throw new Error(`Worker ${e} has no isolated worktree`);let n=r.info.worktreePath;return this.execGitSafe(["add","-N","."],n),{workerId:r.info.workerId,provider:r.info.provider,worktreePath:r.info.worktreePath,branch:r.info.worktreeBranch,filesChanged:this.listChangedFiles(n),diffStat:this.execGit(["diff","--stat","HEAD"],n),fullDiff:this.execGit(["diff","HEAD"],n)}}acceptChanges(e,r){let n=this.workers.get(e);if(!n)throw new Error(`Worker not found: ${e}`);if(!n.info.worktreePath||!n.info.worktreeBranch)throw new Error(`Worker ${e} has no isolated worktree`);let o=n.info.worktreePath,s=r??`agestra: worker ${e}`;this.execGit(["add","-A"],o);let i=this.execGit(["status","--porcelain"],o),a=i.trim()?i.trim().split(`
24
- `).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",s],o),this.execGit(["merge",n.info.worktreeBranch,"--no-edit"],this.baseDir)),this.worktreeManager.remove(n.info.workerId),n.info.worktreePath=null,n.info.worktreeBranch=null,{merged:a}}rejectChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);r.info.worktreePath&&this.worktreeManager.remove(r.info.workerId),r.info.worktreePath=null,r.info.worktreeBranch=null}tryCreateWorktree(e){try{return this.worktreeManager.create(e)}catch{return null}}execGit(e,r){return lS("git",e,{cwd:r,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}execGitSafe(e,r){try{return this.execGit(e,r)}catch{return null}}listChangedFiles(e){let r=this.execGitSafe(["status","--porcelain"],e);return r?.trim()?r.trim().split(`
25
- `).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of yp){let n=process.env[r];n!==void 0&&(e[r]=n)}for(let[r,n]of Object.entries(process.env))r.startsWith("AGESTRA_")&&n!==void 0&&(e[r]=n);return e}getProviderPolicy(e){let r=this.providerPolicies.get(e);if(r===void 0){let n=[...this.providerPolicies.keys()];throw new Error(`No execution policy configured for provider "${e}". Known: [${n.join(", ")}]`)}return r}assertAutonomousExecutionAllowed(e){let r=this.getProviderPolicy(e);if(!Ms(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return ht(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let o=lf(n)?n:df(r,n);return Ft(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=lf(n)?n:df(r,n);return ht(o,this.baseDir)})}};var Hs=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(e,r){this.upstream=e,this.ttlMs=r?.ttlMs??6e4}getQualityStats(e){let r=Date.now();return this.cached!==null&&this.cachedDaysBack===e&&r-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(e),this.cachedAt=r,this.cachedDaysBack=e,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var wn=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(e,r=16){this.maxConcurrent=e,this.maxQueueSize=r}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}async run(e){await this.acquire();try{return await e()}finally{this.release()}}};fn();vr();import{spawn as dS}from"child_process";var pS=3e5,fS=3,mS=15e3,hS=3e3,gS=12e4,Gs=class{state="idle";process=null;consecutiveFailures=0;lastFailureTime=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;commandArgs;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(e){this.command=e.command,this.commandPrefix=e.commandPrefix??[],this.commandArgs=e.commandArgs??[],this.idleTimeoutMs=e.idleTimeoutMs??pS,this.maxConsecutiveFailures=e.maxConsecutiveFailures??fS,this.startupTimeoutMs=e.startupTimeoutMs??mS}async request(e,r){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??gS)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures<this.maxConsecutiveFailures?!1:Date.now()-this.lastFailureTime>vp?(this.consecutiveFailures=0,!1):!0}resetFailures(){this.consecutiveFailures=0}async shutdown(){if(!this.process||this.state==="shutdown"||this.state==="idle")return;this.state="shutdown",this.clearIdleTimer();for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error("App server shutting down"));this.pendingRequests.clear(),this.startupReject&&(this.startupReject(new Error("App server shutting down")),this.startupResolve=null,this.startupReject=null);let e=this.process;this.process=null;try{e.kill("SIGTERM")}catch{this.state="idle";return}let r=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},hS);await new Promise(n=>{e.on("close",()=>{clearTimeout(r),n()}),(e.exitCode!==null||e.signalCode!==null)&&(clearTimeout(r),n())}),this.state="idle"}async start(){if(this.state!=="idle"&&this.state!=="error")return;this.state="starting",this.stdoutBuffer="";let e=[...this.commandPrefix,...this.commandArgs,"app-server"],r=Nt(this.command,e);return this.process=dS(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0}),this.process.stdout.on("data",n=>{this.handleStdout(n.toString())}),this.process.stderr.on("data",n=>{process.stderr.write(`[codex-app-server] ${n.toString()}`)}),this.process.on("close",(n,o)=>{this.handleProcessClose(n,o)}),this.process.on("error",n=>{this.handleProcessError(n)}),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((e,r)=>{let n=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",r(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs);this.startupResolve=()=>{clearTimeout(n),e()},this.startupReject=o=>{clearTimeout(n),r(o)}})}handleStdout(e){this.stdoutBuffer+=e;let r;for(;(r=this.stdoutBuffer.indexOf(`
26
- `))!==-1;){let n=this.stdoutBuffer.slice(0,r).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(r+1),!!n){if(this.state==="starting"&&(n.includes("ready")||n.includes("initialized"))){this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null);continue}try{let o=JSON.parse(n);if(o.id&&this.pendingRequests.has(o.id)){let s=this.pendingRequests.get(o.id);this.pendingRequests.delete(o.id),clearTimeout(s.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),s.resolve(o)}}catch{this.state==="starting"&&(this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null))}}}}sendRequest(e,r){return new Promise((n,o)=>{if(!this.process||!this.process.stdin){o(new Error("App server process not available"));return}let s=setTimeout(()=>{this.pendingRequests.delete(e.id),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),o(new Error(`App server request timeout (${r}ms)`))},r);this.pendingRequests.set(e.id,{resolve:n,reject:o,timer:s}),this.state="busy",this.clearIdleTimer();try{this.process.stdin.write(JSON.stringify(e)+`
27
- `)}catch(i){clearTimeout(s),this.pendingRequests.delete(e.id),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",o(new Error(`Failed to write to app server: ${i.message}`))}})}handleProcessClose(e,r){for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error(`App server process exited (code=${e}, signal=${r})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject(new Error(`App server process exited during startup (code=${e})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(e){this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${e.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};function q(t){return t instanceof Error?t.message:String(t)}function $n(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}fn();async function Sn(t,e){try{if((await De({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await De({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function pf(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await De({command:t==="npx"?"npx":e,args:t==="npx"?[r,"--version"]:["--version"],timeout:1e4});return i.exitCode===0?{status:"ok",message:`${n} CLI available`}:{status:"error",message:`Exit code: ${i.exitCode}`}}catch(o){return{status:"error",message:o.message}}}function kn(t,e,r){let n=e.trim()||`Exit code ${t}`,o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("quota")){let s=new me(r,`Rate limited: ${n}`);throw s.markUnavailable=!0,s}throw o.includes("auth")||o.includes("credential")||o.includes("login")||o.includes("api key")?new me(r,`Authentication issue: ${n}`):new Be(r,n)}function ff(t){let e="",r=!1;return{feed(n){if(r)return null;e+=n;let o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("rate-limit")||o.includes("resource_exhausted")||o.includes("quota")){r=!0;let s=new me(t,`Rate limited (detected in stream): ${n.trim().slice(0,200)}`);return s.markUnavailable=!0,s}return o.includes("authentication")||o.includes("credential")||o.includes("api key")?(r=!0,new me(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Lr(t){let e=t.prompt;if(t.system&&(e=`${t.system}
23
+ `))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:Hc(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{tm(r.outputPath)&&(n=em(r.outputPath,"utf-8"))}catch{}n=Hc(n);let o=null;try{r.info.worktreePath&&(o=this.reviewChanges(r.info.workerId))}catch{o=null}return r.info.state===$e.COLLECTING&&(r.info.state=$e.COMPLETED),{workerId:r.info.workerId,state:r.info.state,exitCode:r.info.exitCode,outputFull:n,gitDiff:o?.fullDiff??"",filesChanged:o?.filesChanged??[],worktreeBranch:r.info.worktreeBranch}}stop(e){let r=this.workers.get(e);if(!r||!r.process||r.info.state!==$e.RUNNING)return;r.info.state=$e.CANCELLING;let n=r.process.pid;if(n)pn(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===$e.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=$e.CANCELLED}},5e3)}listAll(){return[...this.workers.values()].map(e=>({...e.info}))}reviewChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);if(!r.info.worktreePath)throw new Error(`Worker ${e} has no isolated worktree`);let n=r.info.worktreePath;return this.execGitSafe(["add","-N","."],n),{workerId:r.info.workerId,provider:r.info.provider,worktreePath:r.info.worktreePath,branch:r.info.worktreeBranch,filesChanged:this.listChangedFiles(n),diffStat:this.execGit(["diff","--stat","HEAD"],n),fullDiff:this.execGit(["diff","HEAD"],n)}}acceptChanges(e,r){let n=this.workers.get(e);if(!n)throw new Error(`Worker not found: ${e}`);if(!n.info.worktreePath||!n.info.worktreeBranch)throw new Error(`Worker ${e} has no isolated worktree`);let o=n.info.worktreePath,s=r??`agestra: worker ${e}`;this.execGit(["add","-A"],o);let i=this.execGit(["status","--porcelain"],o),a=i.trim()?i.trim().split(`
24
+ `).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",s],o),this.execGit(["merge",n.info.worktreeBranch,"--no-edit"],this.baseDir)),this.worktreeManager.remove(n.info.workerId),n.info.worktreePath=null,n.info.worktreeBranch=null,{merged:a}}rejectChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);r.info.worktreePath&&this.worktreeManager.remove(r.info.workerId),r.info.worktreePath=null,r.info.worktreeBranch=null}tryCreateWorktree(e){try{return this.worktreeManager.create(e)}catch{return null}}execGit(e,r){return Hk("git",e,{cwd:r,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}execGitSafe(e,r){try{return this.execGit(e,r)}catch{return null}}listChangedFiles(e){let r=this.execGitSafe(["status","--porcelain"],e);return r?.trim()?r.trim().split(`
25
+ `).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of af){let n=process.env[r];n!==void 0&&(e[r]=n)}for(let[r,n]of Object.entries(process.env))r.startsWith("AGESTRA_")&&n!==void 0&&(e[r]=n);return e}getProviderPolicy(e){let r=this.providerPolicies.get(e);if(r===void 0){let n=[...this.providerPolicies.keys()];throw new Error(`No execution policy configured for provider "${e}". Known: [${n.join(", ")}]`)}return r}assertAutonomousExecutionAllowed(e){let r=this.getProviderPolicy(e);if(!ei(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return ht(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let o=rm(n)?n:nm(r,n);return Bt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=rm(n)?n:nm(r,n);return ht(o,this.baseDir)})}};var pi=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(e,r){this.upstream=e,this.ttlMs=r?.ttlMs??6e4}getQualityStats(e){let r=Date.now();return this.cached!==null&&this.cachedDaysBack===e&&r-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(e),this.cachedAt=r,this.cachedDaysBack=e,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var Sn=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(e,r=16){this.maxConcurrent=e,this.maxQueueSize=r}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}async run(e){await this.acquire();try{return await e()}finally{this.release()}}};mn();Nt();import{spawn as Kk}from"child_process";var Jk=3e5,Gk=3,Yk=15e3,Qk=3e3,Xk=6e5,fi=class{state="idle";process=null;consecutiveFailures=0;lastFailureTime=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;commandArgs;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(e){this.command=e.command,this.commandPrefix=e.commandPrefix??[],this.commandArgs=e.commandArgs??[],this.idleTimeoutMs=e.idleTimeoutMs??Jk,this.maxConsecutiveFailures=e.maxConsecutiveFailures??Gk,this.startupTimeoutMs=e.startupTimeoutMs??Yk}async request(e,r){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??Xk)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures<this.maxConsecutiveFailures?!1:Date.now()-this.lastFailureTime>uf?(this.consecutiveFailures=0,!1):!0}resetFailures(){this.consecutiveFailures=0}async shutdown(){if(!this.process||this.state==="shutdown"||this.state==="idle")return;this.state="shutdown",this.clearIdleTimer();for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error("App server shutting down"));this.pendingRequests.clear(),this.startupReject&&(this.startupReject(new Error("App server shutting down")),this.startupResolve=null,this.startupReject=null);let e=this.process;this.process=null;try{e.kill("SIGTERM")}catch{this.state="idle";return}let r=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},Qk);await new Promise(n=>{e.on("close",()=>{clearTimeout(r),n()}),(e.exitCode!==null||e.signalCode!==null)&&(clearTimeout(r),n())}),this.state="idle"}async start(){if(this.state!=="idle"&&this.state!=="error")return;this.state="starting",this.stdoutBuffer="";let e=[...this.commandPrefix,...this.commandArgs,"app-server"],r=Lt(this.command,e);return this.process=Kk(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0}),this.process.stdout.on("data",n=>{this.handleStdout(n.toString())}),this.process.stderr.on("data",n=>{process.stderr.write(`[codex-app-server] ${n.toString()}`)}),this.process.on("close",(n,o)=>{this.handleProcessClose(n,o)}),this.process.on("error",n=>{this.handleProcessError(n)}),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((e,r)=>{let n=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",r(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs);this.startupResolve=()=>{clearTimeout(n),e()},this.startupReject=o=>{clearTimeout(n),r(o)}})}handleStdout(e){this.stdoutBuffer+=e;for(let n of this.pendingRequests.values())n.resetTimer();let r;for(;(r=this.stdoutBuffer.indexOf(`
26
+ `))!==-1;){let n=this.stdoutBuffer.slice(0,r).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(r+1),!!n){if(this.state==="starting"&&(n.includes("ready")||n.includes("initialized"))){this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null);continue}try{let o=JSON.parse(n);if(o.id&&this.pendingRequests.has(o.id)){let s=this.pendingRequests.get(o.id);this.pendingRequests.delete(o.id),clearTimeout(s.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),s.resolve(o)}}catch{this.state==="starting"&&(this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null))}}}}sendRequest(e,r){return new Promise((n,o)=>{if(!this.process||!this.process.stdin){o(new Error("App server process not available"));return}let s=()=>{this.pendingRequests.delete(e.id),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),o(new Error(`App server request timeout (${r}ms of inactivity)`))},i=setTimeout(s,r),a=()=>{clearTimeout(i),i=setTimeout(s,r)};this.pendingRequests.set(e.id,{resolve:n,reject:o,timer:i,resetTimer:a}),this.state="busy",this.clearIdleTimer();try{this.process.stdin.write(JSON.stringify(e)+`
27
+ `)}catch(c){clearTimeout(i),this.pendingRequests.delete(e.id),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",o(new Error(`Failed to write to app server: ${c.message}`))}})}handleProcessClose(e,r){for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error(`App server process exited (code=${e}, signal=${r})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject(new Error(`App server process exited during startup (code=${e})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(e){this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${e.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};function M(t){return t instanceof Error?t.message:String(t)}function $n(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}mn();async function kn(t,e){try{if((await ze({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await ze({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function om(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await ze({command:t==="npx"?"npx":e,args:t==="npx"?[r,"--version"]:["--version"],timeout:1e4});return i.exitCode===0?{status:"ok",message:`${n} CLI available`}:{status:"error",message:`Exit code: ${i.exitCode}`}}catch(o){return{status:"error",message:o.message}}}function Pn(t,e,r){let n=e.trim()||`Exit code ${t}`,o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("quota")){let s=new me(r,`Rate limited: ${n}`);throw s.markUnavailable=!0,s}throw o.includes("auth")||o.includes("credential")||o.includes("login")||o.includes("api key")?new me(r,`Authentication issue: ${n}`):new He(r,n)}function sm(t){let e="",r=!1;return{feed(n){if(r)return null;e+=n;let o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("rate-limit")||o.includes("resource_exhausted")||o.includes("quota")){r=!0;let s=new me(t,`Rate limited (detected in stream): ${n.trim().slice(0,200)}`);return s.markUnavailable=!0,s}return o.includes("authentication")||o.includes("credential")||o.includes("api key")?(r=!0,new me(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Ur(t){let e=t.prompt;if(t.system&&(e=`${t.system}
28
28
 
29
29
  ${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
30
30
 
31
31
  ### File: ${r.path}
32
32
  \`\`\`
33
33
  ${r.content}
34
- \`\`\``);return e}function Js(t,e){return!!t.files?.length||e.length>4e3}function or(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Tn(t,e,r){throw t instanceof me||t instanceof Be?t:t.message?.includes("timeout")?new un(e,r):new Be(e,t.message)}function yS(t){let e=t.prompt;if(t.files?.length)for(let r of t.files)r.content&&(e+=`
34
+ \`\`\``);return e}function mi(t,e){return!!t.files?.length||e.length>4e3}function ar(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Tn(t,e,r){throw t instanceof me||t instanceof He?t:t.message?.includes("timeout")?new un(e,r):new He(e,t.message)}function e0(t){let e=t.prompt;if(t.files?.length)for(let r of t.files)r.content&&(e+=`
35
35
 
36
36
  ### File: ${r.path}
37
37
  \`\`\`
38
38
  ${r.content}
39
- \`\`\``);return e}function _S(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var sr=class{id;type;bridge;modelName;displayName;capabilities;constructor(e){this.id=e.id??e.bridge.providerId,this.type=e.type,this.bridge=e.bridge,this.modelName=e.modelName??e.type,this.displayName=e.displayName,this.capabilities=e.capabilities}async initialize(){}async healthCheck(){return this.bridge.healthCheck?this.bridge.healthCheck():this.bridge.isAvailable()?{status:"ok",message:`${this.displayName} host bridge available`}:{status:"error",message:`${this.displayName} host bridge unavailable`}}getCapabilities(){return{...this.capabilities,models:this.capabilities.models.map((e,r)=>r===0?{...e,name:this.modelName}:{...e})}}getDescriptor(){return Qt(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new me(this.id,`${this.displayName} host bridge is not available`);try{let r=yS(e),n={...e.extra??{}};e.model&&(n.model=e.model),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.maxTokens=e.maxTokens);let o=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:o.text,model:_S(this.modelName,o.metadata),provider:this.id,metadata:o.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new me(this.id,n):new Be(this.id,n)}}};var vS={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude-host",description:"Claude host model via MCP sampling bridge",strengths:["reasoning","review","synthesis"]}]},Ks=class extends sr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:vS,modelName:e.modelName??"claude-host"})}};var xS={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["coding","reasoning","review","implementation"],models:[{name:"codex-host",description:"Codex host model via MCP sampling bridge",strengths:["coding","implementation","review"]}]},Qs=class extends sr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:xS,modelName:e.modelName??"codex-host"})}};var bS={maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["analysis","reasoning","research","review"],models:[{name:"gemini-host",description:"Gemini host model via MCP sampling bridge",strengths:["analysis","research","review"]}]},Ys=class extends sr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:bS,modelName:e.modelName??"gemini-host"})}};async function mf(t){let e=await fetch(`${t}/api/tags`);if(!e.ok)throw new Error(`Ollama API error: ${e.status}`);return((await e.json()).models||[]).map(n=>({name:n.name||"unknown",size:n.size||0,strengths:wS(n.name||"")}))}function wS(t){let e=["chat"],r=t.toLowerCase();return(r.includes("coder")||r.includes("code"))&&e.push("code_review","code_generation"),r.includes("instruct")&&e.push("instruction_following"),r.includes("embed")&&e.push("embedding"),e}var Zr=class t{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(e){this.id=e.id,this.host=e.host,this.defaultModel=e.defaultModel||"auto",this.maxContext=e.maxContext??32768,this.timeouts={default:e.timeouts?.default??3e4,generate:e.timeouts?.generate??3e5,chat:e.timeouts?.chat??3e5}}async initialize(){try{this.models=await mf(this.host),this.available=this.models.length>0}catch{this.available=!1}}async healthCheck(){try{let e=await fetch(`${this.host}/api/tags`);if(!e.ok)return{status:"error",message:`HTTP ${e.status}`};let r=await e.json(),n=r.models?.length??0;return{status:n>0?"ok":"degraded",message:`${n} models available`,details:{models:r.models?.map(o=>o.name)}}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(e=>e.strengths))],models:this.models.map(e=>({name:e.name,description:`Ollama model (${Math.round(e.size/1e9)}GB)`,strengths:e.strengths,sizeGb:e.size/1e9}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(e){if(!this.available)throw new me(this.id,"Ollama not running or no models installed");let r=e.model||this.selectModel(),n={model:r,prompt:e.prompt,system:e.system||"You are a helpful assistant.",stream:!1,...e.extra||{}},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeouts.generate);try{let i=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(i.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new me(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!i.ok)throw new Be(this.id,`HTTP ${i.status}: ${i.statusText}`);let a=await i.json();return{text:a.response||"",model:a.model||r,provider:this.id}}catch(i){throw i.name==="AbortError"?new un(this.id,this.timeouts.generate):i instanceof Be||i instanceof me?i:new Be(this.id,i.message)}finally{clearTimeout(s)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new me(this.id,`No models detected. Install a model first (ollama pull ${up})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var SS=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function hf(t){return t.split(`
40
- `).filter(n=>{let o=n.trim();return o?!SS.some(s=>s.test(o)):!1}).join(`
41
- `).trim()}function gf(t){try{let e=JSON.parse(t.trim());if(e&&typeof e.response=="string")return e.response}catch{let e=t.split(`
42
- `);for(let r=e.length-1;r>=0;r--){let n=e[r].trim();if(n.startsWith("{"))try{let o=JSON.parse(n);if(o&&typeof o.response=="string")return o.response}catch{}}}return null}var yc="gemini",_c="@google/gemini-cli",qr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new wn(_p);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await Sn(yc,_c);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){if(!this.available)return{status:"error",message:"Gemini CLI not installed"};try{let{command:e,cliArgs:r}=or(this.cliPath,yc,_c,["--version"]),n=await De({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Gemini CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["long_context","file_analysis","translation","summarization"],models:[{name:"gemini-2.5-pro",description:"Google Gemini 2.5 Pro via CLI",strengths:["long_context","reasoning"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available)throw new me(this.id,"Gemini CLI not installed");let r=Lr(e),n=Js(e,r),s=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=or(this.cliPath,yc,_c,s),c=ff(this.id);try{let u=await De({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,onStderrChunk:p=>c.feed(p)});if(u.exitCode!==0)try{kn(u.exitCode,u.stderr,this.id)}catch(p){throw p.markUnavailable&&(this.available=!1),p}let l=gf(u.stdout);if(l!==null){let p=kS(u.stdout);return{text:l,model:p,provider:this.id}}return{text:hf(u.stdout),model:"gemini",provider:this.id}}catch(u){if(u instanceof me)throw u.markUnavailable&&(this.available=!1),u;Tn(u,this.id,this.timeout)}}};function kS(t){try{let e=JSON.parse(t.trim());if(e?.stats?.models){for(let[n,o]of Object.entries(e.stats.models))if(o?.roles?.main)return n;let r=Object.keys(e.stats.models);if(r.length>0)return r[0]}}catch{}return"gemini"}import{randomUUID as TS}from"crypto";function vc(t){let e=t.trim().split(`
39
+ \`\`\``);return e}function t0(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var cr=class{id;type;bridge;modelName;displayName;capabilities;constructor(e){this.id=e.id??e.bridge.providerId,this.type=e.type,this.bridge=e.bridge,this.modelName=e.modelName??e.type,this.displayName=e.displayName,this.capabilities=e.capabilities}async initialize(){}async healthCheck(){return this.bridge.healthCheck?this.bridge.healthCheck():this.bridge.isAvailable()?{status:"ok",message:`${this.displayName} host bridge available`}:{status:"error",message:`${this.displayName} host bridge unavailable`}}getCapabilities(){return{...this.capabilities,models:this.capabilities.models.map((e,r)=>r===0?{...e,name:this.modelName}:{...e})}}getDescriptor(){return tr(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new me(this.id,`${this.displayName} host bridge is not available`);try{let r=e0(e),n={...e.extra??{}};e.model&&(n.model=e.model),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.maxTokens=e.maxTokens);let o=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:o.text,model:t0(this.modelName,o.metadata),provider:this.id,metadata:o.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new me(this.id,n):new He(this.id,n)}}};var r0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude-host",description:"Claude host model via MCP sampling bridge",strengths:["reasoning","review","synthesis"]}]},hi=class extends cr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:r0,modelName:e.modelName??"claude-host"})}};var n0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["coding","reasoning","review","implementation"],models:[{name:"codex-host",description:"Codex host model via MCP sampling bridge",strengths:["coding","implementation","review"]}]},gi=class extends cr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:n0,modelName:e.modelName??"codex-host"})}};var o0={maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["analysis","reasoning","research","review"],models:[{name:"gemini-host",description:"Gemini host model via MCP sampling bridge",strengths:["analysis","research","review"]}]},yi=class extends cr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:o0,modelName:e.modelName??"gemini-host"})}};Nt();var im={"report.header.topic":"Topic","report.header.participants":"Participants","report.header.individualDocs":"Individual documents","report.table.proposer":"Proposer","report.table.opinion":"Opinion","report.table.severity":"Severity","report.table.agreement":"Agreement","report.section.mainTable":"Proposal ledger","report.section.dissentDetail":"Dissenting items","report.section.contributionSummary":"AI contribution summary","report.contribution.ai":"AI","report.contribution.proposed":"Proposed","report.contribution.accepted":"Accepted","report.contribution.revises":"Revises issued","report.contribution.abstains":"Abstains","report.footer.synthesisPath":"Final synthesis document","report.footer.debatePath":"Debate transcript","report.footer.pendingSynthesis":"(pending leader approval)","report.status.running":"running","report.status.readyForApproval":"ready for approval","report.status.consensus":"consensus","report.status.escalated":"escalated","report.status.approved":"approved","report.status.rejected":"rejected","report.status.leaderTimeout":"leader timeout","report.status.error":"error","synthesis.status.consensus":"Consensus reached","synthesis.status.escalated":"Partial / escalated","synthesis.section.acceptedItems":"Accepted Items","synthesis.section.rejectedItems":"Rejected / Withdrawn Items","synthesis.section.openItems":"Open Items","synthesis.section.sources":"Sources","synthesis.narration.consensusIn":"Consensus reached in round {round} of {max}.","synthesis.narration.escalated":"Session escalated by user after {round} rounds without consensus.","synthesis.narration.leaderNote":"Leader note","approval.pending":"Awaiting leader approval. Call `agent_debate_approve`, `agent_debate_continue`, or `agent_debate_reject`.","approval.timeout":"Session timed out waiting for leader decision ({hours}h).","moderator.narration.roundHeader":"Round {round} of {max}","moderator.narration.consensusInRound":"Consensus reached after {round} round(s).","moderator.narration.dissentDetailHeader":"Unresolved items","moderator.narration.noInterest":"No interest from participants","moderator.narration.participantDropout":"Participant `{participantId}` marked unavailable after repeated failures.","moderator.narration.participantTimeout":"Participant `{participantId}` did not respond in this round.","moderator.narration.leaderTimeoutFooter":"Leader Timeout","moderator.narration.rejected":"Session rejected by leader.","moderator.narration.approved":"Session approved by leader.","moderator.narration.aliasClarification":"Alias clarification phase","prompt.system.moderator":"You are the moderator of a structured multi-AI debate. You do not author proposals; you aggregate structured votes and produce a neutral synthesis. Respond only in the channels the protocol defines.","error.participantTimeout":"Participant `{participantId}` timed out after {seconds}s.","error.parseFailure":"Could not parse `<{tag}>` block from `{participantId}`.","error.sessionNotFound":"Debate session `{sessionId}` was not found.","error.invalidState":"Operation `{operation}` is not allowed in state `{state}`.","error.unknownLocaleFallback":"Unknown locale `{locale}`; falling back to `{fallback}`.","askUser.escalation.header":"Maximum rounds reached without consensus","askUser.escalation.question":"How would you like to proceed?","askUser.escalation.continue":"Continue +{rounds} rounds","askUser.escalation.escalate":"Escalate without consensus","askUser.escalation.stop":"Stop the debate"};var am={"report.header.topic":"\uC8FC\uC81C","report.header.participants":"\uCC38\uAC00\uC790","report.header.individualDocs":"\uAC1C\uBCC4 \uAC80\uD1A0 \uBB38\uC11C","report.table.proposer":"\uC81C\uC548\uC790","report.table.opinion":"\uC758\uACAC","report.table.severity":"\uC911\uC694\uB3C4","report.table.agreement":"\uB3D9\uC758\uC728","report.section.mainTable":"\uC81C\uC548 \uC6D0\uC7A5","report.section.dissentDetail":"\uBBF8\uD569\uC758 \uD56D\uBAA9 \uC0C1\uC138","report.section.contributionSummary":"AI \uAE30\uC5EC\uB3C4 \uC694\uC57D","report.contribution.ai":"AI","report.contribution.proposed":"\uC81C\uC548","report.contribution.accepted":"\uCC44\uD0DD","report.contribution.revises":"\uC218\uC815 \uC694\uCCAD","report.contribution.abstains":"\uAE30\uAD8C","report.footer.synthesisPath":"\uCD5C\uC885 \uD569\uC758 \uBB38\uC11C","report.footer.debatePath":"\uD1A0\uB860 \uAE30\uB85D","report.footer.pendingSynthesis":"(\uB9AC\uB354 \uC2B9\uC778 \uB300\uAE30 \uC911)","report.status.running":"\uC9C4\uD589 \uC911","report.status.readyForApproval":"\uC2B9\uC778 \uB300\uAE30","report.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","report.status.escalated":"\uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","report.status.approved":"\uC2B9\uC778\uB428","report.status.rejected":"\uAE30\uAC01\uB428","report.status.leaderTimeout":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","report.status.error":"\uC624\uB958","synthesis.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","synthesis.status.escalated":"\uBD80\uBD84 \uD569\uC758 / \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","synthesis.section.acceptedItems":"\uCC44\uD0DD \uD56D\uBAA9","synthesis.section.rejectedItems":"\uAE30\uAC01 / \uCCA0\uD68C \uD56D\uBAA9","synthesis.section.openItems":"\uBBF8\uACB0 \uD56D\uBAA9","synthesis.section.sources":"\uADFC\uAC70","synthesis.narration.consensusIn":"\uC804\uCCB4 {max}\uB77C\uC6B4\uB4DC \uC911 {round}\uB77C\uC6B4\uB4DC\uC5D0\uC11C \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","synthesis.narration.escalated":"{round}\uB77C\uC6B4\uB4DC \uB3D9\uC548 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD558\uC5EC \uC0AC\uC6A9\uC790 \uD310\uB2E8\uC73C\uB85C \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","synthesis.narration.leaderNote":"\uB9AC\uB354 \uBA54\uBAA8","approval.pending":"\uB9AC\uB354 \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uACE0 \uC788\uC2B5\uB2C8\uB2E4. `agent_debate_approve`, `agent_debate_continue`, `agent_debate_reject` \uC911 \uD558\uB098\uB97C \uD638\uCD9C\uD574 \uC8FC\uC2ED\uC2DC\uC624.","approval.timeout":"\uB9AC\uB354 \uACB0\uC815\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC138\uC158\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4({hours}\uC2DC\uAC04).","moderator.narration.roundHeader":"{round}/{max} \uB77C\uC6B4\uB4DC","moderator.narration.consensusInRound":"{round}\uB77C\uC6B4\uB4DC \uB9CC\uC5D0 \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","moderator.narration.dissentDetailHeader":"\uBBF8\uD574\uACB0 \uD56D\uBAA9","moderator.narration.noInterest":"\uCC38\uAC00\uC790 \uAD00\uC2EC \uC5C6\uC74C","moderator.narration.participantDropout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uBC18\uBCF5\uC801 \uC2E4\uD328\uB85C \uC778\uD574 \uC0AC\uC6A9 \uBD88\uAC00 \uC0C1\uD0DC\uB85C \uD45C\uC2DC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uC774\uBC88 \uB77C\uC6B4\uB4DC\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","moderator.narration.leaderTimeoutFooter":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","moderator.narration.rejected":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uAE30\uAC01\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.approved":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uC2B9\uC778\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.aliasClarification":"\uBCC4\uCE6D \uD655\uC778 \uB2E8\uACC4","prompt.system.moderator":"\uB2F9\uC2E0\uC740 \uAD6C\uC870\uD654\uB41C \uB2E4\uC911 AI \uD1A0\uB860\uC758 \uC911\uC7AC\uC790\uC785\uB2C8\uB2E4. \uC81C\uC548\uC744 \uC9C1\uC811 \uC791\uC131\uD558\uC9C0 \uC54A\uC73C\uBA70, \uAD6C\uC870\uD654\uB41C \uD22C\uD45C\uB97C \uC9D1\uACC4\uD558\uACE0 \uC911\uB9BD\uC801\uC778 \uD569\uC758\uC548\uC744 \uC0B0\uCD9C\uD569\uB2C8\uB2E4. \uD504\uB85C\uD1A0\uCF5C\uC774 \uC815\uC758\uD55C \uCC44\uB110 \uC548\uC5D0\uC11C\uB9CC \uC751\uB2F5\uD558\uC2ED\uC2DC\uC624.","error.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 {seconds}\uCD08 \uB0B4\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","error.parseFailure":"\uCC38\uAC00\uC790 `{participantId}`\uC758 `<{tag}>` \uBE14\uB85D\uC744 \uD574\uC11D\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.","error.sessionNotFound":"\uD1A0\uB860 \uC138\uC158 `{sessionId}`\uC744(\uB97C) \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.invalidState":"\uC0C1\uD0DC `{state}`\uC5D0\uC11C\uB294 `{operation}` \uC791\uC5C5\uC744 \uC218\uD589\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.unknownLocaleFallback":"\uC54C \uC218 \uC5C6\uB294 \uB85C\uCF00\uC77C `{locale}`; \uAE30\uBCF8\uAC12 `{fallback}`(\uC73C)\uB85C \uB300\uCCB4\uD569\uB2C8\uB2E4.","askUser.escalation.header":"\uCD5C\uB300 \uB77C\uC6B4\uB4DC\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC73C\uB098 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4","askUser.escalation.question":"\uC5B4\uB5BB\uAC8C \uC9C4\uD589\uD558\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?","askUser.escalation.continue":"{rounds}\uB77C\uC6B4\uB4DC \uCD94\uAC00 \uC9C4\uD589","askUser.escalation.escalate":"\uD569\uC758 \uC5C6\uC774 \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","askUser.escalation.stop":"\uD1A0\uB860 \uC885\uB8CC"};var cm={"report.header.topic":"\u30C6\u30FC\u30DE","report.header.participants":"\u53C2\u52A0\u8005","report.header.individualDocs":"\u500B\u5225\u30EC\u30D3\u30E5\u30FC\u6587\u66F8","report.table.proposer":"\u63D0\u6848\u8005","report.table.opinion":"\u610F\u898B","report.table.severity":"\u91CD\u5927\u5EA6","report.table.agreement":"\u5408\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u5E33","report.section.dissentDetail":"\u672A\u5408\u610F\u9805\u76EE\u306E\u8A73\u7D30","report.section.contributionSummary":"AI \u8CA2\u732E\u5EA6\u30B5\u30DE\u30EA\u30FC","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u6848","report.contribution.accepted":"\u63A1\u629E","report.contribution.revises":"\u4FEE\u6B63\u8981\u8ACB","report.contribution.abstains":"\u68C4\u6A29","report.footer.synthesisPath":"\u6700\u7D42\u5408\u610F\u6587\u66F8","report.footer.debatePath":"\u8A0E\u8B70\u8A18\u9332","report.footer.pendingSynthesis":"(\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u5F85\u3061)","report.status.running":"\u9032\u884C\u4E2D","report.status.readyForApproval":"\u627F\u8A8D\u5F85\u3061","report.status.consensus":"\u5408\u610F\u5F62\u6210","report.status.escalated":"\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","report.status.approved":"\u627F\u8A8D\u6E08\u307F","report.status.rejected":"\u5374\u4E0B","report.status.leaderTimeout":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","report.status.error":"\u30A8\u30E9\u30FC","synthesis.status.consensus":"\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F","synthesis.status.escalated":"\u90E8\u5206\u5408\u610F / \u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","synthesis.section.acceptedItems":"\u63A1\u629E\u9805\u76EE","synthesis.section.rejectedItems":"\u5374\u4E0B / \u53D6\u308A\u4E0B\u3052\u9805\u76EE","synthesis.section.openItems":"\u672A\u6C7A\u9805\u76EE","synthesis.section.sources":"\u6839\u62E0","synthesis.narration.consensusIn":"\u5168 {max} \u30E9\u30A6\u30F3\u30C9\u4E2D {round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","synthesis.narration.escalated":"{round} \u30E9\u30A6\u30F3\u30C9\u7D4C\u904E\u3057\u3066\u3082\u5408\u610F\u306B\u81F3\u3089\u305A\u3001\u30E6\u30FC\u30B6\u30FC\u5224\u65AD\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3\u3055\u308C\u307E\u3057\u305F\u3002","synthesis.narration.leaderNote":"\u30EA\u30FC\u30C0\u30FC\u30E1\u30E2","approval.pending":"\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u3092\u5F85\u6A5F\u3057\u3066\u3044\u307E\u3059\u3002`agent_debate_approve`\u3001`agent_debate_continue`\u3001`agent_debate_reject` \u306E\u3044\u305A\u308C\u304B\u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044\u3002","approval.timeout":"\u30EA\u30FC\u30C0\u30FC\u5224\u65AD\u3092\u5F85\u6A5F\u4E2D\u306B\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F({hours} \u6642\u9593)\u3002","moderator.narration.roundHeader":"\u30E9\u30A6\u30F3\u30C9 {round}/{max}","moderator.narration.consensusInRound":"{round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u6C7A\u9805\u76EE","moderator.narration.noInterest":"\u53C2\u52A0\u8005\u306E\u95A2\u5FC3\u306A\u3057","moderator.narration.participantDropout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u7E70\u308A\u8FD4\u3057\u306E\u5931\u6557\u306B\u3088\u308A\u5229\u7528\u4E0D\u53EF\u3068\u3057\u3066\u30DE\u30FC\u30AF\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u4ECA\u56DE\u306E\u30E9\u30A6\u30F3\u30C9\u3067\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","moderator.narration.leaderTimeoutFooter":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","moderator.narration.rejected":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u5374\u4E0B\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.approved":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u627F\u8A8D\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.aliasClarification":"\u5225\u540D\u78BA\u8A8D\u30D5\u30A7\u30FC\u30BA","prompt.system.moderator":"\u3042\u306A\u305F\u306F\u69CB\u9020\u5316\u30DE\u30EB\u30C1 AI \u8A0E\u8B70\u306E\u30E2\u30C7\u30EC\u30FC\u30BF\u30FC\u3067\u3059\u3002\u63D0\u6848\u3092\u81EA\u3089\u8D77\u6848\u305B\u305A\u3001\u69CB\u9020\u5316\u6295\u7968\u3092\u96C6\u8A08\u3057\u3066\u4E2D\u7ACB\u7684\u306A\u5408\u610F\u6848\u3092\u63D0\u793A\u3057\u307E\u3059\u3002\u30D7\u30ED\u30C8\u30B3\u30EB\u304C\u5B9A\u7FA9\u3059\u308B\u30C1\u30E3\u30CD\u30EB\u306E\u7BC4\u56F2\u5185\u3067\u306E\u307F\u5FDC\u7B54\u3057\u3066\u304F\u3060\u3055\u3044\u3002","error.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F {seconds} \u79D2\u4EE5\u5185\u306B\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.parseFailure":"\u53C2\u52A0\u8005 `{participantId}` \u306E `<{tag}>` \u30D6\u30ED\u30C3\u30AF\u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.sessionNotFound":"\u8A0E\u8B70\u30BB\u30C3\u30B7\u30E7\u30F3 `{sessionId}` \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.invalidState":"\u72B6\u614B `{state}` \u3067\u306F\u64CD\u4F5C `{operation}` \u3092\u5B9F\u884C\u3067\u304D\u307E\u305B\u3093\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u306E\u30ED\u30B1\u30FC\u30EB `{locale}`\u3002\u65E2\u5B9A\u5024 `{fallback}` \u306B\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u3059\u3002","askUser.escalation.header":"\u6700\u5927\u30E9\u30A6\u30F3\u30C9\u306B\u9054\u3057\u307E\u3057\u305F\u304C\u5408\u610F\u306B\u81F3\u308A\u307E\u305B\u3093\u3067\u3057\u305F","askUser.escalation.question":"\u3069\u306E\u3088\u3046\u306B\u9032\u3081\u307E\u3059\u304B?","askUser.escalation.continue":"{rounds} \u30E9\u30A6\u30F3\u30C9\u8FFD\u52A0\u3057\u3066\u7D9A\u884C","askUser.escalation.escalate":"\u5408\u610F\u306A\u3057\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","askUser.escalation.stop":"\u8A0E\u8B70\u3092\u7D42\u4E86"};var um={"report.header.topic":"\u4E3B\u9898","report.header.participants":"\u53C2\u4E0E\u8005","report.header.individualDocs":"\u4E2A\u4EBA\u8BC4\u5BA1\u6587\u6863","report.table.proposer":"\u63D0\u8BAE\u8005","report.table.opinion":"\u610F\u89C1","report.table.severity":"\u4E25\u91CD\u7A0B\u5EA6","report.table.agreement":"\u540C\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u8D26","report.section.dissentDetail":"\u672A\u8FBE\u6210\u4E00\u81F4\u9879\u8BE6\u60C5","report.section.contributionSummary":"AI \u8D21\u732E\u6C47\u603B","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u51FA","report.contribution.accepted":"\u91C7\u7EB3","report.contribution.revises":"\u4FEE\u8BA2\u8BF7\u6C42","report.contribution.abstains":"\u5F03\u6743","report.footer.synthesisPath":"\u6700\u7EC8\u5171\u8BC6\u6587\u6863","report.footer.debatePath":"\u8FA9\u8BBA\u8BB0\u5F55","report.footer.pendingSynthesis":"(\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6)","report.status.running":"\u8FDB\u884C\u4E2D","report.status.readyForApproval":"\u5F85\u6279\u51C6","report.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","report.status.escalated":"\u5DF2\u5347\u7EA7","report.status.approved":"\u5DF2\u6279\u51C6","report.status.rejected":"\u5DF2\u62D2\u7EDD","report.status.leaderTimeout":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","report.status.error":"\u9519\u8BEF","synthesis.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","synthesis.status.escalated":"\u90E8\u5206\u5171\u8BC6 / \u5DF2\u5347\u7EA7","synthesis.section.acceptedItems":"\u91C7\u7EB3\u9879","synthesis.section.rejectedItems":"\u62D2\u7EDD / \u64A4\u56DE\u9879","synthesis.section.openItems":"\u672A\u51B3\u9879","synthesis.section.sources":"\u4F9D\u636E","synthesis.narration.consensusIn":"\u5728\u5168\u90E8 {max} \u8F6E\u4E2D\u7684\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","synthesis.narration.escalated":"\u7ECF\u8FC7 {round} \u8F6E\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6,\u7531\u7528\u6237\u51B3\u5B9A\u5347\u7EA7\u5904\u7406\u3002","synthesis.narration.leaderNote":"\u8D1F\u8D23\u4EBA\u5907\u6CE8","approval.pending":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6\u3002\u8BF7\u8C03\u7528 `agent_debate_approve`\u3001`agent_debate_continue` \u6216 `agent_debate_reject`\u3002","approval.timeout":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u51B3\u7B56\u671F\u95F4\u4F1A\u8BDD\u5DF2\u8D85\u65F6({hours} \u5C0F\u65F6)\u3002","moderator.narration.roundHeader":"\u7B2C {round}/{max} \u8F6E","moderator.narration.consensusInRound":"\u5728\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u51B3\u9879","moderator.narration.noInterest":"\u53C2\u4E0E\u8005\u65E0\u5174\u8DA3","moderator.narration.participantDropout":"\u53C2\u4E0E\u8005 `{participantId}` \u56E0\u591A\u6B21\u5931\u8D25\u88AB\u6807\u8BB0\u4E3A\u4E0D\u53EF\u7528\u3002","moderator.narration.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728\u672C\u8F6E\u672A\u4F5C\u51FA\u54CD\u5E94\u3002","moderator.narration.leaderTimeoutFooter":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","moderator.narration.rejected":"\u8D1F\u8D23\u4EBA\u5DF2\u62D2\u7EDD\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.approved":"\u8D1F\u8D23\u4EBA\u5DF2\u6279\u51C6\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.aliasClarification":"\u522B\u540D\u6F84\u6E05\u9636\u6BB5","prompt.system.moderator":"\u4F60\u662F\u7ED3\u6784\u5316\u591A AI \u8FA9\u8BBA\u7684\u4E3B\u6301\u4EBA\u3002\u4F60\u4E0D\u64B0\u5199\u63D0\u6848,\u800C\u662F\u6C47\u603B\u7ED3\u6784\u5316\u6295\u7968\u5E76\u4EA7\u51FA\u4E2D\u7ACB\u7684\u5171\u8BC6\u65B9\u6848\u3002\u4EC5\u5728\u534F\u8BAE\u5B9A\u4E49\u7684\u901A\u9053\u8303\u56F4\u5185\u4F5C\u51FA\u54CD\u5E94\u3002","error.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728 {seconds} \u79D2\u5185\u672A\u54CD\u5E94\u3002","error.parseFailure":"\u65E0\u6CD5\u89E3\u6790\u53C2\u4E0E\u8005 `{participantId}` \u7684 `<{tag}>` \u5757\u3002","error.sessionNotFound":"\u672A\u627E\u5230\u8FA9\u8BBA\u4F1A\u8BDD `{sessionId}`\u3002","error.invalidState":"\u5728\u72B6\u6001 `{state}` \u4E0B\u4E0D\u5141\u8BB8\u6267\u884C\u64CD\u4F5C `{operation}`\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u533A\u57DF `{locale}`,\u56DE\u9000\u5230 `{fallback}`\u3002","askUser.escalation.header":"\u5DF2\u8FBE\u6700\u5927\u8F6E\u6B21\u4F46\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6","askUser.escalation.question":"\u60A8\u5E0C\u671B\u5982\u4F55\u7EE7\u7EED?","askUser.escalation.continue":"\u518D\u8FDB\u884C {rounds} \u8F6E","askUser.escalation.escalate":"\u4E0D\u8FBE\u6210\u5171\u8BC6\u5373\u5347\u7EA7","askUser.escalation.stop":"\u7ED3\u675F\u8FA9\u8BBA"};var lm=Object.freeze({en:im,ko:am,ja:cm,zh:um});function u0(t){return typeof t=="string"&&Vs.includes(t)}function Yc(t,e){return e===void 0?t:t.replace(/\{(\w+)\}/g,(r,n)=>{if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];return typeof o=="number"?String(o):o}return r})}function dm(t){return t===void 0?Qc(xr):u0(t)?Qc(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${xr}`),Qc(xr))}function l0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return Yc(i,s);let a=r[o];return a!==void 0?(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in locale '${t}', falling back to ${Oc}`)),Yc(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),Yc(o,s))}}}function Qc(t){return l0(t,lm[t],lm[Oc])}async function pm(t){let e=await fetch(`${t}/api/tags`);if(!e.ok)throw new Error(`Ollama API error: ${e.status}`);return((await e.json()).models||[]).map(n=>({name:n.name||"unknown",size:n.size||0,strengths:d0(n.name||"")}))}function d0(t){let e=["chat"],r=t.toLowerCase();return(r.includes("coder")||r.includes("code"))&&e.push("code_review","code_generation"),r.includes("instruct")&&e.push("instruction_following"),r.includes("embed")&&e.push("embedding"),e}var qr=class t{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(e){this.id=e.id,this.host=e.host,this.defaultModel=e.defaultModel||"auto",this.maxContext=e.maxContext??32768,this.timeouts={default:e.timeouts?.default??3e4,generate:e.timeouts?.generate??3e5,chat:e.timeouts?.chat??3e5}}async initialize(){try{this.models=await pm(this.host),this.available=this.models.length>0}catch{this.available=!1}}async healthCheck(){try{let e=await fetch(`${this.host}/api/tags`);if(!e.ok)return{status:"error",message:`HTTP ${e.status}`};let r=await e.json(),n=r.models?.length??0;return{status:n>0?"ok":"degraded",message:`${n} models available`,details:{models:r.models?.map(o=>o.name)}}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(e=>e.strengths))],models:this.models.map(e=>({name:e.name,description:`Ollama model (${Math.round(e.size/1e9)}GB)`,strengths:e.strengths,sizeGb:e.size/1e9}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(e){if(!this.available)throw new me(this.id,"Ollama not running or no models installed");let r=e.model||this.selectModel(),n={model:r,prompt:e.prompt,system:e.system||"You are a helpful assistant.",stream:!1,...e.extra||{}},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeouts.generate);try{let i=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(i.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new me(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!i.ok)throw new He(this.id,`HTTP ${i.status}: ${i.statusText}`);let a=await i.json();return{text:a.response||"",model:a.model||r,provider:this.id}}catch(i){throw i.name==="AbortError"?new un(this.id,this.timeouts.generate):i instanceof He||i instanceof me?i:new He(this.id,i.message)}finally{clearTimeout(s)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new me(this.id,`No models detected. Install a model first (ollama pull ${Yp})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var f0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function fm(t){return t.split(`
40
+ `).filter(n=>{let o=n.trim();return o?!f0.some(s=>s.test(o)):!1}).join(`
41
+ `).trim()}function mm(t){try{let e=JSON.parse(t.trim());if(e&&typeof e.response=="string")return e.response}catch{let e=t.split(`
42
+ `);for(let r=e.length-1;r>=0;r--){let n=e[r].trim();if(n.startsWith("{"))try{let o=JSON.parse(n);if(o&&typeof o.response=="string")return o.response}catch{}}}return null}var Xc="gemini",eu="@google/gemini-cli",Vr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new Sn(cf);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await kn(Xc,eu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){if(!this.available)return{status:"error",message:"Gemini CLI not installed"};try{let{command:e,cliArgs:r}=ar(this.cliPath,Xc,eu,["--version"]),n=await ze({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Gemini CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["long_context","file_analysis","translation","summarization"],models:[{name:"gemini-2.5-pro",description:"Google Gemini 2.5 Pro via CLI",strengths:["long_context","reasoning"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available)throw new me(this.id,"Gemini CLI not installed");let r=Ur(e),n=mi(e,r),s=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=ar(this.cliPath,Xc,eu,s),c=sm(this.id);try{let u=await ze({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,onStderrChunk:p=>c.feed(p)});if(u.exitCode!==0)try{Pn(u.exitCode,u.stderr,this.id)}catch(p){throw p.markUnavailable&&(this.available=!1),p}let l=mm(u.stdout);if(l!==null){let p=m0(u.stdout);return{text:l,model:p,provider:this.id}}return{text:fm(u.stdout),model:"gemini",provider:this.id}}catch(u){if(u instanceof me)throw u.markUnavailable&&(this.available=!1),u;Tn(u,this.id,this.timeout)}}};function m0(t){try{let e=JSON.parse(t.trim());if(e?.stats?.models){for(let[n,o]of Object.entries(e.stats.models))if(o?.roles?.main)return n;let r=Object.keys(e.stats.models);if(r.length>0)return r[0]}}catch{}return"gemini"}import{randomUUID as h0}from"crypto";function tu(t){let e=t.trim().split(`
43
43
  `),r=[];for(let n of e)try{let o=JSON.parse(n);o.type==="item.completed"&&o.item?.type==="agent_message"&&o.item.text&&r.push(o.item.text)}catch{n.trim()&&r.push(n.trim())}return r.join(`
44
- `)||t.trim()}var Xs="codex",ei="@openai/codex";function PS(){return["-C",process.cwd()]}function ES(t,e){return["exec","--skip-git-repo-check","-C",process.cwd(),"--full-auto","--ephemeral","--json","--",e?"-":t]}var Fr=class{id;type="codex-cli";timeout;available=!1;cliPath=null;appServer=null;constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await Sn(Xs,ei);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new Gs({command:this.cliPath==="npx"?"npx":Xs,commandPrefix:this.cliPath==="npx"?[ei]:void 0,commandArgs:PS()}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=or(this.cliPath,Xs,ei,["--version"]),n=await De({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Codex CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:128e3,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!0,strengths:["code_generation","code_review","autonomous_execution"],models:[{name:"codex",description:"OpenAI Codex CLI",strengths:["code_generation"]}]}}isAvailable(){return this.available}async chat(e){if(!this.available)throw new me(this.id,"Codex CLI not installed");if(this.appServer&&!this.appServer.shouldFallback())try{return await this.chatViaAppServer(e)}catch{}return this.chatViaCli(e)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r={method:"exec",params:{prompt:Lr(e),fullAuto:!0,ephemeral:!0},id:TS()},n=await this.appServer.request(r,this.timeout);if(n.error)throw new Be(this.id,n.error.message);return{text:vc(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=Lr(e),n=process.platform==="win32"||Js(e,r),o=ES(r,n),{command:s,cliArgs:i}=or(this.cliPath,Xs,ei,o);try{let a=await De({command:s,args:i,stdin:n?r:void 0,timeout:this.timeout});if(a.exitCode!==0)try{kn(a.exitCode,a.stderr,this.id)}catch(u){throw u.markUnavailable&&(this.available=!1),u}return{text:vc(a.stdout),model:"codex",provider:this.id}}catch(a){Tn(a,this.id,this.timeout)}}};function yf(t){try{return JSON.parse(t.trim())}catch{return null}}function _f(t){let e=yf(t);if(e)return e;let r=t.split(`
45
- `);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=yf(o);if(s)return s}return null}function vf(t){let e=_f(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function xf(t){let e=_f(t);return typeof e?.model=="string"?e.model:"claude"}var RS=1,xc="claude",bc="@anthropic-ai/claude-code",Ur=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new wn(RS);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await Sn(xc,bc);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return pf(this.cliPath,xc,bc,"Claude")}getCapabilities(){return{maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude",description:"Anthropic Claude Code CLI",strengths:["reasoning","review","synthesis"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available||!this.cliPath)throw new me(this.id,"Claude CLI not installed");let r=Lr(e),n=["-p","--output-format","json"];e.model&&n.push("--model",e.model),n.push(r);let{command:o,cliArgs:s}=or(this.cliPath,xc,bc,n);try{let i=await De({command:o,args:s,timeout:this.timeout});if(i.exitCode!==0){let c=[i.stderr,i.stdout].filter(Boolean).join(`
46
- `).trim();try{kn(i.exitCode,c,this.id)}catch(u){throw(u.markUnavailable||/auth|credential|login|api key|oauth|token|401/i.test(c))&&(this.available=!1),u}}return{text:vf(i.stdout)??i.stdout.trim(),model:xf(i.stdout),provider:this.id}}catch(i){Tn(i,this.id,this.timeout)}}};import{randomUUID as zS}from"crypto";var ho=class t{static AGREEMENT_PATTERNS=[/\bi\s+agree\b/i,/\bi\s+concur\b/i,/\bfully\s+agree\b/i,/\bagree\s+with\s+(this|that|the|your|all)\b/i,/\bno\s+(further\s+)?objections?\b/i,/\breached\s+(a\s+)?consensus\b/i,/\blet'?s?\s+go\s+with\s+(this|that)\b/i,/\bsounds?\s+good\b/i,/\bi'?m?\s+on\s+board\b/i,/동의합니다/,/찬성합니다/,/동의해요/,/이견\s*없습니다/,/이의\s*없습니다/,/합의/,/同意します/,/賛成です/,/異議(は)?ありません/,/同意/,/赞成/,/没有异议/];analyzeConsensus(e){if(e.turns.length<2)return{reached:!1,signals:[],recommendation:"continue",reason:"Not enough turns for consensus detection (minimum 2 required)."};let r=new Set(e.providerIds),n=new Map;for(let u of e.turns)r.has(u.speaker)&&n.set(u.speaker,u);let o=[];for(let u of r){let l=n.get(u);if(!l){o.push({speaker:u,agreedExplicitly:!1});continue}let d=this.findAgreementExpression(l.content);o.push({speaker:u,agreedExplicitly:!!d,agreementExpression:d??void 0})}let s=o.length>0&&o.every(u=>u.agreedExplicitly),i=o.some(u=>u.agreedExplicitly);if(s)return{reached:!0,signals:o,recommendation:"conclude",reason:"All participants have explicitly expressed agreement."};let a=o.filter(u=>u.agreedExplicitly).map(u=>u.speaker),c=o.filter(u=>!u.agreedExplicitly).map(u=>u.speaker);return{reached:!1,signals:o,recommendation:"continue",reason:i?`Partial agreement: ${a.join(", ")} agreed. Awaiting: ${c.join(", ")}.`:"No explicit agreement expressions detected from any participant."}}findAgreementExpression(e){for(let r of t.AGREEMENT_PATTERNS){let n=e.match(r);if(n)return n[0]}return null}},CS=7200*1e3,go=class{debates=new Map;create(e){this.purgeStaleDebates();let r=zS(),n=new Date().toISOString(),o={id:r,topic:e.topic,goal:e.goal,providerIds:e.providerIds,turns:[],status:"active",documentId:e.documentId,createdAt:n};return this.debates.set(r,o),o}addTurn(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);if(o.status==="concluded")throw new Error(`Debate already concluded: ${e}`);let s={turnNumber:o.turns.length+1,speaker:r,content:n,timestamp:new Date().toISOString()};return o.turns.push(s),o}buildPromptForProvider(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);let o=`Topic: ${n.topic}
44
+ `)||t.trim()}var vi="codex",_i="@openai/codex";function g0(){return["-C",process.cwd()]}function y0(t,e){return["exec","--skip-git-repo-check","-C",process.cwd(),"--full-auto","--ephemeral","--json","--",e?"-":t]}var Br=class{id;type="codex-cli";timeout;available=!1;cliPath=null;appServer=null;constructor(e){this.id=e.id,this.timeout=e.timeout??6e5}async initialize(){let e=await kn(vi,_i);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new fi({command:this.cliPath==="npx"?"npx":vi,commandPrefix:this.cliPath==="npx"?[_i]:void 0,commandArgs:g0()}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=ar(this.cliPath,vi,_i,["--version"]),n=await ze({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Codex CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:128e3,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!0,strengths:["code_generation","code_review","autonomous_execution"],models:[{name:"codex",description:"OpenAI Codex CLI",strengths:["code_generation"]}]}}isAvailable(){return this.available}async chat(e){if(!this.available)throw new me(this.id,"Codex CLI not installed");if(this.appServer&&!this.appServer.shouldFallback())try{return await this.chatViaAppServer(e)}catch{}return this.chatViaCli(e)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r={method:"exec",params:{prompt:Ur(e),fullAuto:!0,ephemeral:!0},id:h0()},n=await this.appServer.request(r,this.timeout);if(n.error)throw new He(this.id,n.error.message);return{text:tu(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=Ur(e),n=process.platform==="win32"||mi(e,r),o=y0(r,n),{command:s,cliArgs:i}=ar(this.cliPath,vi,_i,o);try{let a=await ze({command:s,args:i,stdin:n?r:void 0,timeout:this.timeout});if(a.exitCode!==0)try{Pn(a.exitCode,a.stderr,this.id)}catch(u){throw u.markUnavailable&&(this.available=!1),u}return{text:tu(a.stdout),model:"codex",provider:this.id}}catch(a){Tn(a,this.id,this.timeout)}}};function hm(t){try{return JSON.parse(t.trim())}catch{return null}}function gm(t){let e=hm(t);if(e)return e;let r=t.split(`
45
+ `);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=hm(o);if(s)return s}return null}function ym(t){let e=gm(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function vm(t){let e=gm(t);return typeof e?.model=="string"?e.model:"claude"}var v0=1,ru="claude",nu="@anthropic-ai/claude-code",Wr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Sn(v0);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await kn(ru,nu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return om(this.cliPath,ru,nu,"Claude")}getCapabilities(){return{maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude",description:"Anthropic Claude Code CLI",strengths:["reasoning","review","synthesis"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available||!this.cliPath)throw new me(this.id,"Claude CLI not installed");let r=Ur(e),n=["-p","--output-format","json"];e.model&&n.push("--model",e.model),n.push(r);let{command:o,cliArgs:s}=ar(this.cliPath,ru,nu,n);try{let i=await ze({command:o,args:s,timeout:this.timeout});if(i.exitCode!==0){let c=[i.stderr,i.stdout].filter(Boolean).join(`
46
+ `).trim();try{Pn(i.exitCode,c,this.id)}catch(u){throw(u.markUnavailable||/auth|credential|login|api key|oauth|token|401/i.test(c))&&(this.available=!1),u}}return{text:ym(i.stdout)??i.stdout.trim(),model:vm(i.stdout),provider:this.id}}catch(i){Tn(i,this.id,this.timeout)}}};import{randomUUID as _0}from"crypto";var b0=7200*1e3,Po=class{debates=new Map;create(e){this.purgeStaleDebates();let r=_0(),n=new Date().toISOString(),o={id:r,topic:e.topic,goal:e.goal,providerIds:e.providerIds,turns:[],status:"active",documentId:e.documentId,createdAt:n};return this.debates.set(r,o),o}addTurn(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);if(o.status==="concluded")throw new Error(`Debate already concluded: ${e}`);let s={turnNumber:o.turns.length+1,speaker:r,content:n,timestamp:new Date().toISOString()};return o.turns.push(s),o}buildPromptForProvider(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);let o=`Topic: ${n.topic}
47
47
  `;if(n.goal&&(o+=`Goal: ${n.goal}
48
48
  `),n.turns.length>0){o+=`
49
49
  === Conversation History ===
50
50
 
51
- `;let i=n.turns.length;if(i>Ts){let u=i-Ts,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];o+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
51
+ `;let i=n.turns.length;if(i>qs){let u=i-qs,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];o+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
52
52
 
53
- `}let a=n.turns.slice(-Ts),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
53
+ `}let a=n.turns.slice(-qs),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
54
54
  ${u.content}
55
55
 
56
- `;if(c.length+l.length>tc){c+=`[... history truncated at ${tc} characters]
56
+ `;if(c.length+l.length>Ac){c+=`[... history truncated at ${Ac} characters]
57
57
 
58
58
  `;break}c+=l}o+=c,o+=`===
59
59
 
@@ -77,7 +77,7 @@ ${u.content}
77
77
  `,o+=`- Be thorough and detailed in your response
78
78
  `),n.goal&&(o+=`
79
79
  Evaluation goal: ${n.goal}
80
- `),o}conclude(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);return r.status="concluded",r}getState(e){return this.debates.get(e)}delete(e){return this.debates.delete(e)}recordConsensusCheck(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);n.consensusHistory||(n.consensusHistory=[]),n.consensusHistory.push(r)}markProviderUnavailable(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);o.providerIds.includes(r)&&(o.unavailableProviders||(o.unavailableProviders=[]),!o.unavailableProviders.some(s=>s.providerId===r)&&o.unavailableProviders.push({providerId:r,reason:n,recordedAt:new Date().toISOString()}))}getActiveProviders(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);let n=new Set((r.unavailableProviders??[]).map(o=>o.providerId));return r.providerIds.filter(o=>!n.has(o))}isProviderUnavailable(e,r){let n=this.getState(e);return n?(n.unavailableProviders??[]).some(o=>o.providerId===r):!1}buildTurnTranscript(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);let n=`# Debate: ${r.topic}
80
+ `),o}conclude(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);return r.status="concluded",r}getState(e){return this.debates.get(e)}delete(e){return this.debates.delete(e)}markProviderUnavailable(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);o.providerIds.includes(r)&&(o.unavailableProviders||(o.unavailableProviders=[]),!o.unavailableProviders.some(s=>s.providerId===r)&&o.unavailableProviders.push({providerId:r,reason:n,recordedAt:new Date().toISOString()}))}getActiveProviders(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);let n=new Set((r.unavailableProviders??[]).map(o=>o.providerId));return r.providerIds.filter(o=>!n.has(o))}isProviderUnavailable(e,r){let n=this.getState(e);return n?(n.unavailableProviders??[]).some(o=>o.providerId===r):!1}buildTurnTranscript(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);let n=`# Debate: ${r.topic}
81
81
 
82
82
  `;r.goal&&(n+=`**Goal:** ${r.goal}
83
83
 
@@ -89,31 +89,31 @@ Evaluation goal: ${n.goal}
89
89
 
90
90
  ${o.content}
91
91
 
92
- `;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>CS&&this.debates.delete(r)}}};import{mkdirSync as AS,readFileSync as bf,readdirSync as IS,existsSync as wf}from"fs";import{join as DS}from"path";import{randomUUID as OS}from"crypto";function wc(t){if(t.providers<=0)throw new Error(`deriveTerminalStatus: providers must be positive, got ${t.providers}`);if(t.failed<0||t.failed>t.providers)throw new Error(`deriveTerminalStatus: failed (${t.failed}) out of range [0, ${t.providers}]`);return t.failed===0?"completed":t.failed===t.providers?"failed":"completed_with_errors"}var $f=new Set(["completed","completed_with_errors","failed"]);function Sf(t,e){return $f.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&$f.has(e)||t==="in_progress"&&e==="in_progress")}function kf(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}var yo=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=DS(e,"sessions"),AS(this.sessionDir,{recursive:!0}),this.sessions=new Map}createSession(e,r){let n=new Date().toISOString(),o={id:OS(),type:e,status:"pending",config:r,createdAt:n,updatedAt:n};return this.sessions.set(o.id,o),this.persist(o),o}getSession(e){let r=this.sessions.get(e);if(r)return r;if(!this.fullyLoaded){let n;try{n=Me(`${e}.json`,this.sessionDir)}catch{return}if(wf(n))try{let o=bf(n,"utf-8"),s=JSON.parse(o);return kf(s)?(this.sessions.set(s.id,s),s):void 0}catch{}}}listSessions(){return this.ensureFullyLoaded(),[...this.sessions.values()]}updateSessionStatus(e,r){let n=this.getSession(e);if(!n)throw new Error(`Session not found: ${e}`);if(!Sf(n.status,r))throw new Error(`Illegal session transition: ${n.id} ${n.status} -> ${r}`);n.status=r,n.updatedAt=new Date().toISOString(),this.persist(n)}transitionSession(e,r,n){let o=this.getSession(e);if(!o)throw new Error(`Session not found: ${e}`);if(!Sf(o.status,r))throw new Error(`Illegal session transition: ${o.id} ${o.status} -> ${r}`);o.status=r,n!==void 0&&(o.result=n),o.updatedAt=new Date().toISOString(),this.persist(o)}completeSession(e,r){this.transitionSession(e,"completed",r)}persist(e){let r=Me(`${e.id}.json`,this.sessionDir);it(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!wf(this.sessionDir)){this.fullyLoaded=!0;return}let e=IS(this.sessionDir).filter(r=>r.endsWith(".json"));for(let r of e){let n=r.replace(/\.json$/,"");if(!this.sessions.has(n))try{let o=Me(r,this.sessionDir),s=bf(o,"utf-8"),i=JSON.parse(s);if(!kf(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function Pn(t){if(!t||!t.trim())return null;try{return JSON.parse(t.trim())}catch{}let e=[],r=0,n=-1;for(let o=0;o<t.length;o++){let s=t[o];s==="{"?(r===0&&(n=o),r++):s==="}"&&(r--,r===0&&n>=0&&(e.push(t.slice(n,o+1)),n=-1),r<0&&(r=0))}if(e.length===0)return null;for(let o=e.length-1;o>=0;o--)try{return JSON.parse(e[o])}catch{continue}return null}function Tf(t,e,r){try{let n=Pn(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var _o=class{registry;chatAdapter;constructor(e,r){this.registry=e,this.chatAdapter=r}async chatWith(e,r){return this.chatAdapter?this.chatAdapter.chat(e,r):e.chat(r)}canValidate(e){if(this.chatAdapter){let r=this.registry.getCapability(e);return r.tier==="agent"||r.tier==="tool"}return this.isAgentTier(e)}async validate(e){let{items:r,criteria:n}=e,o=this.resolveValidators(e),s=[];for(let l of r)for(let d of o)d.id!==l.providerId&&s.push(this.reviewItem(l,d,n));let i=await Promise.all(s),a=this.detectConflicts(i),c=i.length>0&&i.every(l=>l.passed),u=i.length===0?this.chatAdapter?"No validators available for cross-validation.":"No agent-tier validators available for cross-validation.":void 0;return{reviews:i,overallPass:c,conflicts:a,message:u}}resolveValidators(e){if(e.validators)return e.validators.filter(o=>this.canValidate(o.id));let r=new Set,n=[];for(let o of e.items)r.has(o.providerId)||(r.add(o.providerId),this.canValidate(o.providerId)&&n.push(this.registry.get(o.providerId)));return n}isAgentTier(e){return this.registry.getCapability(e).tier==="agent"}async reviewItem(e,r,n){let o=n?`
92
+ `;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>b0&&this.debates.delete(r)}}};import{mkdirSync as w0,readFileSync as _m,readdirSync as ou,existsSync as bi,renameSync as x0,rmdirSync as S0}from"fs";import{join as $0}from"path";import{randomUUID as k0}from"crypto";function su(t){if(t.providers<=0)throw new Error(`deriveTerminalStatus: providers must be positive, got ${t.providers}`);if(t.failed<0||t.failed>t.providers)throw new Error(`deriveTerminalStatus: failed (${t.failed}) out of range [0, ${t.providers}]`);return t.failed===0?"completed":t.failed===t.providers?"failed":"completed_with_errors"}var bm=new Set(["completed","completed_with_errors","failed"]);function wm(t,e){return bm.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&bm.has(e)||t==="in_progress"&&e==="in_progress")}function xm(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}var To=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,w0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=$0(this.sessionDir,"sessions");if(!bi(e))return;let r;try{r=ou(e)}catch(o){console.warn(`[SessionManager] failed to read legacy nested dir ${e}: ${String(o)}`);return}let n=r.filter(o=>o.endsWith(".json"));for(let o of n){let s,i;try{s=Me(o,e),i=Me(o,this.sessionDir)}catch(a){console.warn(`[SessionManager] skipped legacy file ${JSON.stringify(o)}: ${String(a)}`);continue}if(bi(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{x0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{ou(e).length===0&&S0(e)}catch(o){console.warn(`[SessionManager] could not remove legacy nested dir ${e}: ${String(o)}`)}}createSession(e,r){let n=new Date().toISOString(),o={id:k0(),type:e,status:"pending",config:r,createdAt:n,updatedAt:n};return this.sessions.set(o.id,o),this.persist(o),o}getSession(e){let r=this.sessions.get(e);if(r)return r;if(!this.fullyLoaded){let n;try{n=Me(`${e}.json`,this.sessionDir)}catch{return}if(bi(n))try{let o=_m(n,"utf-8"),s=JSON.parse(o);return xm(s)?(this.sessions.set(s.id,s),s):void 0}catch{}}}listSessions(){return this.ensureFullyLoaded(),[...this.sessions.values()]}updateSessionStatus(e,r){let n=this.getSession(e);if(!n)throw new Error(`Session not found: ${e}`);if(!wm(n.status,r))throw new Error(`Illegal session transition: ${n.id} ${n.status} -> ${r}`);n.status=r,n.updatedAt=new Date().toISOString(),this.persist(n)}transitionSession(e,r,n){let o=this.getSession(e);if(!o)throw new Error(`Session not found: ${e}`);if(!wm(o.status,r))throw new Error(`Illegal session transition: ${o.id} ${o.status} -> ${r}`);o.status=r,n!==void 0&&(o.result=n),o.updatedAt=new Date().toISOString(),this.persist(o)}completeSession(e,r){this.transitionSession(e,"completed",r)}persist(e){let r=Me(`${e.id}.json`,this.sessionDir);Ue(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!bi(this.sessionDir)){this.fullyLoaded=!0;return}let e=ou(this.sessionDir).filter(r=>r.endsWith(".json"));for(let r of e){let n=r.replace(/\.json$/,"");if(!this.sessions.has(n))try{let o=Me(r,this.sessionDir),s=_m(o,"utf-8"),i=JSON.parse(s);if(!xm(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function En(t){if(!t||!t.trim())return null;try{return JSON.parse(t.trim())}catch{}let e=[],r=0,n=-1;for(let o=0;o<t.length;o++){let s=t[o];s==="{"?(r===0&&(n=o),r++):s==="}"&&(r--,r===0&&n>=0&&(e.push(t.slice(n,o+1)),n=-1),r<0&&(r=0))}if(e.length===0)return null;for(let o=e.length-1;o>=0;o--)try{return JSON.parse(e[o])}catch{continue}return null}function Sm(t,e,r){try{let n=En(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var Eo=class{registry;chatAdapter;constructor(e,r){this.registry=e,this.chatAdapter=r}async chatWith(e,r){return this.chatAdapter?this.chatAdapter.chat(e,r):e.chat(r)}canValidate(e){if(this.chatAdapter){let r=this.registry.getCapability(e);return r.tier==="agent"||r.tier==="tool"}return this.isAgentTier(e)}async validate(e){let{items:r,criteria:n}=e,o=this.resolveValidators(e),s=[];for(let l of r)for(let d of o)d.id!==l.providerId&&s.push(this.reviewItem(l,d,n));let i=await Promise.all(s),a=this.detectConflicts(i),c=i.length>0&&i.every(l=>l.passed),u=i.length===0?this.chatAdapter?"No validators available for cross-validation.":"No agent-tier validators available for cross-validation.":void 0;return{reviews:i,overallPass:c,conflicts:a,message:u}}resolveValidators(e){if(e.validators)return e.validators.filter(o=>this.canValidate(o.id));let r=new Set,n=[];for(let o of e.items)r.has(o.providerId)||(r.add(o.providerId),this.canValidate(o.providerId)&&n.push(this.registry.get(o.providerId)));return n}isAgentTier(e){return this.registry.getCapability(e).tier==="agent"}async reviewItem(e,r,n){let o=n?`
93
93
  Additional criteria: ${n}`:"",s=[`You are a cross-validator reviewing work from provider "${e.providerId}".`,`Task: ${e.task}`,`Content to review:
94
94
  ${e.content}`,o,"",'Respond with JSON only: { "passed": boolean, "feedback": "string", "suggestedFixes": "string or omit" }'].join(`
95
- `),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return Tf(n,o=>({targetProvider:e,reviewerProvider:r,passed:!!o.passed,feedback:String(o.feedback??""),suggestedFixes:o.suggestedFixes?String(o.suggestedFixes):void 0}),o=>({targetProvider:e,reviewerProvider:r,passed:!1,feedback:o}))}detectConflicts(e){let r=[],n=new Map;for(let o of e){let s=o.targetProvider;n.has(s)||n.set(s,[]),n.get(s).push(o)}for(let[o,s]of n){if(s.length<2)continue;let i=s.filter(c=>c.passed),a=s.filter(c=>!c.passed);if(i.length>0&&a.length>0){let c=i.map(l=>l.reviewerProvider).join(", "),u=a.map(l=>l.reviewerProvider).join(", ");r.push(`Conflict on "${o}": passed by [${c}], failed by [${u}]`)}}return r}};import{readFileSync as Rf,readdirSync as zf,statSync as ri}from"fs";import{join as Cf,relative as jS}from"path";var Pf=50*1024,ti=500,Ef=100;function LS(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function ZS(t,e){let r=[],n=o=>{let s=ri(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of zf(o)){let a=Cf(o,i),c=ri(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function qS(t,e){if(process.platform!=="win32")return{command:t,args:e};let r=n=>`'${n.replace(/'/g,"''")}'`;switch(t){case"ls":{let n=e.length>0?r(e[0]):".",o=e.slice(1).map(r);return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-ChildItem -Name -LiteralPath ${n}${o.length?" "+o.join(" "):""}`]}}case"cat":return e.length===0?{command:t,args:e}:{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-Content -LiteralPath ${e.map(r).join(",")}`]};default:return{command:t,args:e}}}var Af={name:"file_read",description:"Read the contents of a file. Returns the text content.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},offset:{type:"number",description:"Line offset to start reading from (0-based)"},limit:{type:"number",description:"Maximum number of lines to read"}},async execute(t,e){let r=Ft(String(t.path??""),e),n=Rf(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
95
+ `),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return Sm(n,o=>({targetProvider:e,reviewerProvider:r,passed:!!o.passed,feedback:String(o.feedback??""),suggestedFixes:o.suggestedFixes?String(o.suggestedFixes):void 0}),o=>({targetProvider:e,reviewerProvider:r,passed:!1,feedback:o}))}detectConflicts(e){let r=[],n=new Map;for(let o of e){let s=o.targetProvider;n.has(s)||n.set(s,[]),n.get(s).push(o)}for(let[o,s]of n){if(s.length<2)continue;let i=s.filter(c=>c.passed),a=s.filter(c=>!c.passed);if(i.length>0&&a.length>0){let c=i.map(l=>l.reviewerProvider).join(", "),u=a.map(l=>l.reviewerProvider).join(", ");r.push(`Conflict on "${o}": passed by [${c}], failed by [${u}]`)}}return r}};import{readFileSync as Pm,readdirSync as Tm,statSync as xi}from"fs";import{join as Em,relative as E0}from"path";var $m=50*1024,wi=500,km=100;function R0(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function I0(t,e){let r=[],n=o=>{let s=xi(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of Tm(o)){let a=Em(o,i),c=xi(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function A0(t,e){if(process.platform!=="win32")return{command:t,args:e};let r=n=>`'${n.replace(/'/g,"''")}'`;switch(t){case"ls":{let n=e.length>0?r(e[0]):".",o=e.slice(1).map(r);return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-ChildItem -Name -LiteralPath ${n}${o.length?" "+o.join(" "):""}`]}}case"cat":return e.length===0?{command:t,args:e}:{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-Content -LiteralPath ${e.map(r).join(",")}`]};default:return{command:t,args:e}}}var Rm={name:"file_read",description:"Read the contents of a file. Returns the text content.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},offset:{type:"number",description:"Line offset to start reading from (0-based)"},limit:{type:"number",description:"Maximum number of lines to read"}},async execute(t,e){let r=Bt(String(t.path??""),e),n=Pm(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
96
96
  `),s=Number(t.offset??0),i=Number(t.limit??o.length);n=o.slice(s,s+i).join(`
97
- `)}return Buffer.byteLength(n,"utf-8")>Pf&&(n=$n(n,Pf,`
98
- ... [truncated]`)),n}},FS={name:"file_write",description:"Write content to a file. Creates parent directories if needed. Overwrites existing files.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},content:{type:"string",description:"Content to write",required:!0}},async execute(t,e){let r=ht(String(t.path??""),e),n=String(t.content??"");return ie(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},If={name:"file_list",description:"List files and directories at the given path.",parameters:{path:{type:"string",description:"Directory path relative to workspace (default: '.')"},recursive:{type:"boolean",description:"List recursively (default: false)"}},async execute(t,e){let r=Ft(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=ti)return;let u=zf(a);for(let l of u){if(o.length>=ti)break;let d=Cf(a,l),p=c?`${c}/${l}`:l;try{let f=ri(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=ti?`
99
- ... [truncated at ${ti} entries]`:"";return o.join(`
100
- `)+i}},Df={name:"grep_search",description:"Search file contents with a regex pattern. Returns matching lines with file paths and line numbers.",parameters:{pattern:{type:"string",description:"Regular expression pattern to search for",required:!0},path:{type:"string",description:"Directory or file path to search in (default: '.')"},glob:{type:"string",description:"Glob pattern to filter files (e.g., '*.ts')"}},async execute(t,e){let r=String(t.pattern??""),n=Ft(String(t.path??"."),e),o=t.glob?LS(String(t.glob)):null,s=ri(n).isDirectory(),i=ZS(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=jS(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=Rf(u,"utf-8")}catch{continue}let p=d.split(/\r?\n/);for(let f=0;f<p.length;f++)if(a.test(p[f])&&(c.push(`${l}:${f+1}:${p[f]}`),c.length>=Ef))return c.join(`
97
+ `)}return Buffer.byteLength(n,"utf-8")>$m&&(n=$n(n,$m,`
98
+ ... [truncated]`)),n}},C0={name:"file_write",description:"Write content to a file. Creates parent directories if needed. Overwrites existing files.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},content:{type:"string",description:"Content to write",required:!0}},async execute(t,e){let r=ht(String(t.path??""),e),n=String(t.content??"");return se(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},Im={name:"file_list",description:"List files and directories at the given path.",parameters:{path:{type:"string",description:"Directory path relative to workspace (default: '.')"},recursive:{type:"boolean",description:"List recursively (default: false)"}},async execute(t,e){let r=Bt(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=wi)return;let u=Tm(a);for(let l of u){if(o.length>=wi)break;let d=Em(a,l),p=c?`${c}/${l}`:l;try{let f=xi(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=wi?`
99
+ ... [truncated at ${wi} entries]`:"";return o.join(`
100
+ `)+i}},Am={name:"grep_search",description:"Search file contents with a regex pattern. Returns matching lines with file paths and line numbers.",parameters:{pattern:{type:"string",description:"Regular expression pattern to search for",required:!0},path:{type:"string",description:"Directory or file path to search in (default: '.')"},glob:{type:"string",description:"Glob pattern to filter files (e.g., '*.ts')"}},async execute(t,e){let r=String(t.pattern??""),n=Bt(String(t.path??"."),e),o=t.glob?R0(String(t.glob)):null,s=xi(n).isDirectory(),i=I0(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=E0(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=Pm(u,"utf-8")}catch{continue}let p=d.split(/\r?\n/);for(let f=0;f<p.length;f++)if(a.test(p[f])&&(c.push(`${l}:${f+1}:${p[f]}`),c.length>=km))return c.join(`
101
101
  `)+`
102
- ... [truncated at ${Ef} matches]`}return c.join(`
103
- `)||"No matches found."}catch{return"No matches found."}}},US={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...Us].join(", ")}). Shell operators (pipes, chaining, subshells) are blocked.`,parameters:{command:{type:"string",description:"Shell command to execute",required:!0}},async execute(t,e){let r=String(t.command??"").trim();if(!r)return"Error: empty command";let n=Kp(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=qS(s,i);try{let c=await De({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
102
+ ... [truncated at ${km} matches]`}return c.join(`
103
+ `)||"No matches found."}catch{return"No matches found."}}},D0={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...ci].join(", ")}). Shell operators (pipes, chaining, subshells) are blocked.`,parameters:{command:{type:"string",description:"Shell command to execute",required:!0}},async execute(t,e){let r=String(t.command??"").trim();if(!r)return"Error: empty command";let n=qf(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=A0(s,i);try{let c=await ze({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
104
104
  `:"")+`[stderr] ${c.stderr}`),c.exitCode!==0&&(u+=`
105
105
  [exit code: ${c.exitCode}]`),c.truncated&&(u+=`
106
- ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${q(c)}`}}};function $c(){return[Af,FS,If,Df,US]}function Sc(){return[Af,If,Df]}function kc(t){return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:e.parameters,required:Object.entries(e.parameters).filter(([,r])=>r.required===!0).map(([r])=>r)}}}))}var VS=15,WS=30,BS=3e5,HS=2e3,GS=`You are a coding assistant with access to tools for reading, writing, and searching files in a workspace. Use the provided tools when you need to inspect or modify code. When your task is complete, respond with your final answer without making any tool calls.
106
+ ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${M(c)}`}}};function iu(){return[Rm,C0,Im,Am,D0]}function Si(){return[Rm,Im,Am]}function au(t){return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:e.parameters,required:Object.entries(e.parameters).filter(([,r])=>r.required===!0).map(([r])=>r)}}}))}var z0=15,O0=30,M0=3e5,j0=2e3,N0=`You are a coding assistant with access to tools for reading, writing, and searching files in a workspace. Use the provided tools when you need to inspect or modify code. When your task is complete, respond with your final answer without making any tool calls.
107
107
 
108
108
  Guidelines:
109
109
  - Read files before modifying them to understand the existing code.
110
110
  - Use grep_search to find relevant code across the workspace.
111
111
  - Write complete file contents when using file_write (not just diffs).
112
- - Provide a clear summary of what you did when finished.`,ni=class{host;model;baseDir;maxIterations;timeoutMs;systemPrompt;tools;toolDefs;toolMap;constructor(e){this.host=e.providerHost.replace(/\/$/,""),this.model=e.model,this.baseDir=e.baseDir,this.maxIterations=Math.min(e.maxIterations??VS,WS),this.timeoutMs=e.timeoutMs??BS,this.systemPrompt=e.systemPrompt??GS,this.tools=e.tools??$c(),this.toolDefs=kc(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r]))}async run(e){let r=Date.now(),n=[],o="",s=[{role:"system",content:this.systemPrompt},{role:"user",content:e}];for(let i=0;i<this.maxIterations;i++){if(Date.now()-r>this.timeoutMs)return{success:!1,output:o||"Agent loop timed out before completion.",iterations:i,toolCalls:n,error:`Timed out after ${this.timeoutMs}ms`};let a;try{a=await this.callOllama(s)}catch(u){let l=q(u);return{success:!1,output:o||"",iterations:i,toolCalls:n,error:`Ollama API error: ${l}`}}let c=a.message;if(c.content&&(o=c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:o,iterations:i+1,toolCalls:n};s.push(c);for(let u of c.tool_calls){let l=u.function.name,d=u.function.arguments,p;if(typeof d=="string"){let m=Pn(d);p=m&&typeof m=="object"&&!Array.isArray(m)?m:{}}else p=d??{};let f=this.toolMap.get(l),g=Date.now(),y;if(!f)y=`Error: unknown tool '${l}'. Available tools: ${[...this.toolMap.keys()].join(", ")}`;else try{y=await f.execute(p,this.baseDir)}catch(m){y=`Error: ${q(m)}`}n.push({iteration:i,toolName:l,arguments:p,result:$n(y,HS,"... [truncated in log]"),durationMs:Date.now()-g}),s.push({role:"tool",content:y})}}return{success:!1,output:o||"Agent loop reached max iterations without completing.",iterations:this.maxIterations,toolCalls:n,error:`Max iterations (${this.maxIterations}) reached`}}async callOllama(e){let r=`${this.host}/api/chat`,n={model:this.model,messages:e,tools:this.toolDefs,stream:!1},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`HTTP ${i.status}: ${a.slice(0,200)}`)}return await i.json()}finally{clearTimeout(s)}}};function Of(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var vo=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(Ps(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Of(e);return o?{text:(await new ni({providerHost:o.host,model:o.model,baseDir:this.baseDir,tools:this.tools}).run(r.prompt)).output,model:o.model,provider:e.id}:e.chat(r)}};import{existsSync as xo,readFileSync as QS,readdirSync as YS}from"fs";import{join as En}from"path";var bo=class{baseDir;constructor(e){this.baseDir=e}async run(e={}){let r=e.timeoutMs??12e4,n=e.buildProfile??"auto",o=this.resolveProfile(n),s=e.designDoc??this.detectDesignDoc(),i=o?await this.runProfile(o,r):{exitCode:0,output:"(no build profile resolved)"},a=i.exitCode===0,c=i.output,u=[];o?u.push(`${o.name}: ${a?"PASS":"FAIL"}`):u.push("No profile resolved"),s&&u.push(`Design doc: ${s}`);let d=`**AutoQA: ${a?"PASS":"FAIL"}**
112
+ - Provide a clear summary of what you did when finished.`,$i=class{host;model;baseDir;maxIterations;timeoutMs;systemPrompt;tools;toolDefs;toolMap;constructor(e){this.host=e.providerHost.replace(/\/$/,""),this.model=e.model,this.baseDir=e.baseDir,this.maxIterations=Math.min(e.maxIterations??z0,O0),this.timeoutMs=e.timeoutMs??M0,this.systemPrompt=e.systemPrompt??N0,this.tools=e.tools??iu(),this.toolDefs=au(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r]))}async run(e){let r=Date.now(),n=[],o="",s=[{role:"system",content:this.systemPrompt},{role:"user",content:e}];for(let i=0;i<this.maxIterations;i++){if(Date.now()-r>this.timeoutMs)return{success:!1,output:o||"Agent loop timed out before completion.",iterations:i,toolCalls:n,error:`Timed out after ${this.timeoutMs}ms`};let a;try{a=await this.callOllama(s)}catch(u){let l=M(u);return{success:!1,output:o||"",iterations:i,toolCalls:n,error:`Ollama API error: ${l}`}}let c=a.message;if(c.content&&(o=c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:o,iterations:i+1,toolCalls:n};s.push(c);for(let u of c.tool_calls){let l=u.function.name,d=u.function.arguments,p;if(typeof d=="string"){let y=En(d);p=y&&typeof y=="object"&&!Array.isArray(y)?y:{}}else p=d??{};let f=this.toolMap.get(l),m=Date.now(),g;if(!f)g=`Error: unknown tool '${l}'. Available tools: ${[...this.toolMap.keys()].join(", ")}`;else try{g=await f.execute(p,this.baseDir)}catch(y){g=`Error: ${M(y)}`}n.push({iteration:i,toolName:l,arguments:p,result:$n(g,j0,"... [truncated in log]"),durationMs:Date.now()-m}),s.push({role:"tool",content:g})}}return{success:!1,output:o||"Agent loop reached max iterations without completing.",iterations:this.maxIterations,toolCalls:n,error:`Max iterations (${this.maxIterations}) reached`}}async callOllama(e){let r=`${this.host}/api/chat`,n={model:this.model,messages:e,tools:this.toolDefs,stream:!1},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`HTTP ${i.status}: ${a.slice(0,200)}`)}return await i.json()}finally{clearTimeout(s)}}};function Cm(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var Rn=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(Bs(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Cm(e);return o?{text:(await new $i({providerHost:o.host,model:o.model,baseDir:this.baseDir,tools:this.tools}).run(r.prompt)).output,model:o.model,provider:e.id}:e.chat(r)}};import{existsSync as Ro,readFileSync as Z0,readdirSync as U0}from"fs";import{join as In}from"path";var Io=class{baseDir;constructor(e){this.baseDir=e}async run(e={}){let r=e.timeoutMs??12e4,n=e.buildProfile??"auto",o=this.resolveProfile(n),s=e.designDoc??this.detectDesignDoc(),i=o?await this.runProfile(o,r):{exitCode:0,output:"(no build profile resolved)"},a=i.exitCode===0,c=i.output,u=[];o?u.push(`${o.name}: ${a?"PASS":"FAIL"}`):u.push("No profile resolved"),s&&u.push(`Design doc: ${s}`);let d=`**AutoQA: ${a?"PASS":"FAIL"}**
113
113
  ${u.join(`
114
- `)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=ln[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(xo(En(this.baseDir,"tsconfig.json")))return ln.tsc;if(xo(En(this.baseDir,"vitest.config.ts"))||xo(En(this.baseDir,"vitest.config.js")))return ln.vitest;let e=this.getPackageScripts();return e?.build?ln["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?ln["npm-test"]:null}detectDesignDoc(){let e=En(this.baseDir,"docs","plans");if(!xo(e))return null;try{let r=YS(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return En("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=En(this.baseDir,"package.json");if(!xo(e))return null;try{return JSON.parse(QS(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{Zs(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof et?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await De({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),o=n.exitCode===0?n.stdout:`${n.stdout}
114
+ `)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=dn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(Ro(In(this.baseDir,"tsconfig.json")))return dn.tsc;if(Ro(In(this.baseDir,"vitest.config.ts"))||Ro(In(this.baseDir,"vitest.config.js")))return dn.vitest;let e=this.getPackageScripts();return e?.build?dn["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?dn["npm-test"]:null}detectDesignDoc(){let e=In(this.baseDir,"docs","plans");if(!Ro(e))return null;try{let r=U0(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return In("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=In(this.baseDir,"package.json");if(!Ro(e))return null;try{return JSON.parse(Z0(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{si(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof tt?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await ze({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),o=n.exitCode===0?n.stdout:`${n.stdout}
115
115
  ${n.stderr}`.trim(),s=$n(o,1e4,`
116
- ... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var XS=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),e0=/[\w./\\]+\.[a-z]{1,4}/gi,t0=/\b\d+\.?\d*\b/g,r0=/`[^`\n]+`/g,n0=/https?:\/\/\S+/g,o0=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function oi(t){return Math.max(0,Math.min(1,t))}function Ut(t,e){return t.match(e)?.length??0}function s0(t){let r=t.split(/[.!?]+|\n+(?=\S)/g).map(n=>n.trim()).filter(n=>n.length>0);return r.length>0?r:t.trim().length>0?[t.trim()]:[]}function i0(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return XS.has(e)?!0:e.replace(/\s+/g,"").length<5}function a0(t){let e=s0(t);if(e.length===0)return .1;let r=e.filter(i0).length,n=(e.length-r)/e.length;return Math.max(.1,oi(n))}function c0(t){let e=Ut(t,/^\s*#\s+/gm),r=Ut(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Ut(t,/^\s*```/gm)/2),o=Ut(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return oi(s/3)}function u0(t){let e=Ut(t,e0)+Ut(t,t0)+Ut(t,r0)+Ut(t,n0)+Ut(t,o0);return oi(e/3)}function Mf(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function l0(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Mf(i.content))r.add(a);if(r.size===0)return 0;let n=Mf(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return oi(o/s)}function wo(t,e,r){let n={substanceRatio:a0(t),structureScore:c0(t),specificityScore:u0(t),engagementScore:l0(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Nf,readFileSync as jf,readdirSync as Rc,existsSync as Vr,statSync as d0,unlinkSync as p0}from"fs";import{join as Tc}from"path";import{randomUUID as f0}from"crypto";function si(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function Pc(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}${r}${n}`}function Ec(t,e){if(!Vr(t))return"001";let r=Rc(t).filter(o=>o.includes(`_${e}_`)),n=0;for(let o of r){let s=o.match(new RegExp(`_${e}_(\\d{3})\\.md$`));if(s){let i=parseInt(s[1],10);i>n&&(n=i)}}return String(n+1).padStart(3,"0")}var $o=class{baseDir;reviewDir;debateDir;constructor(e){this.baseDir=e,this.reviewDir=Tc(e,"reviews"),this.debateDir=Tc(e,"debates"),Nf(this.reviewDir,{recursive:!0}),Nf(this.debateDir,{recursive:!0})}async createReview(e){let r=Pc(),n=e.topic?si(e.topic):f0().slice(0,8),o=Ec(this.reviewDir,r),s=e.provider?`${e.provider}_${n}_${r}_${o}`:`${n}_${r}_${o}`,i=Me(`${s}.md`,this.reviewDir),a=`# Review: ${e.topic??s}
116
+ ... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var q0=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),V0=/[\w./\\]+\.[a-z]{1,4}/gi,B0=/\b\d+\.?\d*\b/g,W0=/`[^`\n]+`/g,H0=/https?:\/\/\S+/g,K0=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function ki(t){return Math.max(0,Math.min(1,t))}function Wt(t,e){return t.match(e)?.length??0}function J0(t){let r=t.split(/[.!?]+|\n+(?=\S)/g).map(n=>n.trim()).filter(n=>n.length>0);return r.length>0?r:t.trim().length>0?[t.trim()]:[]}function G0(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return q0.has(e)?!0:e.replace(/\s+/g,"").length<5}function Y0(t){let e=J0(t);if(e.length===0)return .1;let r=e.filter(G0).length,n=(e.length-r)/e.length;return Math.max(.1,ki(n))}function Q0(t){let e=Wt(t,/^\s*#\s+/gm),r=Wt(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Wt(t,/^\s*```/gm)/2),o=Wt(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return ki(s/3)}function X0(t){let e=Wt(t,V0)+Wt(t,B0)+Wt(t,W0)+Wt(t,H0)+Wt(t,K0);return ki(e/3)}function Dm(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function eP(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Dm(i.content))r.add(a);if(r.size===0)return 0;let n=Dm(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return ki(o/s)}function Ao(t,e,r){let n={substanceRatio:Y0(t),structureScore:Q0(t),specificityScore:X0(t),engagementScore:eP(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Pi,readFileSync as zm,readdirSync as cu,existsSync as Do,statSync as rP,unlinkSync as nP}from"fs";import{basename as Om,join as Co,relative as Mm,sep as jm}from"path";import{randomUUID as oP}from"crypto";var sP="reviews";function An(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function iP(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function Cn(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}${r}${n}`}function Dn(t,e){if(!Do(t))return"001";let r=cu(t).filter(o=>o.includes(`_${e}_`)),n=0;for(let o of r){let s=o.match(new RegExp(`_${e}_(\\d{3})\\.md$`));if(s){let i=parseInt(s[1],10);i>n&&(n=i)}}return String(n+1).padStart(3,"0")}function Nm(t){return jm==="/"?t:t.split(jm).join("/")}var zo=class{baseDir;reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.baseDir=e,this.reviewDir=Co(e,sP),this.individualDir=Co(e,rf),this.debateDir=Co(e,Us),this.synthesisDir=Co(e,nf),Pi(this.reviewDir,{recursive:!0}),Pi(this.individualDir,{recursive:!0}),Pi(this.debateDir,{recursive:!0}),Pi(this.synthesisDir,{recursive:!0})}get allDirs(){return[this.individualDir,this.debateDir,this.synthesisDir,this.reviewDir]}resolveDocPath(e){let r;for(let n of this.allDirs)try{let o=Me(`${e}.md`,n);if(Do(o))return o}catch(o){r===void 0&&(r=o)}throw r!==void 0?r:new Error(`Document not found: ${e}`)}async createReview(e){let r=Cn(),n=e.topic?An(e.topic):oP().slice(0,8),o=Dn(this.reviewDir,r),s=e.provider?`${e.provider}_${n}_${r}_${o}`:`${n}_${r}_${o}`,i=Me(`${s}.md`,this.reviewDir),a=`# Review: ${e.topic??s}
117
117
 
118
118
  `;a+=`**Date:** ${new Date().toISOString().slice(0,10)}
119
119
  `,e.provider&&(a+=`**Provider:** ${e.provider}
@@ -128,7 +128,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
128
128
  `}return a+=`
129
129
  ---
130
130
 
131
- `,ie(i,a),{id:s,content:a,path:i}}async createDebateDocument(e){let r=Pc(),n=si(e.topic),o=Ec(this.debateDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.debateDir),a=`# Debate: ${e.topic}
131
+ `,se(i,a),{id:s,content:a,path:i}}async createDebateDocument(e){let r=Cn(),n=An(e.topic),o=Dn(this.debateDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.debateDir),a=`# Debate: ${e.topic}
132
132
 
133
133
  `;return a+=`**Date:** ${new Date().toISOString().slice(0,10)}
134
134
  `,a+=`**Participants:** ${e.providers.join(", ")}
@@ -136,74 +136,128 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
136
136
  `),a+=`
137
137
  ---
138
138
 
139
- `,ie(i,a),{id:s,content:a,path:i}}async addComment(e,r){let n=Me(`${e}.md`,this.reviewDir),o=Me(`${e}.md`,this.debateDir),s;if(Vr(n))s=n;else if(Vr(o))s=o;else throw new Error(`Document not found: ${e}`);let i=`
139
+ `,se(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=Cn(),n=iP(e.participantId),o=An(e.topic),s=Dn(this.individualDir,r),i=`${n}_${o}_${r}_${s}`,a=Me(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
140
+
141
+ `;if(c+=`**Date:** ${new Date().toISOString().slice(0,10)}
142
+ `,c+=`**Participant:** ${e.participantId}
143
+ `,e.metadata)for(let[u,l]of Object.entries(e.metadata))c+=`**${u}:** ${l}
144
+ `;if(e.files&&e.files.length>0){c+=`
145
+ ## Files examined
146
+
147
+ `;for(let u of e.files)c+=`- ${u}
148
+ `}return c+=`
149
+ ## Findings
150
+
151
+ `,c+=e.content,c+=`
152
+
153
+ ---
154
+ `,se(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=Cn(),n=e.sessionId.slice(0,8),o=Dn(this.individualDir,r),s=`${of}_${n}_${r}_${o}`,i=Me(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
155
+
156
+ `;if(a+=`**Session:** ${e.sessionId}
157
+ `,a+=`**Rejected at:** ${new Date().toISOString()}
158
+ `,a+=`**Reason:** ${e.reason??"\u2014"}
159
+ `,a+=`
160
+ ## Proposals not accepted
161
+
162
+ `,e.items.length===0)a+=`(none)
163
+ `;else for(let c of e.items){a+=`### ${c.title} (severity: ${c.severity})
164
+
165
+ `,a+=`- Status: ${c.status}
166
+ `;let u=c.proposerIds.length>0?c.proposerIds.join(", "):"\u2014";if(a+=`- Proposers: ${u}
167
+ `,a+=`- Location: ${c.location??"\u2014"}
168
+ `,a+=`- Description: ${c.description??"\u2014"}
169
+ `,c.votes){let l=c.votes;a+=`- Last tally: agree ${l.agree}/${l.total}, disagree ${l.disagree}, abstain ${l.abstain}, revise ${l.revise}
170
+ `}a+=`
171
+ `}return a+=`
172
+ ---
173
+ `,se(i,a),{id:s,content:a,path:i}}async createSynthesis(e){let r=Cn(),n=An(e.topic),o=Dn(this.synthesisDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.synthesisDir),a=Nm(Mm(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>Nm(Mm(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
174
+
175
+ `;if(u+=`**Date:** ${new Date().toISOString().slice(0,10)}
176
+ `,u+=`**Status:** ${e.status}
177
+ `,u+=`**Rounds:** ${e.rounds}/${e.maxRounds}
178
+ `,u+=`**Participants:** ${e.participantIds.join(", ")}
179
+ `,u+=`**Session:** ${e.sessionId}
180
+ `,e.metadata)for(let[l,d]of Object.entries(e.metadata))u+=`**${l}:** ${d}
181
+ `;if(u+=`
182
+ ## Sources
183
+
184
+ `,u+=`- Debate transcript: [${Om(e.debatePath)}](${a})
185
+ `,e.individualPaths.length>0){u+=`- Individual reviews:
186
+ `;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${Om(d)}](${c[l]})
187
+ `}}return u+=`
188
+ ---
189
+
190
+ `,u+=e.body,u+=`
191
+
192
+ ---
193
+ `,se(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Me(`${e}.md`,this.synthesisDir);if(!Do(n))throw new Error(`Synthesis document not found: ${e}`);ri(n,`
194
+ ${r}
195
+ `)}async addComment(e,r){let n=this.resolveDocPath(e),o=`
140
196
  ## Comment by ${r.author}
141
197
 
142
198
  ${r.content}
143
199
 
144
200
  ---
145
- `;co(s,i)}async read(e){let r=Me(`${e}.md`,this.reviewDir),n=Me(`${e}.md`,this.debateDir),o;if(Vr(r))o=r;else if(Vr(n))o=n;else throw new Error(`Document not found: ${e}`);let s=jf(o,"utf-8");return{id:e,content:s,path:o}}async createDocument(e){let r=Pc(),n=e.topic?si(e.topic):si(e.title),o=Ec(this.reviewDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.reviewDir),a=`# ${e.title}
201
+ `;ri(n,o)}async read(e){let r=this.resolveDocPath(e),n=zm(r,"utf-8");return{id:e,content:n,path:r}}async createDocument(e){let r=Cn(),n=e.topic?An(e.topic):An(e.title),o=Dn(this.reviewDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.reviewDir),a=`# ${e.title}
146
202
 
147
203
  `;if(e.metadata){for(let[c,u]of Object.entries(e.metadata))a+=`**${c}:** ${u}
148
204
  `;a+=`
149
205
  `}return a+=e.content,a+=`
150
206
 
151
207
  ---
152
- `,ie(i,a),{id:s,content:a,path:i}}async list(){let e=[];for(let r of[this.reviewDir,this.debateDir]){if(!Vr(r))continue;let n=Rc(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Me(o,r),a=jf(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of[this.reviewDir,this.debateDir]){if(!Vr(a))continue;let c=Rc(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Tc(a,u),d=d0(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=o-c[u].mtime;if(u>=n||l>s)try{p0(c[u].path),i++}catch{}}}return{removed:i}}};import{readFileSync as m0,existsSync as h0,mkdirSync as g0}from"fs";var y0=256,_0=1e3,So=class{cache=new Map;dir;maxSessions;maxMessagesPerSession;constructor(e,r){this.dir=e,this.maxSessions=r?.maxSessions??y0,this.maxMessagesPerSession=r?.maxMessagesPerSession??_0,g0(e,{recursive:!0})}send(e,r){let n={...r,timestamp:r.timestamp||new Date().toISOString()};this.touchSession(e),this.cache.has(e)||this.cache.set(e,[]);let o=this.cache.get(e);if(o.push(n),o.length>this.maxMessagesPerSession){let i=o.length-this.maxMessagesPerSession;o.splice(0,i)}let s=Me(`${e}.jsonl`,this.dir);co(s,JSON.stringify(n)+`
153
- `),this.evictIfNeeded()}receive(e){return this.cache.has(e)?(this.touchSession(e),[...this.cache.get(e)]):this.recover(e)}recover(e){let r;try{r=Me(`${e}.jsonl`,this.dir)}catch{return[]}if(!h0(r))return[];let o=m0(r,"utf-8").split(`
154
- `).filter(c=>c.trim()),s=[],i=0;for(let c of o)try{s.push(JSON.parse(c))}catch{i++}i>0&&console.warn(`[message-queue] Skipped ${i} corrupted line(s) in session ${e}`);let a=s.length>this.maxMessagesPerSession?s.slice(-this.maxMessagesPerSession):s;return this.touchSession(e),this.cache.set(e,a),this.evictIfNeeded(),[...a]}touchSession(e){if(this.cache.has(e)){let r=this.cache.get(e);this.cache.delete(e),this.cache.set(e,r)}}evictIfNeeded(){for(;this.cache.size>this.maxSessions;){let e=this.cache.keys().next().value;this.cache.delete(e)}}};var Aj=Object.freeze({status:"aborted"});function x(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Vt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ii={};function at(t){return t&&Object.assign(ii,t),ii}var se={};We(se,{BIGINT_FORMAT_RANGES:()=>Zf,Class:()=>Cc,NUMBER_FORMAT_RANGES:()=>Lc,aborted:()=>Br,allowsEval:()=>Mc,assert:()=>$0,assertEqual:()=>v0,assertIs:()=>b0,assertNever:()=>w0,assertNotEqual:()=>x0,assignProp:()=>Oc,cached:()=>To,captureStackTrace:()=>ci,cleanEnum:()=>M0,cleanRegex:()=>Eo,clone:()=>Rt,createTransparentProxy:()=>R0,defineLazy:()=>de,esc:()=>Wr,escapeRegex:()=>ir,extend:()=>A0,finalizeIssue:()=>gt,floatSafeRemainder:()=>Dc,getElementAtPath:()=>S0,getEnumValues:()=>Ac,getLengthableOrigin:()=>Ro,getParsedType:()=>E0,getSizableOrigin:()=>qf,isObject:()=>Rn,isPlainObject:()=>zn,issue:()=>Zc,joinValues:()=>ai,jsonStringifyReplacer:()=>Ic,merge:()=>I0,normalizeParams:()=>O,nullish:()=>Po,numKeys:()=>P0,omit:()=>C0,optionalKeys:()=>jc,partial:()=>D0,pick:()=>z0,prefixIssues:()=>zt,primitiveTypes:()=>Lf,promiseAllObject:()=>k0,propertyKeyTypes:()=>Nc,randomString:()=>T0,required:()=>O0,stringifyPrimitive:()=>ui,unwrapMessage:()=>ko});function v0(t){return t}function x0(t){return t}function b0(t){}function w0(t){throw new Error}function $0(t){}function Ac(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function ai(t,e="|"){return t.map(r=>ui(r)).join(e)}function Ic(t,e){return typeof e=="bigint"?e.toString():e}function To(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Po(t){return t==null}function Eo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Dc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function de(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Oc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function S0(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function k0(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function T0(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Wr(t){return JSON.stringify(t)}var ci=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Rn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Mc=To(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function zn(t){if(Rn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Rn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function P0(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var E0=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Nc=new Set(["string","number","symbol"]),Lf=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ir(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function O(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function R0(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function ui(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function jc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Lc={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]},Zf={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function z0(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Rt(t,{...t._zod.def,shape:r,checks:[]})}function C0(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Rt(t,{...t._zod.def,shape:r,checks:[]})}function A0(t,e){if(!zn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Oc(this,"shape",n),n},checks:[]};return Rt(t,r)}function I0(t,e){return Rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Oc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function D0(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Rt(e,{...e._zod.def,shape:o,checks:[]})}function O0(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Rt(e,{...e._zod.def,shape:o,checks:[]})}function Br(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function zt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ko(t){return typeof t=="string"?t:t?.message}function gt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=ko(t.inst?._zod.def?.error?.(t))??ko(e?.error?.(t))??ko(r.customError?.(t))??ko(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function qf(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ro(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Zc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function M0(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Cc=class{constructor(...e){}};var Ff=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Ic,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},li=x("$ZodError",Ff),qc=x("$ZodError",Ff,{Parent:Error});function Uf(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Vf(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Wf=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Vt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw ci(a,o?.callee),a}return i.value};var Bf=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw ci(a,o?.callee),a}return i.value};var Fc=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Vt;return s.issues.length?{success:!1,error:new(t??li)(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},zo=Fc(qc),Uc=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},di=Uc(qc);var Hf=/^[cC][^\s-]{8,}$/,Gf=/^[0-9a-z]+$/,Jf=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Kf=/^[0-9a-vA-V]{20}$/,Qf=/^[A-Za-z0-9]{27}$/,Yf=/^[a-zA-Z0-9_-]{21}$/,Xf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var em=/^([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})$/,Vc=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/;var tm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var j0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rm(){return new RegExp(j0,"u")}var nm=/^(?:(?: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])$/,om=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,sm=/^((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])$/,im=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,am=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wc=/^[A-Za-z0-9_-]*$/,cm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var um=/^\+(?:[0-9]){6,14}[0-9]$/,lm="(?:(?:\\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])))",dm=new RegExp(`^${lm}$`);function pm(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fm(t){return new RegExp(`^${pm(t)}$`)}function mm(t){let e=pm({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${lm}T(?:${n})$`)}var hm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var gm=/^\d+$/,ym=/^-?\d+(?:\.\d+)?/i,_m=/true|false/i,vm=/null/i;var xm=/^[^A-Z]*$/,bm=/^[^a-z]*$/;var Ne=x("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),wm={number:"number",bigint:"bigint",object:"date"},Hc=x("$ZodCheckLessThan",(t,e)=>{Ne.init(t,e);let r=wm[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Gc=x("$ZodCheckGreaterThan",(t,e)=>{Ne.init(t,e);let r=wm[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),$m=x("$ZodCheckMultipleOf",(t,e)=>{Ne.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Dc(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Sm=x("$ZodCheckNumberFormat",(t,e)=>{Ne.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Lc[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=gm)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var km=x("$ZodCheckMaxLength",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Ro(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Tm=x("$ZodCheckMinLength",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ro(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Pm=x("$ZodCheckLengthEquals",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ro(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Co=x("$ZodCheckStringFormat",(t,e)=>{var r,n;Ne.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Em=x("$ZodCheckRegex",(t,e)=>{Co.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Rm=x("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=xm),Co.init(t,e)}),zm=x("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=bm),Co.init(t,e)}),Cm=x("$ZodCheckIncludes",(t,e)=>{Ne.init(t,e);let r=ir(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Am=x("$ZodCheckStartsWith",(t,e)=>{Ne.init(t,e);let r=new RegExp(`^${ir(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Im=x("$ZodCheckEndsWith",(t,e)=>{Ne.init(t,e);let r=new RegExp(`.*${ir(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Dm=x("$ZodCheckOverwrite",(t,e)=>{Ne.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var pi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
208
+ `,se(i,a),{id:s,content:a,path:i}}async list(){let e=[];for(let r of this.allDirs){if(!Do(r))continue;let n=cu(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Me(o,r),a=zm(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!Do(a))continue;let c=cu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Co(a,u),d=rP(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=o-c[u].mtime;if(u>=n||l>s)try{nP(c[u].path),i++}catch{}}}return{removed:i}}};var dZ=Object.freeze({status:"aborted"});function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ht=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ti={};function at(t){return t&&Object.assign(Ti,t),Ti}var ie={};Ze(ie,{BIGINT_FORMAT_RANGES:()=>Fm,Class:()=>lu,NUMBER_FORMAT_RANGES:()=>vu,aborted:()=>Kr,allowsEval:()=>hu,assert:()=>dP,assertEqual:()=>aP,assertIs:()=>uP,assertNever:()=>lP,assertNotEqual:()=>cP,assignProp:()=>mu,cached:()=>Mo,captureStackTrace:()=>Ri,cleanEnum:()=>$P,cleanRegex:()=>No,clone:()=>It,createTransparentProxy:()=>yP,defineLazy:()=>de,esc:()=>Hr,escapeRegex:()=>ur,extend:()=>bP,finalizeIssue:()=>gt,floatSafeRemainder:()=>fu,getElementAtPath:()=>pP,getEnumValues:()=>du,getLengthableOrigin:()=>Lo,getParsedType:()=>gP,getSizableOrigin:()=>Zm,isObject:()=>zn,isPlainObject:()=>On,issue:()=>_u,joinValues:()=>Ei,jsonStringifyReplacer:()=>pu,merge:()=>wP,normalizeParams:()=>N,nullish:()=>jo,numKeys:()=>hP,omit:()=>_P,optionalKeys:()=>yu,partial:()=>xP,pick:()=>vP,prefixIssues:()=>At,primitiveTypes:()=>Lm,promiseAllObject:()=>fP,propertyKeyTypes:()=>gu,randomString:()=>mP,required:()=>SP,stringifyPrimitive:()=>Ii,unwrapMessage:()=>Oo});function aP(t){return t}function cP(t){return t}function uP(t){}function lP(t){throw new Error}function dP(t){}function du(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ei(t,e="|"){return t.map(r=>Ii(r)).join(e)}function pu(t,e){return typeof e=="bigint"?e.toString():e}function Mo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function jo(t){return t==null}function No(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function de(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function mu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function pP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function fP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function mP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Hr(t){return JSON.stringify(t)}var Ri=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hu=Mo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function On(t){if(zn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(zn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function hP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var gP=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},gu=new Set(["string","number","symbol"]),Lm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ur(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function It(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function N(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function yP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ii(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function yu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var vu={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]},Fm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return It(t,{...t._zod.def,shape:r,checks:[]})}function _P(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return It(t,{...t._zod.def,shape:r,checks:[]})}function bP(t,e){if(!On(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return mu(this,"shape",n),n},checks:[]};return It(t,r)}function wP(t,e){return It(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return mu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function xP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return It(e,{...e._zod.def,shape:o,checks:[]})}function SP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return It(e,{...e._zod.def,shape:o,checks:[]})}function Kr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function At(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Oo(t){return typeof t=="string"?t:t?.message}function gt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Oo(t.inst?._zod.def?.error?.(t))??Oo(e?.error?.(t))??Oo(r.customError?.(t))??Oo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Zm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Lo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _u(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function $P(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var lu=class{constructor(...e){}};var Um=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,pu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ai=w("$ZodError",Um),bu=w("$ZodError",Um,{Parent:Error});function qm(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Vm(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Bm=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ht;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw Ri(a,o?.callee),a}return i.value};var Wm=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw Ri(a,o?.callee),a}return i.value};var wu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ht;return s.issues.length?{success:!1,error:new(t??Ai)(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Fo=wu(bu),xu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Ci=xu(bu);var Hm=/^[cC][^\s-]{8,}$/,Km=/^[0-9a-z]+$/,Jm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gm=/^[0-9a-vA-V]{20}$/,Ym=/^[A-Za-z0-9]{27}$/,Qm=/^[a-zA-Z0-9_-]{21}$/,Xm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var eh=/^([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})$/,Su=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/;var th=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var PP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rh(){return new RegExp(PP,"u")}var nh=/^(?:(?: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])$/,oh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,sh=/^((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])$/,ih=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ah=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$u=/^[A-Za-z0-9_-]*$/,ch=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var uh=/^\+(?:[0-9]){6,14}[0-9]$/,lh="(?:(?:\\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])))",dh=new RegExp(`^${lh}$`);function ph(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fh(t){return new RegExp(`^${ph(t)}$`)}function mh(t){let e=ph({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${lh}T(?:${n})$`)}var hh=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var gh=/^\d+$/,yh=/^-?\d+(?:\.\d+)?/i,vh=/true|false/i,_h=/null/i;var bh=/^[^A-Z]*$/,wh=/^[^a-z]*$/;var je=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),xh={number:"number",bigint:"bigint",object:"date"},Pu=w("$ZodCheckLessThan",(t,e)=>{je.init(t,e);let r=xh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Tu=w("$ZodCheckGreaterThan",(t,e)=>{je.init(t,e);let r=xh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Sh=w("$ZodCheckMultipleOf",(t,e)=>{je.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):fu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),$h=w("$ZodCheckNumberFormat",(t,e)=>{je.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=vu[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=gh)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var kh=w("$ZodCheckMaxLength",(t,e)=>{var r;je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Lo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ph=w("$ZodCheckMinLength",(t,e)=>{var r;je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Lo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Th=w("$ZodCheckLengthEquals",(t,e)=>{var r;je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Lo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Zo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;je.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Eh=w("$ZodCheckRegex",(t,e)=>{Zo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Rh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=bh),Zo.init(t,e)}),Ih=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=wh),Zo.init(t,e)}),Ah=w("$ZodCheckIncludes",(t,e)=>{je.init(t,e);let r=ur(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Ch=w("$ZodCheckStartsWith",(t,e)=>{je.init(t,e);let r=new RegExp(`^${ur(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Dh=w("$ZodCheckEndsWith",(t,e)=>{je.init(t,e);let r=new RegExp(`.*${ur(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var zh=w("$ZodCheckOverwrite",(t,e)=>{je.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Di=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
155
209
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
156
- `))}};var Mm={major:4,minor:0,patch:0};var pe=x("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Mm;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Br(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Vt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Br(s,d)))});else{if(s.issues.length===d)continue;c||(c=Br(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Vt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=zo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return di(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),mi=x("$ZodString",(t,e)=>{pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??hm(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),he=x("$ZodStringFormat",(t,e)=>{Co.init(t,e),mi.init(t,e)}),Bm=x("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=em),he.init(t,e)}),Hm=x("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Vc(n))}else e.pattern??(e.pattern=Vc());he.init(t,e)}),Gm=x("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=tm),he.init(t,e)}),Jm=x("$ZodURL",(t,e)=>{he.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:cm.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Km=x("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=rm()),he.init(t,e)}),Qm=x("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Yf),he.init(t,e)}),Ym=x("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hf),he.init(t,e)}),Xm=x("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Gf),he.init(t,e)}),eh=x("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Jf),he.init(t,e)}),th=x("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Kf),he.init(t,e)}),rh=x("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Qf),he.init(t,e)}),nh=x("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=mm(e)),he.init(t,e)}),oh=x("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=dm),he.init(t,e)}),sh=x("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=fm(e)),he.init(t,e)}),ih=x("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Xf),he.init(t,e)}),ah=x("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=nm),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ch=x("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=om),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),uh=x("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=sm),he.init(t,e)}),lh=x("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=im),he.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function dh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var ph=x("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=am),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{dh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function L0(t){if(!Wc.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return dh(r)}var fh=x("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Wc),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{L0(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),mh=x("$ZodE164",(t,e)=>{e.pattern??(e.pattern=um),he.init(t,e)});function Z0(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var hh=x("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{Z0(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Kc=x("$ZodNumber",(t,e)=>{pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??ym,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),gh=x("$ZodNumber",(t,e)=>{Sm.init(t,e),Kc.init(t,e)}),yh=x("$ZodBoolean",(t,e)=>{pe.init(t,e),t._zod.pattern=_m,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var _h=x("$ZodNull",(t,e)=>{pe.init(t,e),t._zod.pattern=vm,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var vh=x("$ZodUnknown",(t,e)=>{pe.init(t,e),t._zod.parse=r=>r}),xh=x("$ZodNever",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Nm(t,e,r){t.issues.length&&e.issues.push(...zt(r,t.issues)),e.value[r]=t.value}var bh=x("$ZodArray",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Nm(u,r,i))):Nm(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function fi(t,e,r){t.issues.length&&e.issues.push(...zt(r,t.issues)),e.value[r]=t.value}function jm(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...zt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var wh=x("$ZodObject",(t,e)=>{pe.init(t,e);let r=To(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof pe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=jc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});de(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let g=d[f]._zod;if(g.values){p[f]??(p[f]=new Set);for(let y of g.values)p[f].add(y)}}return p});let n=d=>{let p=new pi(["shape","payload","ctx"]),f=r.value,g=_=>{let w=Wr(_);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),m=0;for(let _ of f.keys)y[_]=`key_${m++}`;p.write("const newResult = {}");for(let _ of f.keys)if(f.optionalKeys.has(_)){let w=y[_];p.write(`const ${w} = ${g(_)};`);let k=Wr(_);p.write(`
157
- if (${w}.issues.length) {
210
+ `))}};var Mh={major:4,minor:0,patch:0};var pe=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Mh;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Kr(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Ht;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Kr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Kr(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Ht;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Fo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ci(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Oi=w("$ZodString",(t,e)=>{pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??hh(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),he=w("$ZodStringFormat",(t,e)=>{Zo.init(t,e),Oi.init(t,e)}),Wh=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=eh),he.init(t,e)}),Hh=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Su(n))}else e.pattern??(e.pattern=Su());he.init(t,e)}),Kh=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=th),he.init(t,e)}),Jh=w("$ZodURL",(t,e)=>{he.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ch.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Gh=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=rh()),he.init(t,e)}),Yh=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Qm),he.init(t,e)}),Qh=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hm),he.init(t,e)}),Xh=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Km),he.init(t,e)}),eg=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Jm),he.init(t,e)}),tg=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Gm),he.init(t,e)}),rg=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ym),he.init(t,e)}),ng=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=mh(e)),he.init(t,e)}),og=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=dh),he.init(t,e)}),sg=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=fh(e)),he.init(t,e)}),ig=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Xm),he.init(t,e)}),ag=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=nh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),cg=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=oh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),ug=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=sh),he.init(t,e)}),lg=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ih),he.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function dg(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var pg=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ah),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{dg(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function TP(t){if(!$u.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return dg(r)}var fg=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=$u),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{TP(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),mg=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=uh),he.init(t,e)});function EP(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var hg=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{EP(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Ru=w("$ZodNumber",(t,e)=>{pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??yh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),gg=w("$ZodNumber",(t,e)=>{$h.init(t,e),Ru.init(t,e)}),yg=w("$ZodBoolean",(t,e)=>{pe.init(t,e),t._zod.pattern=vh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var vg=w("$ZodNull",(t,e)=>{pe.init(t,e),t._zod.pattern=_h,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var _g=w("$ZodUnknown",(t,e)=>{pe.init(t,e),t._zod.parse=r=>r}),bg=w("$ZodNever",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function jh(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}var wg=w("$ZodArray",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>jh(u,r,i))):jh(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function zi(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}function Nh(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...At(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var xg=w("$ZodObject",(t,e)=>{pe.init(t,e);let r=Mo(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof pe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=yu(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});de(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let g of m.values)p[f].add(g)}}return p});let n=d=>{let p=new Di(["shape","payload","ctx"]),f=r.value,m=S=>{let v=Hr(S);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let S of f.keys)g[S]=`key_${y++}`;p.write("const newResult = {}");for(let S of f.keys)if(f.optionalKeys.has(S)){let v=g[S];p.write(`const ${v} = ${m(S)};`);let k=Hr(S);p.write(`
211
+ if (${v}.issues.length) {
158
212
  if (input[${k}] === undefined) {
159
213
  if (${k} in input) {
160
214
  newResult[${k}] = undefined;
161
215
  }
162
216
  } else {
163
217
  payload.issues = payload.issues.concat(
164
- ${w}.issues.map((iss) => ({
218
+ ${v}.issues.map((iss) => ({
165
219
  ...iss,
166
220
  path: iss.path ? [${k}, ...iss.path] : [${k}],
167
221
  }))
168
222
  );
169
223
  }
170
- } else if (${w}.value === undefined) {
224
+ } else if (${v}.value === undefined) {
171
225
  if (${k} in input) newResult[${k}] = undefined;
172
226
  } else {
173
- newResult[${k}] = ${w}.value;
227
+ newResult[${k}] = ${v}.value;
174
228
  }
175
- `)}else{let w=y[_];p.write(`const ${w} = ${g(_)};`),p.write(`
176
- if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
229
+ `)}else{let v=g[S];p.write(`const ${v} = ${m(S)};`),p.write(`
230
+ if (${v}.issues.length) payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
177
231
  ...iss,
178
- path: iss.path ? [${Wr(_)}, ...iss.path] : [${Wr(_)}]
179
- })));`),p.write(`newResult[${Wr(_)}] = ${w}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return(_,w)=>b(d,_,w)},o,s=Rn,i=!ii.jitless,c=i&&Mc.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let g=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let w=l.shape;for(let k of l.keys){let P=w[k],U=P._zod.run({value:f[k],issues:[]},p),Z=P._zod.optin==="optional"&&P._zod.optout==="optional";U instanceof Promise?g.push(U.then(j=>Z?jm(j,d,k,f):fi(j,d,k))):Z?jm(U,d,k,f):fi(U,d,k)}}if(!u)return g.length?Promise.all(g).then(()=>d):d;let y=[],m=l.keySet,b=u._zod,_=b.def.type;for(let w of Object.keys(f)){if(m.has(w))continue;if(_==="never"){y.push(w);continue}let k=b.run({value:f[w],issues:[]},p);k instanceof Promise?g.push(k.then(P=>fi(P,d,w))):fi(k,d,w)}return y.length&&d.issues.push({code:"unrecognized_keys",keys:y,input:f,inst:t}),g.length?Promise.all(g).then(()=>d):d}});function Lm(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>gt(s,n,at())))}),e}var Qc=x("$ZodUnion",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),de(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Eo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Lm(i,r,t,n)):Lm(s,r,t,n)}}),$h=x("$ZodDiscriminatedUnion",(t,e)=>{Qc.init(t,e);let r=t._zod.parse;de(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=To(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Rn(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Sh=x("$ZodIntersection",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Zm(r,c,u)):Zm(r,s,i)}});function Jc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(zn(t)&&zn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Jc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Jc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Zm(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Br(t))return t;let n=Jc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var kh=x("$ZodRecord",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!zn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...zt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...zt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>gt(u,n,at())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...zt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...zt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Th=x("$ZodEnum",(t,e)=>{pe.init(t,e);let r=Ac(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Nc.has(typeof n)).map(n=>typeof n=="string"?ir(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Ph=x("$ZodLiteral",(t,e)=>{pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ir(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Eh=x("$ZodTransform",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Vt;return r.value=o,r}}),Rh=x("$ZodOptional",(t,e)=>{pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Eo(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),zh=x("$ZodNullable",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Eo(r.source)}|null)$`):void 0}),de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Ch=x("$ZodDefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>qm(s,e)):qm(o,e)}});function qm(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Ah=x("$ZodPrefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Ih=x("$ZodNonOptional",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Fm(s,t)):Fm(o,t)}});function Fm(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Dh=x("$ZodCatch",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>gt(i,n,at()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gt(s,n,at()))},input:r.value}),r.issues=[]),r)}});var Oh=x("$ZodPipe",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>e.in._zod.values),de(t._zod,"optin",()=>e.in._zod.optin),de(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Um(s,e,n)):Um(o,e,n)}});function Um(t,e,r){return Br(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Mh=x("$ZodReadonly",(t,e)=>{pe.init(t,e),de(t._zod,"propValues",()=>e.innerType._zod.propValues),de(t._zod,"values",()=>e.innerType._zod.values),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Vm):Vm(o)}});function Vm(t){return t.value=Object.freeze(t.value),t}var Nh=x("$ZodCustom",(t,e)=>{Ne.init(t,e),pe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Wm(s,r,n,t));Wm(o,r,n,t)}});function Wm(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Zc(o))}}var q0=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},F0=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${q0(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ui(n.values[0])}`:`Invalid option: expected one of ${ai(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${ai(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function jh(){return{localeError:F0()}}var Yc=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function U0(){return new Yc}var Ao=U0();function Lh(t,e){return new t({type:"string",...O(e)})}function Zh(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...O(e)})}function Xc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...O(e)})}function qh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...O(e)})}function Fh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...O(e)})}function Uh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...O(e)})}function Vh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...O(e)})}function Wh(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...O(e)})}function Bh(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...O(e)})}function Hh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...O(e)})}function Gh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...O(e)})}function Jh(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...O(e)})}function Kh(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...O(e)})}function Qh(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...O(e)})}function Yh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...O(e)})}function Xh(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...O(e)})}function eg(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...O(e)})}function tg(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...O(e)})}function rg(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...O(e)})}function ng(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...O(e)})}function og(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...O(e)})}function sg(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...O(e)})}function ig(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...O(e)})}function ag(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...O(e)})}function cg(t,e){return new t({type:"string",format:"date",check:"string_format",...O(e)})}function ug(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...O(e)})}function lg(t,e){return new t({type:"string",format:"duration",check:"string_format",...O(e)})}function dg(t,e){return new t({type:"number",checks:[],...O(e)})}function pg(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...O(e)})}function fg(t,e){return new t({type:"boolean",...O(e)})}function mg(t,e){return new t({type:"null",...O(e)})}function hg(t){return new t({type:"unknown"})}function gg(t,e){return new t({type:"never",...O(e)})}function hi(t,e){return new Hc({check:"less_than",...O(e),value:t,inclusive:!1})}function Io(t,e){return new Hc({check:"less_than",...O(e),value:t,inclusive:!0})}function gi(t,e){return new Gc({check:"greater_than",...O(e),value:t,inclusive:!1})}function Do(t,e){return new Gc({check:"greater_than",...O(e),value:t,inclusive:!0})}function yi(t,e){return new $m({check:"multiple_of",...O(e),value:t})}function _i(t,e){return new km({check:"max_length",...O(e),maximum:t})}function Cn(t,e){return new Tm({check:"min_length",...O(e),minimum:t})}function vi(t,e){return new Pm({check:"length_equals",...O(e),length:t})}function eu(t,e){return new Em({check:"string_format",format:"regex",...O(e),pattern:t})}function tu(t){return new Rm({check:"string_format",format:"lowercase",...O(t)})}function ru(t){return new zm({check:"string_format",format:"uppercase",...O(t)})}function nu(t,e){return new Cm({check:"string_format",format:"includes",...O(e),includes:t})}function ou(t,e){return new Am({check:"string_format",format:"starts_with",...O(e),prefix:t})}function su(t,e){return new Im({check:"string_format",format:"ends_with",...O(e),suffix:t})}function Hr(t){return new Dm({check:"overwrite",tx:t})}function iu(t){return Hr(e=>e.normalize(t))}function au(){return Hr(t=>t.trim())}function cu(){return Hr(t=>t.toLowerCase())}function uu(){return Hr(t=>t.toUpperCase())}function yg(t,e,r){return new t({type:"array",element:e,...O(r)})}function _g(t,e,r){let n=O(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function vg(t,e,r){return new t({type:"custom",check:"custom",fn:e,...O(r)})}function An(t){return!!t._zod}function ar(t,e){return An(t)?zo(t,e):t.safeParse(e)}function xi(t){if(!t)return;let e;if(An(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function xg(t){if(An(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Mo={};We(Mo,{ZodISODate:()=>wg,ZodISODateTime:()=>bg,ZodISODuration:()=>Sg,ZodISOTime:()=>$g,date:()=>du,datetime:()=>lu,duration:()=>fu,time:()=>pu});var bg=x("ZodISODateTime",(t,e)=>{nh.init(t,e),_e.init(t,e)});function lu(t){return ag(bg,t)}var wg=x("ZodISODate",(t,e)=>{oh.init(t,e),_e.init(t,e)});function du(t){return cg(wg,t)}var $g=x("ZodISOTime",(t,e)=>{sh.init(t,e),_e.init(t,e)});function pu(t){return ug($g,t)}var Sg=x("ZodISODuration",(t,e)=>{ih.init(t,e),_e.init(t,e)});function fu(t){return lg(Sg,t)}var kg=(t,e)=>{li.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Vf(t,r)},flatten:{value:r=>Uf(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},k1=x("ZodError",kg),No=x("ZodError",kg,{Parent:Error});var Tg=Wf(No),Pg=Bf(No),Eg=Fc(No),Rg=Uc(No);var $e=x("ZodType",(t,e)=>(pe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Tg(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Eg(t,r,n),t.parseAsync=async(r,n)=>Pg(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Rg(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Zk(r,n)),t.superRefine=r=>t.check(qk(r)),t.overwrite=r=>t.check(Hr(r)),t.optional=()=>we(t),t.nullable=()=>Ag(t),t.nullish=()=>we(Ag(t)),t.nonoptional=r=>Ik(t,r),t.array=()=>Y(t),t.or=r=>fe([t,r]),t.and=r=>wi(t,r),t.transform=r=>hu(t,Ng(r)),t.default=r=>zk(t,r),t.prefault=r=>Ak(t,r),t.catch=r=>Ok(t,r),t.pipe=r=>hu(t,r),t.readonly=()=>jk(t),t.describe=r=>{let n=t.clone();return Ao.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ao.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ao.get(t);let n=t.clone();return Ao.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Ig=x("_ZodString",(t,e)=>{mi.init(t,e),$e.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(eu(...n)),t.includes=(...n)=>t.check(nu(...n)),t.startsWith=(...n)=>t.check(ou(...n)),t.endsWith=(...n)=>t.check(su(...n)),t.min=(...n)=>t.check(Cn(...n)),t.max=(...n)=>t.check(_i(...n)),t.length=(...n)=>t.check(vi(...n)),t.nonempty=(...n)=>t.check(Cn(1,...n)),t.lowercase=n=>t.check(tu(n)),t.uppercase=n=>t.check(ru(n)),t.trim=()=>t.check(au()),t.normalize=(...n)=>t.check(iu(...n)),t.toLowerCase=()=>t.check(cu()),t.toUpperCase=()=>t.check(uu())}),Y0=x("ZodString",(t,e)=>{mi.init(t,e),Ig.init(t,e),t.email=r=>t.check(Zh(X0,r)),t.url=r=>t.check(Wh(ek,r)),t.jwt=r=>t.check(ig(hk,r)),t.emoji=r=>t.check(Bh(tk,r)),t.guid=r=>t.check(Xc(zg,r)),t.uuid=r=>t.check(qh(bi,r)),t.uuidv4=r=>t.check(Fh(bi,r)),t.uuidv6=r=>t.check(Uh(bi,r)),t.uuidv7=r=>t.check(Vh(bi,r)),t.nanoid=r=>t.check(Hh(rk,r)),t.guid=r=>t.check(Xc(zg,r)),t.cuid=r=>t.check(Gh(nk,r)),t.cuid2=r=>t.check(Jh(ok,r)),t.ulid=r=>t.check(Kh(sk,r)),t.base64=r=>t.check(ng(pk,r)),t.base64url=r=>t.check(og(fk,r)),t.xid=r=>t.check(Qh(ik,r)),t.ksuid=r=>t.check(Yh(ak,r)),t.ipv4=r=>t.check(Xh(ck,r)),t.ipv6=r=>t.check(eg(uk,r)),t.cidrv4=r=>t.check(tg(lk,r)),t.cidrv6=r=>t.check(rg(dk,r)),t.e164=r=>t.check(sg(mk,r)),t.datetime=r=>t.check(lu(r)),t.date=r=>t.check(du(r)),t.time=r=>t.check(pu(r)),t.duration=r=>t.check(fu(r))});function v(t){return Lh(Y0,t)}var _e=x("ZodStringFormat",(t,e)=>{he.init(t,e),Ig.init(t,e)}),X0=x("ZodEmail",(t,e)=>{Gm.init(t,e),_e.init(t,e)});var zg=x("ZodGUID",(t,e)=>{Bm.init(t,e),_e.init(t,e)});var bi=x("ZodUUID",(t,e)=>{Hm.init(t,e),_e.init(t,e)});var ek=x("ZodURL",(t,e)=>{Jm.init(t,e),_e.init(t,e)});var tk=x("ZodEmoji",(t,e)=>{Km.init(t,e),_e.init(t,e)});var rk=x("ZodNanoID",(t,e)=>{Qm.init(t,e),_e.init(t,e)});var nk=x("ZodCUID",(t,e)=>{Ym.init(t,e),_e.init(t,e)});var ok=x("ZodCUID2",(t,e)=>{Xm.init(t,e),_e.init(t,e)});var sk=x("ZodULID",(t,e)=>{eh.init(t,e),_e.init(t,e)});var ik=x("ZodXID",(t,e)=>{th.init(t,e),_e.init(t,e)});var ak=x("ZodKSUID",(t,e)=>{rh.init(t,e),_e.init(t,e)});var ck=x("ZodIPv4",(t,e)=>{ah.init(t,e),_e.init(t,e)});var uk=x("ZodIPv6",(t,e)=>{ch.init(t,e),_e.init(t,e)});var lk=x("ZodCIDRv4",(t,e)=>{uh.init(t,e),_e.init(t,e)});var dk=x("ZodCIDRv6",(t,e)=>{lh.init(t,e),_e.init(t,e)});var pk=x("ZodBase64",(t,e)=>{ph.init(t,e),_e.init(t,e)});var fk=x("ZodBase64URL",(t,e)=>{fh.init(t,e),_e.init(t,e)});var mk=x("ZodE164",(t,e)=>{mh.init(t,e),_e.init(t,e)});var hk=x("ZodJWT",(t,e)=>{hh.init(t,e),_e.init(t,e)});var Dg=x("ZodNumber",(t,e)=>{Kc.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(gi(n,o)),t.gte=(n,o)=>t.check(Do(n,o)),t.min=(n,o)=>t.check(Do(n,o)),t.lt=(n,o)=>t.check(hi(n,o)),t.lte=(n,o)=>t.check(Io(n,o)),t.max=(n,o)=>t.check(Io(n,o)),t.int=n=>t.check(Cg(n)),t.safe=n=>t.check(Cg(n)),t.positive=n=>t.check(gi(0,n)),t.nonnegative=n=>t.check(Do(0,n)),t.negative=n=>t.check(hi(0,n)),t.nonpositive=n=>t.check(Io(0,n)),t.multipleOf=(n,o)=>t.check(yi(n,o)),t.step=(n,o)=>t.check(yi(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ae(t){return dg(Dg,t)}var gk=x("ZodNumberFormat",(t,e)=>{gh.init(t,e),Dg.init(t,e)});function Cg(t){return pg(gk,t)}var yk=x("ZodBoolean",(t,e)=>{yh.init(t,e),$e.init(t,e)});function Pe(t){return fg(yk,t)}var _k=x("ZodNull",(t,e)=>{_h.init(t,e),$e.init(t,e)});function gu(t){return mg(_k,t)}var vk=x("ZodUnknown",(t,e)=>{vh.init(t,e),$e.init(t,e)});function ve(){return hg(vk)}var xk=x("ZodNever",(t,e)=>{xh.init(t,e),$e.init(t,e)});function bk(t){return gg(xk,t)}var wk=x("ZodArray",(t,e)=>{bh.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Cn(r,n)),t.nonempty=r=>t.check(Cn(1,r)),t.max=(r,n)=>t.check(_i(r,n)),t.length=(r,n)=>t.check(vi(r,n)),t.unwrap=()=>t.element});function Y(t,e){return yg(wk,t,e)}var Og=x("ZodObject",(t,e)=>{wh.init(t,e),$e.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Je(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ve()}),t.loose=()=>t.clone({...t._zod.def,catchall:ve()}),t.strict=()=>t.clone({...t._zod.def,catchall:bk()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>se.extend(t,r),t.merge=r=>se.merge(t,r),t.pick=r=>se.pick(t,r),t.omit=r=>se.omit(t,r),t.partial=(...r)=>se.partial(jg,t,r[0]),t.required=(...r)=>se.required(Lg,t,r[0])});function z(t,e){let r={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new Og(r)}function qe(t,e){return new Og({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:ve(),...se.normalizeParams(e)})}var Mg=x("ZodUnion",(t,e)=>{Qc.init(t,e),$e.init(t,e),t.options=e.options});function fe(t,e){return new Mg({type:"union",options:t,...se.normalizeParams(e)})}var $k=x("ZodDiscriminatedUnion",(t,e)=>{Mg.init(t,e),$h.init(t,e)});function yu(t,e,r){return new $k({type:"union",options:e,discriminator:t,...se.normalizeParams(r)})}var Sk=x("ZodIntersection",(t,e)=>{Sh.init(t,e),$e.init(t,e)});function wi(t,e){return new Sk({type:"intersection",left:t,right:e})}var kk=x("ZodRecord",(t,e)=>{kh.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function xe(t,e,r){return new kk({type:"record",keyType:t,valueType:e,...se.normalizeParams(r)})}var mu=x("ZodEnum",(t,e)=>{Th.init(t,e),$e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new mu({...e,checks:[],...se.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new mu({...e,checks:[],...se.normalizeParams(o),entries:s})}});function Je(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new mu({type:"enum",entries:r,...se.normalizeParams(e)})}var Tk=x("ZodLiteral",(t,e)=>{Ph.init(t,e),$e.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function A(t,e){return new Tk({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var Pk=x("ZodTransform",(t,e)=>{Eh.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(se.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(se.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Ng(t){return new Pk({type:"transform",transform:t})}var jg=x("ZodOptional",(t,e)=>{Rh.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function we(t){return new jg({type:"optional",innerType:t})}var Ek=x("ZodNullable",(t,e)=>{zh.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ag(t){return new Ek({type:"nullable",innerType:t})}var Rk=x("ZodDefault",(t,e)=>{Ch.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function zk(t,e){return new Rk({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Ck=x("ZodPrefault",(t,e)=>{Ah.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ak(t,e){return new Ck({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Lg=x("ZodNonOptional",(t,e)=>{Ih.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ik(t,e){return new Lg({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var Dk=x("ZodCatch",(t,e)=>{Dh.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Ok(t,e){return new Dk({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Mk=x("ZodPipe",(t,e)=>{Oh.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});function hu(t,e){return new Mk({type:"pipe",in:t,out:e})}var Nk=x("ZodReadonly",(t,e)=>{Mh.init(t,e),$e.init(t,e)});function jk(t){return new Nk({type:"readonly",innerType:t})}var Zg=x("ZodCustom",(t,e)=>{Nh.init(t,e),$e.init(t,e)});function Lk(t){let e=new Ne({check:"custom"});return e._zod.check=t,e}function qg(t,e){return _g(Zg,t??(()=>!0),e)}function Zk(t,e={}){return vg(Zg,t,e)}function qk(t){let e=Lk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(se.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(se.issue(o))}},t(r.value,r)));return e}function _u(t,e){return hu(Ng(t),e)}at(jh());var xu="2025-11-25";var Fg=[xu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],cr="io.modelcontextprotocol/related-task",Si="2.0",Re=qg(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Ug=fe([v(),ae().int()]),Vg=v(),_L=qe({ttl:fe([ae(),gu()]).optional(),pollInterval:ae().optional()}),Fk=z({ttl:ae().optional()}),Uk=z({taskId:v()}),bu=qe({progressToken:Ug.optional(),[cr]:Uk.optional()}),rt=z({_meta:bu.optional()}),jo=rt.extend({task:Fk.optional()}),Wg=t=>jo.safeParse(t).success,ze=z({method:v(),params:rt.loose().optional()}),ct=z({_meta:bu.optional()}),ut=z({method:v(),params:ct.loose().optional()}),Ce=qe({_meta:bu.optional()}),ki=fe([v(),ae().int()]),Bg=z({jsonrpc:A(Si),id:ki,...ze.shape}).strict(),wu=t=>Bg.safeParse(t).success,Hg=z({jsonrpc:A(Si),...ut.shape}).strict(),Gg=t=>Hg.safeParse(t).success,$u=z({jsonrpc:A(Si),id:ki,result:Ce}).strict(),Lo=t=>$u.safeParse(t).success;var X;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(X||(X={}));var Su=z({jsonrpc:A(Si),id:ki.optional(),error:z({code:ae().int(),message:v(),data:ve().optional()})}).strict();var Jg=t=>Su.safeParse(t).success;var Kg=fe([Bg,Hg,$u,Su]),vL=fe([$u,Su]),Ti=Ce.strict(),Vk=ct.extend({requestId:ki.optional(),reason:v().optional()}),Pi=ut.extend({method:A("notifications/cancelled"),params:Vk}),Wk=z({src:v(),mimeType:v().optional(),sizes:Y(v()).optional(),theme:Je(["light","dark"]).optional()}),Zo=z({icons:Y(Wk).optional()}),In=z({name:v(),title:v().optional()}),Qg=In.extend({...In.shape,...Zo.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),Bk=wi(z({applyDefaults:Pe().optional()}),xe(v(),ve())),Hk=_u(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,wi(z({form:Bk.optional(),url:Re.optional()}),xe(v(),ve()).optional())),Gk=qe({list:Re.optional(),cancel:Re.optional(),requests:qe({sampling:qe({createMessage:Re.optional()}).optional(),elicitation:qe({create:Re.optional()}).optional()}).optional()}),Jk=qe({list:Re.optional(),cancel:Re.optional(),requests:qe({tools:qe({call:Re.optional()}).optional()}).optional()}),Kk=z({experimental:xe(v(),Re).optional(),sampling:z({context:Re.optional(),tools:Re.optional()}).optional(),elicitation:Hk.optional(),roots:z({listChanged:Pe().optional()}).optional(),tasks:Gk.optional()}),Qk=rt.extend({protocolVersion:v(),capabilities:Kk,clientInfo:Qg}),ku=ze.extend({method:A("initialize"),params:Qk});var Yk=z({experimental:xe(v(),Re).optional(),logging:Re.optional(),completions:Re.optional(),prompts:z({listChanged:Pe().optional()}).optional(),resources:z({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:z({listChanged:Pe().optional()}).optional(),tasks:Jk.optional()}),Xk=Ce.extend({protocolVersion:v(),capabilities:Yk,serverInfo:Qg,instructions:v().optional()}),Tu=ut.extend({method:A("notifications/initialized"),params:ct.optional()});var Ei=ze.extend({method:A("ping"),params:rt.optional()}),eT=z({progress:ae(),total:we(ae()),message:we(v())}),tT=z({...ct.shape,...eT.shape,progressToken:Ug}),Ri=ut.extend({method:A("notifications/progress"),params:tT}),rT=rt.extend({cursor:Vg.optional()}),qo=ze.extend({params:rT.optional()}),Fo=Ce.extend({nextCursor:Vg.optional()}),nT=Je(["working","input_required","completed","failed","cancelled"]),Uo=z({taskId:v(),status:nT,ttl:fe([ae(),gu()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:we(ae()),statusMessage:we(v())}),Dn=Ce.extend({task:Uo}),oT=ct.merge(Uo),Vo=ut.extend({method:A("notifications/tasks/status"),params:oT}),zi=ze.extend({method:A("tasks/get"),params:rt.extend({taskId:v()})}),Ci=Ce.merge(Uo),Ai=ze.extend({method:A("tasks/result"),params:rt.extend({taskId:v()})}),xL=Ce.loose(),Ii=qo.extend({method:A("tasks/list")}),Di=Fo.extend({tasks:Y(Uo)}),Oi=ze.extend({method:A("tasks/cancel"),params:rt.extend({taskId:v()})}),Yg=Ce.merge(Uo),Xg=z({uri:v(),mimeType:we(v()),_meta:xe(v(),ve()).optional()}),ey=Xg.extend({text:v()}),Pu=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ty=Xg.extend({blob:Pu}),Wo=Je(["user","assistant"]),On=z({audience:Y(Wo).optional(),priority:ae().min(0).max(1).optional(),lastModified:Mo.datetime({offset:!0}).optional()}),ry=z({...In.shape,...Zo.shape,uri:v(),description:we(v()),mimeType:we(v()),annotations:On.optional(),_meta:we(qe({}))}),sT=z({...In.shape,...Zo.shape,uriTemplate:v(),description:we(v()),mimeType:we(v()),annotations:On.optional(),_meta:we(qe({}))}),iT=qo.extend({method:A("resources/list")}),aT=Fo.extend({resources:Y(ry)}),cT=qo.extend({method:A("resources/templates/list")}),uT=Fo.extend({resourceTemplates:Y(sT)}),Eu=rt.extend({uri:v()}),lT=Eu,dT=ze.extend({method:A("resources/read"),params:lT}),pT=Ce.extend({contents:Y(fe([ey,ty]))}),fT=ut.extend({method:A("notifications/resources/list_changed"),params:ct.optional()}),mT=Eu,hT=ze.extend({method:A("resources/subscribe"),params:mT}),gT=Eu,yT=ze.extend({method:A("resources/unsubscribe"),params:gT}),_T=ct.extend({uri:v()}),vT=ut.extend({method:A("notifications/resources/updated"),params:_T}),xT=z({name:v(),description:we(v()),required:we(Pe())}),bT=z({...In.shape,...Zo.shape,description:we(v()),arguments:we(Y(xT)),_meta:we(qe({}))}),wT=qo.extend({method:A("prompts/list")}),$T=Fo.extend({prompts:Y(bT)}),ST=rt.extend({name:v(),arguments:xe(v(),v()).optional()}),kT=ze.extend({method:A("prompts/get"),params:ST}),Ru=z({type:A("text"),text:v(),annotations:On.optional(),_meta:xe(v(),ve()).optional()}),zu=z({type:A("image"),data:Pu,mimeType:v(),annotations:On.optional(),_meta:xe(v(),ve()).optional()}),Cu=z({type:A("audio"),data:Pu,mimeType:v(),annotations:On.optional(),_meta:xe(v(),ve()).optional()}),TT=z({type:A("tool_use"),name:v(),id:v(),input:xe(v(),ve()),_meta:xe(v(),ve()).optional()}),PT=z({type:A("resource"),resource:fe([ey,ty]),annotations:On.optional(),_meta:xe(v(),ve()).optional()}),ET=ry.extend({type:A("resource_link")}),Au=fe([Ru,zu,Cu,ET,PT]),RT=z({role:Wo,content:Au}),zT=Ce.extend({description:v().optional(),messages:Y(RT)}),CT=ut.extend({method:A("notifications/prompts/list_changed"),params:ct.optional()}),AT=z({title:v().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),IT=z({taskSupport:Je(["required","optional","forbidden"]).optional()}),ny=z({...In.shape,...Zo.shape,description:v().optional(),inputSchema:z({type:A("object"),properties:xe(v(),Re).optional(),required:Y(v()).optional()}).catchall(ve()),outputSchema:z({type:A("object"),properties:xe(v(),Re).optional(),required:Y(v()).optional()}).catchall(ve()).optional(),annotations:AT.optional(),execution:IT.optional(),_meta:xe(v(),ve()).optional()}),Iu=qo.extend({method:A("tools/list")}),DT=Fo.extend({tools:Y(ny)}),Mi=Ce.extend({content:Y(Au).default([]),structuredContent:xe(v(),ve()).optional(),isError:Pe().optional()}),bL=Mi.or(Ce.extend({toolResult:ve()})),OT=jo.extend({name:v(),arguments:xe(v(),ve()).optional()}),Bo=ze.extend({method:A("tools/call"),params:OT}),MT=ut.extend({method:A("notifications/tools/list_changed"),params:ct.optional()}),wL=z({autoRefresh:Pe().default(!0),debounceMs:ae().int().nonnegative().default(300)}),Ho=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),NT=rt.extend({level:Ho}),Du=ze.extend({method:A("logging/setLevel"),params:NT}),jT=ct.extend({level:Ho,logger:v().optional(),data:ve()}),LT=ut.extend({method:A("notifications/message"),params:jT}),ZT=z({name:v().optional()}),qT=z({hints:Y(ZT).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),FT=z({mode:Je(["auto","required","none"]).optional()}),UT=z({type:A("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:Y(Au).default([]),structuredContent:z({}).loose().optional(),isError:Pe().optional(),_meta:xe(v(),ve()).optional()}),VT=yu("type",[Ru,zu,Cu]),$i=yu("type",[Ru,zu,Cu,TT,UT]),WT=z({role:Wo,content:fe([$i,Y($i)]),_meta:xe(v(),ve()).optional()}),BT=jo.extend({messages:Y(WT),modelPreferences:qT.optional(),systemPrompt:v().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:Y(v()).optional(),metadata:Re.optional(),tools:Y(ny).optional(),toolChoice:FT.optional()}),HT=ze.extend({method:A("sampling/createMessage"),params:BT}),Ou=Ce.extend({model:v(),stopReason:we(Je(["endTurn","stopSequence","maxTokens"]).or(v())),role:Wo,content:VT}),Mu=Ce.extend({model:v(),stopReason:we(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:Wo,content:fe([$i,Y($i)])}),GT=z({type:A("boolean"),title:v().optional(),description:v().optional(),default:Pe().optional()}),JT=z({type:A("string"),title:v().optional(),description:v().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:Je(["email","uri","date","date-time"]).optional(),default:v().optional()}),KT=z({type:Je(["number","integer"]),title:v().optional(),description:v().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),QT=z({type:A("string"),title:v().optional(),description:v().optional(),enum:Y(v()),default:v().optional()}),YT=z({type:A("string"),title:v().optional(),description:v().optional(),oneOf:Y(z({const:v(),title:v()})),default:v().optional()}),XT=z({type:A("string"),title:v().optional(),description:v().optional(),enum:Y(v()),enumNames:Y(v()).optional(),default:v().optional()}),eP=fe([QT,YT]),tP=z({type:A("array"),title:v().optional(),description:v().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:z({type:A("string"),enum:Y(v())}),default:Y(v()).optional()}),rP=z({type:A("array"),title:v().optional(),description:v().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:z({anyOf:Y(z({const:v(),title:v()}))}),default:Y(v()).optional()}),nP=fe([tP,rP]),oP=fe([XT,eP,nP]),sP=fe([oP,GT,JT,KT]),iP=jo.extend({mode:A("form").optional(),message:v(),requestedSchema:z({type:A("object"),properties:xe(v(),sP),required:Y(v()).optional()})}),aP=jo.extend({mode:A("url"),message:v(),elicitationId:v(),url:v().url()}),cP=fe([iP,aP]),uP=ze.extend({method:A("elicitation/create"),params:cP}),lP=ct.extend({elicitationId:v()}),dP=ut.extend({method:A("notifications/elicitation/complete"),params:lP}),Ni=Ce.extend({action:Je(["accept","decline","cancel"]),content:_u(t=>t===null?void 0:t,xe(v(),fe([v(),ae(),Pe(),Y(v())])).optional())}),pP=z({type:A("ref/resource"),uri:v()});var fP=z({type:A("ref/prompt"),name:v()}),mP=rt.extend({ref:fe([fP,pP]),argument:z({name:v(),value:v()}),context:z({arguments:xe(v(),v()).optional()}).optional()}),hP=ze.extend({method:A("completion/complete"),params:mP});var gP=Ce.extend({completion:qe({values:Y(v()).max(100),total:we(ae().int()),hasMore:we(Pe())})}),yP=z({uri:v().startsWith("file://"),name:v().optional(),_meta:xe(v(),ve()).optional()}),_P=ze.extend({method:A("roots/list"),params:rt.optional()}),Nu=Ce.extend({roots:Y(yP)}),vP=ut.extend({method:A("notifications/roots/list_changed"),params:ct.optional()}),$L=fe([Ei,ku,hP,Du,kT,wT,iT,cT,dT,hT,yT,Bo,Iu,zi,Ai,Ii,Oi]),SL=fe([Pi,Ri,Tu,vP,Vo]),kL=fe([Ti,Ou,Mu,Ni,Nu,Ci,Di,Dn]),TL=fe([Ei,HT,uP,_P,zi,Ai,Ii,Oi]),PL=fe([Pi,Ri,LT,vT,fT,MT,CT,Vo,dP]),EL=fe([Ti,Xk,gP,zT,$T,aT,uT,pT,Mi,DT,Ci,Di,Dn]),W=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new vu(o.elicitations,r)}return new t(e,r,n)}},vu=class extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ur(t){return t==="completed"||t==="failed"||t==="cancelled"}var sy=Symbol("Let zodToJsonSchema decide on which parser to use");var oy={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},iy=t=>typeof t=="string"?{...oy,name:t}:{...oy,...t};var ay=t=>{let e=iy(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ju(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,ju(t,e,n,o)}var ji=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function be(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ji(e,t.currentPath):e.join("/")}}function cy(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=M(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function uy(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function ly(){return{type:"boolean"}}function Li(t,e){return M(t.type._def,e)}var dy=(t,e)=>M(t.innerType._def,e);function Lu(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Lu(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xP(t,e)}}var xP=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function py(t,e){return{...M(t.innerType._def,e),default:t.defaultValue()}}function fy(t,e){return e.effectStrategy==="input"?M(t.schema._def,e):be(e)}function my(t){return{type:"string",enum:Array.from(t.values)}}var bP=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function hy(t,e){let r=[M(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),M(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(bP(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function gy(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Zu,yt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Zu===void 0&&(Zu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Zu),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Zi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":_t(r,"email",n.message,e);break;case"format:idn-email":_t(r,"idn-email",n.message,e);break;case"pattern:zod":Fe(r,yt.email,n.message,e);break}break;case"url":_t(r,"uri",n.message,e);break;case"uuid":_t(r,"uuid",n.message,e);break;case"regex":Fe(r,n.regex,n.message,e);break;case"cuid":Fe(r,yt.cuid,n.message,e);break;case"cuid2":Fe(r,yt.cuid2,n.message,e);break;case"startsWith":Fe(r,RegExp(`^${qu(n.value,e)}`),n.message,e);break;case"endsWith":Fe(r,RegExp(`${qu(n.value,e)}$`),n.message,e);break;case"datetime":_t(r,"date-time",n.message,e);break;case"date":_t(r,"date",n.message,e);break;case"time":_t(r,"time",n.message,e);break;case"duration":_t(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Fe(r,RegExp(qu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&_t(r,"ipv4",n.message,e),n.version!=="v4"&&_t(r,"ipv6",n.message,e);break}case"base64url":Fe(r,yt.base64url,n.message,e);break;case"jwt":Fe(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Fe(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&Fe(r,yt.ipv6Cidr,n.message,e);break}case"emoji":Fe(r,yt.emoji(),n.message,e);break;case"ulid":{Fe(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{_t(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Fe(r,yt.base64,n.message,e);break}}break}case"nanoid":Fe(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function qu(t,e){return e.patternStrategy==="escape"?$P(t):t}var wP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $P(t){let e="";for(let r=0;r<t.length;r++)wP.has(t[r])||(e+="\\"),e+=t[r];return e}function _t(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ee(t,"format",e,r,n)}function Fe(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:yy(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",yy(e,n),r,n)}function yy(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
232
+ path: iss.path ? [${Hr(S)}, ...iss.path] : [${Hr(S)}]
233
+ })));`),p.write(`newResult[${Hr(S)}] = ${v}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(S,v)=>_(d,S,v)},o,s=zn,i=!Ti.jitless,c=i&&hu.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let v=l.shape;for(let k of l.keys){let x=v[k],z=x._zod.run({value:f[k],issues:[]},p),O=x._zod.optin==="optional"&&x._zod.optout==="optional";z instanceof Promise?m.push(z.then(Z=>O?Nh(Z,d,k,f):zi(Z,d,k))):O?Nh(z,d,k,f):zi(z,d,k)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],y=l.keySet,_=u._zod,S=_.def.type;for(let v of Object.keys(f)){if(y.has(v))continue;if(S==="never"){g.push(v);continue}let k=_.run({value:f[v],issues:[]},p);k instanceof Promise?m.push(k.then(x=>zi(x,d,v))):zi(k,d,v)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function Lh(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>gt(s,n,at())))}),e}var Iu=w("$ZodUnion",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),de(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>No(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Lh(i,r,t,n)):Lh(s,r,t,n)}}),Sg=w("$ZodDiscriminatedUnion",(t,e)=>{Iu.init(t,e);let r=t._zod.parse;de(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Mo(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!zn(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),$g=w("$ZodIntersection",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Fh(r,c,u)):Fh(r,s,i)}});function Eu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(On(t)&&On(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Eu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Eu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Fh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Kr(t))return t;let n=Eu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var kg=w("$ZodRecord",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!On(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...At(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...At(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>gt(u,n,at())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...At(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...At(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Pg=w("$ZodEnum",(t,e)=>{pe.init(t,e);let r=du(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>gu.has(typeof n)).map(n=>typeof n=="string"?ur(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Tg=w("$ZodLiteral",(t,e)=>{pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ur(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Eg=w("$ZodTransform",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ht;return r.value=o,r}}),Rg=w("$ZodOptional",(t,e)=>{pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${No(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Ig=w("$ZodNullable",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${No(r.source)}|null)$`):void 0}),de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Ag=w("$ZodDefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Zh(s,e)):Zh(o,e)}});function Zh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Cg=w("$ZodPrefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Dg=w("$ZodNonOptional",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Uh(s,t)):Uh(o,t)}});function Uh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var zg=w("$ZodCatch",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>gt(i,n,at()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gt(s,n,at()))},input:r.value}),r.issues=[]),r)}});var Og=w("$ZodPipe",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>e.in._zod.values),de(t._zod,"optin",()=>e.in._zod.optin),de(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>qh(s,e,n)):qh(o,e,n)}});function qh(t,e,r){return Kr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Mg=w("$ZodReadonly",(t,e)=>{pe.init(t,e),de(t._zod,"propValues",()=>e.innerType._zod.propValues),de(t._zod,"values",()=>e.innerType._zod.values),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Vh):Vh(o)}});function Vh(t){return t.value=Object.freeze(t.value),t}var jg=w("$ZodCustom",(t,e)=>{je.init(t,e),pe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Bh(s,r,n,t));Bh(o,r,n,t)}});function Bh(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(_u(o))}}var RP=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},IP=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${RP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ii(n.values[0])}`:`Invalid option: expected one of ${Ei(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ei(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Ng(){return{localeError:IP()}}var Au=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function AP(){return new Au}var Uo=AP();function Lg(t,e){return new t({type:"string",...N(e)})}function Fg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function Cu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function Zg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function Ug(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function qg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function Vg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function Bg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function Wg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function Hg(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function Kg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function Jg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function Gg(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function Yg(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function Qg(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function Xg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function ey(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function ty(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function ry(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function ny(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function oy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function sy(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function iy(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}function ay(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function cy(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function uy(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function ly(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function dy(t,e){return new t({type:"number",checks:[],...N(e)})}function py(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function fy(t,e){return new t({type:"boolean",...N(e)})}function my(t,e){return new t({type:"null",...N(e)})}function hy(t){return new t({type:"unknown"})}function gy(t,e){return new t({type:"never",...N(e)})}function Mi(t,e){return new Pu({check:"less_than",...N(e),value:t,inclusive:!1})}function qo(t,e){return new Pu({check:"less_than",...N(e),value:t,inclusive:!0})}function ji(t,e){return new Tu({check:"greater_than",...N(e),value:t,inclusive:!1})}function Vo(t,e){return new Tu({check:"greater_than",...N(e),value:t,inclusive:!0})}function Ni(t,e){return new Sh({check:"multiple_of",...N(e),value:t})}function Li(t,e){return new kh({check:"max_length",...N(e),maximum:t})}function Mn(t,e){return new Ph({check:"min_length",...N(e),minimum:t})}function Fi(t,e){return new Th({check:"length_equals",...N(e),length:t})}function Du(t,e){return new Eh({check:"string_format",format:"regex",...N(e),pattern:t})}function zu(t){return new Rh({check:"string_format",format:"lowercase",...N(t)})}function Ou(t){return new Ih({check:"string_format",format:"uppercase",...N(t)})}function Mu(t,e){return new Ah({check:"string_format",format:"includes",...N(e),includes:t})}function ju(t,e){return new Ch({check:"string_format",format:"starts_with",...N(e),prefix:t})}function Nu(t,e){return new Dh({check:"string_format",format:"ends_with",...N(e),suffix:t})}function Jr(t){return new zh({check:"overwrite",tx:t})}function Lu(t){return Jr(e=>e.normalize(t))}function Fu(){return Jr(t=>t.trim())}function Zu(){return Jr(t=>t.toLowerCase())}function Uu(){return Jr(t=>t.toUpperCase())}function yy(t,e,r){return new t({type:"array",element:e,...N(r)})}function vy(t,e,r){let n=N(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function _y(t,e,r){return new t({type:"custom",check:"custom",fn:e,...N(r)})}function jn(t){return!!t._zod}function lr(t,e){return jn(t)?Fo(t,e):t.safeParse(e)}function Zi(t){if(!t)return;let e;if(jn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function by(t){if(jn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Wo={};Ze(Wo,{ZodISODate:()=>xy,ZodISODateTime:()=>wy,ZodISODuration:()=>$y,ZodISOTime:()=>Sy,date:()=>Vu,datetime:()=>qu,duration:()=>Wu,time:()=>Bu});var wy=w("ZodISODateTime",(t,e)=>{ng.init(t,e),ve.init(t,e)});function qu(t){return ay(wy,t)}var xy=w("ZodISODate",(t,e)=>{og.init(t,e),ve.init(t,e)});function Vu(t){return cy(xy,t)}var Sy=w("ZodISOTime",(t,e)=>{sg.init(t,e),ve.init(t,e)});function Bu(t){return uy(Sy,t)}var $y=w("ZodISODuration",(t,e)=>{ig.init(t,e),ve.init(t,e)});function Wu(t){return ly($y,t)}var ky=(t,e)=>{Ai.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Vm(t,r)},flatten:{value:r=>qm(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},oU=w("ZodError",ky),Ho=w("ZodError",ky,{Parent:Error});var Py=Bm(Ho),Ty=Wm(Ho),Ey=wu(Ho),Ry=xu(Ho);var Se=w("ZodType",(t,e)=>(pe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>It(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Py(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ey(t,r,n),t.parseAsync=async(r,n)=>Ty(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ry(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(ET(r,n)),t.superRefine=r=>t.check(RT(r)),t.overwrite=r=>t.check(Jr(r)),t.optional=()=>xe(t),t.nullable=()=>Cy(t),t.nullish=()=>xe(Cy(t)),t.nonoptional=r=>wT(t,r),t.array=()=>Q(t),t.or=r=>fe([t,r]),t.and=r=>qi(t,r),t.transform=r=>Ku(t,jy(r)),t.default=r=>vT(t,r),t.prefault=r=>bT(t,r),t.catch=r=>ST(t,r),t.pipe=r=>Ku(t,r),t.readonly=()=>PT(t),t.describe=r=>{let n=t.clone();return Uo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Uo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Uo.get(t);let n=t.clone();return Uo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Dy=w("_ZodString",(t,e)=>{Oi.init(t,e),Se.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Du(...n)),t.includes=(...n)=>t.check(Mu(...n)),t.startsWith=(...n)=>t.check(ju(...n)),t.endsWith=(...n)=>t.check(Nu(...n)),t.min=(...n)=>t.check(Mn(...n)),t.max=(...n)=>t.check(Li(...n)),t.length=(...n)=>t.check(Fi(...n)),t.nonempty=(...n)=>t.check(Mn(1,...n)),t.lowercase=n=>t.check(zu(n)),t.uppercase=n=>t.check(Ou(n)),t.trim=()=>t.check(Fu()),t.normalize=(...n)=>t.check(Lu(...n)),t.toLowerCase=()=>t.check(Zu()),t.toUpperCase=()=>t.check(Uu())}),FP=w("ZodString",(t,e)=>{Oi.init(t,e),Dy.init(t,e),t.email=r=>t.check(Fg(ZP,r)),t.url=r=>t.check(Bg(UP,r)),t.jwt=r=>t.check(iy(nT,r)),t.emoji=r=>t.check(Wg(qP,r)),t.guid=r=>t.check(Cu(Iy,r)),t.uuid=r=>t.check(Zg(Ui,r)),t.uuidv4=r=>t.check(Ug(Ui,r)),t.uuidv6=r=>t.check(qg(Ui,r)),t.uuidv7=r=>t.check(Vg(Ui,r)),t.nanoid=r=>t.check(Hg(VP,r)),t.guid=r=>t.check(Cu(Iy,r)),t.cuid=r=>t.check(Kg(BP,r)),t.cuid2=r=>t.check(Jg(WP,r)),t.ulid=r=>t.check(Gg(HP,r)),t.base64=r=>t.check(ny(eT,r)),t.base64url=r=>t.check(oy(tT,r)),t.xid=r=>t.check(Yg(KP,r)),t.ksuid=r=>t.check(Qg(JP,r)),t.ipv4=r=>t.check(Xg(GP,r)),t.ipv6=r=>t.check(ey(YP,r)),t.cidrv4=r=>t.check(ty(QP,r)),t.cidrv6=r=>t.check(ry(XP,r)),t.e164=r=>t.check(sy(rT,r)),t.datetime=r=>t.check(qu(r)),t.date=r=>t.check(Vu(r)),t.time=r=>t.check(Bu(r)),t.duration=r=>t.check(Wu(r))});function b(t){return Lg(FP,t)}var ve=w("ZodStringFormat",(t,e)=>{he.init(t,e),Dy.init(t,e)}),ZP=w("ZodEmail",(t,e)=>{Kh.init(t,e),ve.init(t,e)});var Iy=w("ZodGUID",(t,e)=>{Wh.init(t,e),ve.init(t,e)});var Ui=w("ZodUUID",(t,e)=>{Hh.init(t,e),ve.init(t,e)});var UP=w("ZodURL",(t,e)=>{Jh.init(t,e),ve.init(t,e)});var qP=w("ZodEmoji",(t,e)=>{Gh.init(t,e),ve.init(t,e)});var VP=w("ZodNanoID",(t,e)=>{Yh.init(t,e),ve.init(t,e)});var BP=w("ZodCUID",(t,e)=>{Qh.init(t,e),ve.init(t,e)});var WP=w("ZodCUID2",(t,e)=>{Xh.init(t,e),ve.init(t,e)});var HP=w("ZodULID",(t,e)=>{eg.init(t,e),ve.init(t,e)});var KP=w("ZodXID",(t,e)=>{tg.init(t,e),ve.init(t,e)});var JP=w("ZodKSUID",(t,e)=>{rg.init(t,e),ve.init(t,e)});var GP=w("ZodIPv4",(t,e)=>{ag.init(t,e),ve.init(t,e)});var YP=w("ZodIPv6",(t,e)=>{cg.init(t,e),ve.init(t,e)});var QP=w("ZodCIDRv4",(t,e)=>{ug.init(t,e),ve.init(t,e)});var XP=w("ZodCIDRv6",(t,e)=>{lg.init(t,e),ve.init(t,e)});var eT=w("ZodBase64",(t,e)=>{pg.init(t,e),ve.init(t,e)});var tT=w("ZodBase64URL",(t,e)=>{fg.init(t,e),ve.init(t,e)});var rT=w("ZodE164",(t,e)=>{mg.init(t,e),ve.init(t,e)});var nT=w("ZodJWT",(t,e)=>{hg.init(t,e),ve.init(t,e)});var zy=w("ZodNumber",(t,e)=>{Ru.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(ji(n,o)),t.gte=(n,o)=>t.check(Vo(n,o)),t.min=(n,o)=>t.check(Vo(n,o)),t.lt=(n,o)=>t.check(Mi(n,o)),t.lte=(n,o)=>t.check(qo(n,o)),t.max=(n,o)=>t.check(qo(n,o)),t.int=n=>t.check(Ay(n)),t.safe=n=>t.check(Ay(n)),t.positive=n=>t.check(ji(0,n)),t.nonnegative=n=>t.check(Vo(0,n)),t.negative=n=>t.check(Mi(0,n)),t.nonpositive=n=>t.check(qo(0,n)),t.multipleOf=(n,o)=>t.check(Ni(n,o)),t.step=(n,o)=>t.check(Ni(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ae(t){return dy(zy,t)}var oT=w("ZodNumberFormat",(t,e)=>{gg.init(t,e),zy.init(t,e)});function Ay(t){return py(oT,t)}var sT=w("ZodBoolean",(t,e)=>{yg.init(t,e),Se.init(t,e)});function Pe(t){return fy(sT,t)}var iT=w("ZodNull",(t,e)=>{vg.init(t,e),Se.init(t,e)});function Ju(t){return my(iT,t)}var aT=w("ZodUnknown",(t,e)=>{_g.init(t,e),Se.init(t,e)});function _e(){return hy(aT)}var cT=w("ZodNever",(t,e)=>{bg.init(t,e),Se.init(t,e)});function uT(t){return gy(cT,t)}var lT=w("ZodArray",(t,e)=>{wg.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Mn(r,n)),t.nonempty=r=>t.check(Mn(1,r)),t.max=(r,n)=>t.check(Li(r,n)),t.length=(r,n)=>t.check(Fi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return yy(lT,t,e)}var Oy=w("ZodObject",(t,e)=>{xg.init(t,e),Se.init(t,e),ie.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ge(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:_e()}),t.loose=()=>t.clone({...t._zod.def,catchall:_e()}),t.strict=()=>t.clone({...t._zod.def,catchall:uT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ie.extend(t,r),t.merge=r=>ie.merge(t,r),t.pick=r=>ie.pick(t,r),t.omit=r=>ie.omit(t,r),t.partial=(...r)=>ie.partial(Ny,t,r[0]),t.required=(...r)=>ie.required(Ly,t,r[0])});function I(t,e){let r={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new Oy(r)}function qe(t,e){return new Oy({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ie.normalizeParams(e)})}var My=w("ZodUnion",(t,e)=>{Iu.init(t,e),Se.init(t,e),t.options=e.options});function fe(t,e){return new My({type:"union",options:t,...ie.normalizeParams(e)})}var dT=w("ZodDiscriminatedUnion",(t,e)=>{My.init(t,e),Sg.init(t,e)});function Gu(t,e,r){return new dT({type:"union",options:e,discriminator:t,...ie.normalizeParams(r)})}var pT=w("ZodIntersection",(t,e)=>{$g.init(t,e),Se.init(t,e)});function qi(t,e){return new pT({type:"intersection",left:t,right:e})}var fT=w("ZodRecord",(t,e)=>{kg.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new fT({type:"record",keyType:t,valueType:e,...ie.normalizeParams(r)})}var Hu=w("ZodEnum",(t,e)=>{Pg.init(t,e),Se.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Hu({...e,checks:[],...ie.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Hu({...e,checks:[],...ie.normalizeParams(o),entries:s})}});function Ge(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Hu({type:"enum",entries:r,...ie.normalizeParams(e)})}var mT=w("ZodLiteral",(t,e)=>{Tg.init(t,e),Se.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function C(t,e){return new mT({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var hT=w("ZodTransform",(t,e)=>{Eg.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ie.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ie.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function jy(t){return new hT({type:"transform",transform:t})}var Ny=w("ZodOptional",(t,e)=>{Rg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new Ny({type:"optional",innerType:t})}var gT=w("ZodNullable",(t,e)=>{Ig.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Cy(t){return new gT({type:"nullable",innerType:t})}var yT=w("ZodDefault",(t,e)=>{Ag.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function vT(t,e){return new yT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var _T=w("ZodPrefault",(t,e)=>{Cg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bT(t,e){return new _T({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Ly=w("ZodNonOptional",(t,e)=>{Dg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function wT(t,e){return new Ly({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var xT=w("ZodCatch",(t,e)=>{zg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function ST(t,e){return new xT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var $T=w("ZodPipe",(t,e)=>{Og.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function Ku(t,e){return new $T({type:"pipe",in:t,out:e})}var kT=w("ZodReadonly",(t,e)=>{Mg.init(t,e),Se.init(t,e)});function PT(t){return new kT({type:"readonly",innerType:t})}var Fy=w("ZodCustom",(t,e)=>{jg.init(t,e),Se.init(t,e)});function TT(t){let e=new je({check:"custom"});return e._zod.check=t,e}function Zy(t,e){return vy(Fy,t??(()=>!0),e)}function ET(t,e={}){return _y(Fy,t,e)}function RT(t){let e=TT(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ie.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ie.issue(o))}},t(r.value,r)));return e}function Yu(t,e){return Ku(jy(t),e)}at(Ng());var Xu="2025-11-25";var Uy=[Xu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],dr="io.modelcontextprotocol/related-task",Bi="2.0",Ee=Zy(t=>t!==null&&(typeof t=="object"||typeof t=="function")),qy=fe([b(),ae().int()]),Vy=b(),YU=qe({ttl:fe([ae(),Ju()]).optional(),pollInterval:ae().optional()}),IT=I({ttl:ae().optional()}),AT=I({taskId:b()}),el=qe({progressToken:qy.optional(),[dr]:AT.optional()}),nt=I({_meta:el.optional()}),Ko=nt.extend({task:IT.optional()}),By=t=>Ko.safeParse(t).success,Re=I({method:b(),params:nt.loose().optional()}),ct=I({_meta:el.optional()}),ut=I({method:b(),params:ct.loose().optional()}),Ie=qe({_meta:el.optional()}),Wi=fe([b(),ae().int()]),Wy=I({jsonrpc:C(Bi),id:Wi,...Re.shape}).strict(),tl=t=>Wy.safeParse(t).success,Hy=I({jsonrpc:C(Bi),...ut.shape}).strict(),Ky=t=>Hy.safeParse(t).success,rl=I({jsonrpc:C(Bi),id:Wi,result:Ie}).strict(),Jo=t=>rl.safeParse(t).success;var X;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(X||(X={}));var nl=I({jsonrpc:C(Bi),id:Wi.optional(),error:I({code:ae().int(),message:b(),data:_e().optional()})}).strict();var Jy=t=>nl.safeParse(t).success;var Gy=fe([Wy,Hy,rl,nl]),QU=fe([rl,nl]),Hi=Ie.strict(),CT=ct.extend({requestId:Wi.optional(),reason:b().optional()}),Ki=ut.extend({method:C("notifications/cancelled"),params:CT}),DT=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Ge(["light","dark"]).optional()}),Go=I({icons:Q(DT).optional()}),Nn=I({name:b(),title:b().optional()}),Yy=Nn.extend({...Nn.shape,...Go.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),zT=qi(I({applyDefaults:Pe().optional()}),be(b(),_e())),OT=Yu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,qi(I({form:zT.optional(),url:Ee.optional()}),be(b(),_e()).optional())),MT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({sampling:qe({createMessage:Ee.optional()}).optional(),elicitation:qe({create:Ee.optional()}).optional()}).optional()}),jT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({tools:qe({call:Ee.optional()}).optional()}).optional()}),NT=I({experimental:be(b(),Ee).optional(),sampling:I({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:OT.optional(),roots:I({listChanged:Pe().optional()}).optional(),tasks:MT.optional()}),LT=nt.extend({protocolVersion:b(),capabilities:NT,clientInfo:Yy}),ol=Re.extend({method:C("initialize"),params:LT});var FT=I({experimental:be(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:I({listChanged:Pe().optional()}).optional(),resources:I({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:I({listChanged:Pe().optional()}).optional(),tasks:jT.optional()}),ZT=Ie.extend({protocolVersion:b(),capabilities:FT,serverInfo:Yy,instructions:b().optional()}),sl=ut.extend({method:C("notifications/initialized"),params:ct.optional()});var Ji=Re.extend({method:C("ping"),params:nt.optional()}),UT=I({progress:ae(),total:xe(ae()),message:xe(b())}),qT=I({...ct.shape,...UT.shape,progressToken:qy}),Gi=ut.extend({method:C("notifications/progress"),params:qT}),VT=nt.extend({cursor:Vy.optional()}),Yo=Re.extend({params:VT.optional()}),Qo=Ie.extend({nextCursor:Vy.optional()}),BT=Ge(["working","input_required","completed","failed","cancelled"]),Xo=I({taskId:b(),status:BT,ttl:fe([ae(),Ju()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ae()),statusMessage:xe(b())}),Ln=Ie.extend({task:Xo}),WT=ct.merge(Xo),es=ut.extend({method:C("notifications/tasks/status"),params:WT}),Yi=Re.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Qi=Ie.merge(Xo),Xi=Re.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),XU=Ie.loose(),ea=Yo.extend({method:C("tasks/list")}),ta=Qo.extend({tasks:Q(Xo)}),ra=Re.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),Qy=Ie.merge(Xo),Xy=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),ev=Xy.extend({text:b()}),il=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),tv=Xy.extend({blob:il}),ts=Ge(["user","assistant"]),Fn=I({audience:Q(ts).optional(),priority:ae().min(0).max(1).optional(),lastModified:Wo.datetime({offset:!0}).optional()}),rv=I({...Nn.shape,...Go.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),HT=I({...Nn.shape,...Go.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),KT=Yo.extend({method:C("resources/list")}),JT=Qo.extend({resources:Q(rv)}),GT=Yo.extend({method:C("resources/templates/list")}),YT=Qo.extend({resourceTemplates:Q(HT)}),al=nt.extend({uri:b()}),QT=al,XT=Re.extend({method:C("resources/read"),params:QT}),eE=Ie.extend({contents:Q(fe([ev,tv]))}),tE=ut.extend({method:C("notifications/resources/list_changed"),params:ct.optional()}),rE=al,nE=Re.extend({method:C("resources/subscribe"),params:rE}),oE=al,sE=Re.extend({method:C("resources/unsubscribe"),params:oE}),iE=ct.extend({uri:b()}),aE=ut.extend({method:C("notifications/resources/updated"),params:iE}),cE=I({name:b(),description:xe(b()),required:xe(Pe())}),uE=I({...Nn.shape,...Go.shape,description:xe(b()),arguments:xe(Q(cE)),_meta:xe(qe({}))}),lE=Yo.extend({method:C("prompts/list")}),dE=Qo.extend({prompts:Q(uE)}),pE=nt.extend({name:b(),arguments:be(b(),b()).optional()}),fE=Re.extend({method:C("prompts/get"),params:pE}),cl=I({type:C("text"),text:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),ul=I({type:C("image"),data:il,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),ll=I({type:C("audio"),data:il,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),mE=I({type:C("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),hE=I({type:C("resource"),resource:fe([ev,tv]),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),gE=rv.extend({type:C("resource_link")}),dl=fe([cl,ul,ll,gE,hE]),yE=I({role:ts,content:dl}),vE=Ie.extend({description:b().optional(),messages:Q(yE)}),_E=ut.extend({method:C("notifications/prompts/list_changed"),params:ct.optional()}),bE=I({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),wE=I({taskSupport:Ge(["required","optional","forbidden"]).optional()}),nv=I({...Nn.shape,...Go.shape,description:b().optional(),inputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Q(b()).optional()}).catchall(_e()),outputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Q(b()).optional()}).catchall(_e()).optional(),annotations:bE.optional(),execution:wE.optional(),_meta:be(b(),_e()).optional()}),pl=Yo.extend({method:C("tools/list")}),xE=Qo.extend({tools:Q(nv)}),na=Ie.extend({content:Q(dl).default([]),structuredContent:be(b(),_e()).optional(),isError:Pe().optional()}),eq=na.or(Ie.extend({toolResult:_e()})),SE=Ko.extend({name:b(),arguments:be(b(),_e()).optional()}),rs=Re.extend({method:C("tools/call"),params:SE}),$E=ut.extend({method:C("notifications/tools/list_changed"),params:ct.optional()}),tq=I({autoRefresh:Pe().default(!0),debounceMs:ae().int().nonnegative().default(300)}),ns=Ge(["debug","info","notice","warning","error","critical","alert","emergency"]),kE=nt.extend({level:ns}),fl=Re.extend({method:C("logging/setLevel"),params:kE}),PE=ct.extend({level:ns,logger:b().optional(),data:_e()}),TE=ut.extend({method:C("notifications/message"),params:PE}),EE=I({name:b().optional()}),RE=I({hints:Q(EE).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),IE=I({mode:Ge(["auto","required","none"]).optional()}),AE=I({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(dl).default([]),structuredContent:I({}).loose().optional(),isError:Pe().optional(),_meta:be(b(),_e()).optional()}),CE=Gu("type",[cl,ul,ll]),Vi=Gu("type",[cl,ul,ll,mE,AE]),DE=I({role:ts,content:fe([Vi,Q(Vi)]),_meta:be(b(),_e()).optional()}),zE=Ko.extend({messages:Q(DE),modelPreferences:RE.optional(),systemPrompt:b().optional(),includeContext:Ge(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:Q(b()).optional(),metadata:Ee.optional(),tools:Q(nv).optional(),toolChoice:IE.optional()}),OE=Re.extend({method:C("sampling/createMessage"),params:zE}),ml=Ie.extend({model:b(),stopReason:xe(Ge(["endTurn","stopSequence","maxTokens"]).or(b())),role:ts,content:CE}),hl=Ie.extend({model:b(),stopReason:xe(Ge(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:ts,content:fe([Vi,Q(Vi)])}),ME=I({type:C("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),jE=I({type:C("string"),title:b().optional(),description:b().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:Ge(["email","uri","date","date-time"]).optional(),default:b().optional()}),NE=I({type:Ge(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),LE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),FE=I({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),ZE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),UE=fe([LE,FE]),qE=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({type:C("string"),enum:Q(b())}),default:Q(b()).optional()}),VE=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({anyOf:Q(I({const:b(),title:b()}))}),default:Q(b()).optional()}),BE=fe([qE,VE]),WE=fe([ZE,UE,BE]),HE=fe([WE,ME,jE,NE]),KE=Ko.extend({mode:C("form").optional(),message:b(),requestedSchema:I({type:C("object"),properties:be(b(),HE),required:Q(b()).optional()})}),JE=Ko.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),GE=fe([KE,JE]),YE=Re.extend({method:C("elicitation/create"),params:GE}),QE=ct.extend({elicitationId:b()}),XE=ut.extend({method:C("notifications/elicitation/complete"),params:QE}),oa=Ie.extend({action:Ge(["accept","decline","cancel"]),content:Yu(t=>t===null?void 0:t,be(b(),fe([b(),ae(),Pe(),Q(b())])).optional())}),eR=I({type:C("ref/resource"),uri:b()});var tR=I({type:C("ref/prompt"),name:b()}),rR=nt.extend({ref:fe([tR,eR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),nR=Re.extend({method:C("completion/complete"),params:rR});var oR=Ie.extend({completion:qe({values:Q(b()).max(100),total:xe(ae().int()),hasMore:xe(Pe())})}),sR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),iR=Re.extend({method:C("roots/list"),params:nt.optional()}),gl=Ie.extend({roots:Q(sR)}),aR=ut.extend({method:C("notifications/roots/list_changed"),params:ct.optional()}),rq=fe([Ji,ol,nR,fl,fE,lE,KT,GT,XT,nE,sE,rs,pl,Yi,Xi,ea,ra]),nq=fe([Ki,Gi,sl,aR,es]),oq=fe([Hi,ml,hl,oa,gl,Qi,ta,Ln]),sq=fe([Ji,OE,YE,iR,Yi,Xi,ea,ra]),iq=fe([Ki,Gi,TE,aE,tE,$E,_E,es,XE]),aq=fe([Hi,ZT,oR,vE,dE,JT,YT,eE,na,xE,Qi,ta,Ln]),W=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Qu(o.elicitations,r)}return new t(e,r,n)}},Qu=class extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function pr(t){return t==="completed"||t==="failed"||t==="cancelled"}var sv=Symbol("Let zodToJsonSchema decide on which parser to use");var ov={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},iv=t=>typeof t=="string"?{...ov,name:t}:{...ov,...t};var av=t=>{let e=iv(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function yl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,yl(t,e,n,o)}var sa=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?sa(e,t.currentPath):e.join("/")}}function cv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==P.ZodAny&&(r.items=L(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function uv(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function lv(){return{type:"boolean"}}function ia(t,e){return L(t.type._def,e)}var dv=(t,e)=>L(t.innerType._def,e);function vl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>vl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return cR(t,e)}}var cR=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function pv(t,e){return{...L(t.innerType._def,e),default:t.defaultValue()}}function fv(t,e){return e.effectStrategy==="input"?L(t.schema._def,e):we(e)}function mv(t){return{type:"string",enum:Array.from(t.values)}}var uR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function hv(t,e){let r=[L(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),L(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(uR(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function gv(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var _l,yt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(_l===void 0&&(_l=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_l),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function aa(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":vt(r,"email",n.message,e);break;case"format:idn-email":vt(r,"idn-email",n.message,e);break;case"pattern:zod":Ve(r,yt.email,n.message,e);break}break;case"url":vt(r,"uri",n.message,e);break;case"uuid":vt(r,"uuid",n.message,e);break;case"regex":Ve(r,n.regex,n.message,e);break;case"cuid":Ve(r,yt.cuid,n.message,e);break;case"cuid2":Ve(r,yt.cuid2,n.message,e);break;case"startsWith":Ve(r,RegExp(`^${bl(n.value,e)}`),n.message,e);break;case"endsWith":Ve(r,RegExp(`${bl(n.value,e)}$`),n.message,e);break;case"datetime":vt(r,"date-time",n.message,e);break;case"date":vt(r,"date",n.message,e);break;case"time":vt(r,"time",n.message,e);break;case"duration":vt(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ve(r,RegExp(bl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&vt(r,"ipv4",n.message,e),n.version!=="v4"&&vt(r,"ipv6",n.message,e);break}case"base64url":Ve(r,yt.base64url,n.message,e);break;case"jwt":Ve(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ve(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ve(r,yt.ipv6Cidr,n.message,e);break}case"emoji":Ve(r,yt.emoji(),n.message,e);break;case"ulid":{Ve(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{vt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ve(r,yt.base64,n.message,e);break}}break}case"nanoid":Ve(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function bl(t,e){return e.patternStrategy==="escape"?dR(t):t}var lR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function dR(t){let e="";for(let r=0;r<t.length;r++)lR.has(t[r])||(e+="\\"),e+=t[r];return e}function vt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ee(t,"format",e,r,n)}function Ve(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:yv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",yv(e,n),r,n)}function yv(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
180
234
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
181
235
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
182
236
  `:`[${n[c]}\r
183
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function qi(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Zi(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Li(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function _y(t,e){if(e.mapStrategy==="record")return qi(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||be(e),n=M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function vy(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function xy(t){return t.target==="openAi"?void 0:{not:be({...t,currentPath:[...t.currentPath,"not"]})}}function by(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Go={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function $y(t,e){if(e.target==="openApi3")return wy(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Go&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Go[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return wy(t,e)}var wy=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Sy(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Go[t.innerType._def.typeName],nullable:!0}:{type:[Go[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ky(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ju(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function Ty(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=kP(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=M(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=SP(t,e);return i!==void 0&&(n.additionalProperties=i),n}function SP(t,e){if(t.catchall._def.typeName!=="ZodNever")return M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function kP(t){try{return t.isOptional()}catch{return!0}}var Py=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return M(t.innerType._def,e);let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:be(e)},r]}:be(e)};var Ey=(t,e)=>{if(e.pipeStrategy==="input")return M(t.in._def,e);if(e.pipeStrategy==="output")return M(t.out._def,e);let r=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Ry(t,e){return M(t.type._def,e)}function zy(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Cy(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ay(t){return{not:be(t)}}function Iy(t){return be(t)}var Dy=(t,e)=>M(t.innerType._def,e);var Oy=(t,e,r)=>{switch(e){case S.ZodString:return Zi(t,r);case S.ZodNumber:return ky(t,r);case S.ZodObject:return Ty(t,r);case S.ZodBigInt:return uy(t,r);case S.ZodBoolean:return ly();case S.ZodDate:return Lu(t,r);case S.ZodUndefined:return Ay(r);case S.ZodNull:return by(r);case S.ZodArray:return cy(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return $y(t,r);case S.ZodIntersection:return hy(t,r);case S.ZodTuple:return Cy(t,r);case S.ZodRecord:return qi(t,r);case S.ZodLiteral:return gy(t,r);case S.ZodEnum:return my(t);case S.ZodNativeEnum:return vy(t);case S.ZodNullable:return Sy(t,r);case S.ZodOptional:return Py(t,r);case S.ZodMap:return _y(t,r);case S.ZodSet:return zy(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Ry(t,r);case S.ZodNaN:case S.ZodNever:return xy(r);case S.ZodEffects:return fy(t,r);case S.ZodAny:return be(r);case S.ZodUnknown:return Iy(r);case S.ZodDefault:return py(t,r);case S.ZodBranded:return Li(t,r);case S.ZodReadonly:return Dy(t,r);case S.ZodCatch:return dy(t,r);case S.ZodPipeline:return Ey(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==sy)return a}if(n&&!r){let a=TP(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Oy(t,t.typeName,e),i=typeof s=="function"?M(s(),e):s;if(i&&PP(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var TP=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ji(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),be(e)):e.$refStrategy==="seen"?be(e):void 0}},PP=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Fi=(t,e)=>{let r=ay(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:M(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??be(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=M(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??be(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Fu(t){let r=xi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=xg(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Uu(t,e){let r=ar(t,e);if(!r.success)throw r.error;return r.data}var EP=6e4,Ui=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Pi,r=>{this._oncancel(r)}),this.setNotificationHandler(Ri,r=>{this._onprogress(r)}),this.setRequestHandler(Ei,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zi,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ai,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new W(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new W(X.InvalidParams,`Task not found: ${s}`);if(!ur(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(ur(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[cr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ii,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new W(X.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Oi,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,`Task not found: ${r.params.taskId}`);if(ur(o.status))throw new W(X.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(X.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof W?o:new W(X.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),W.fromError(X.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Lo(s)||Jg(s)?this._onresponse(s):wu(s)?this._onrequest(s,i):Gg(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=W.fromError(X.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[cr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:X.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Wg(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let g=f.relatedTask?.taskId??s;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:X.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Lo(e))n(e);else{let i=new W(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Lo(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Lo(e))o(e);else{let i=W.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Dn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(X.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},ur(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new W(X.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new W(X.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[cr]:c}});let g=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let w=_ instanceof W?_:new W(X.RequestTimeout,String(_));l(w)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let w=ar(r,_.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let y=n?.timeout??EP,m=()=>g(W.fromError(X.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,n?.maxTotalTimeout,m,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let _=w=>{let k=this._responseHandlers.get(p);k?k(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(b,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),l(w)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ci,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Di,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Yg,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[cr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[cr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[cr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Fu(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Uu(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Fu(e);this._notificationHandlers.set(n,o=>{let s=Uu(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&wu(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new W(X.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new W(X.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new W(X.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Vo.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ur(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new W(X.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ur(a.status))throw new W(X.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Vo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ur(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function My(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ny(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];My(i)&&My(s)?r[o]={...i,...s}:r[o]=s}return r}var $x=ap(Ed(),1),Sx=ap(wx(),1);function _I(){let t=new $x.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Sx.default)(t),t}var Ta=class{constructor(e){this._ajv=e??_I()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Pa=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function kx(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Tx(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ea=class extends Ui{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ho.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ta,this.setRequestHandler(ku,n=>this._oninitialize(n)),this.setNotificationHandler(Tu,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Du,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ho.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Pa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ny(this._capabilities,e)}setRequestHandler(e,r){let o=xi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(An(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=ar(Bo,c);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new W(X.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let g=ar(Dn,p);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new W(X.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}let f=ar(Mi,p);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new W(X.InvalidParams,`Invalid tools/call result: ${g}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Tx(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&kx(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Fg.includes(r)?r:xu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ti)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Mu,r):this.request({method:"sampling/createMessage",params:e},Ou,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Ni,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Ni,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new W(X.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof W?i:new W(X.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Nu,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Ex from"node:process";var Ra=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
184
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),vI(r)}clear(){this._buffer=void 0}};function vI(t){return Kg.parse(JSON.parse(t))}function Px(t){return JSON.stringify(t)+`
185
- `}var za=class{constructor(e=Ex.stdin,r=Ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ra,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Px(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as $D}from"url";var Md={};We(Md,{AI_CHAT_TIMEOUT_MS:()=>Ix,getTools:()=>bI,handleTool:()=>kI});import{readFileSync as Rx}from"fs";function J(t){let e=Fi(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var xI=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata")}).optional(),zx=h.object({provider:h.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:h.string().describe("Chat prompt to send"),model:h.string().optional().describe("Model override"),system:h.string().optional().describe("System prompt"),files:h.array(h.string()).optional().describe("File paths to include as context"),save_as_document:xI.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Cx=h.object({provider:h.string().describe("Provider ID"),file_paths:h.array(h.string()).min(1).describe("File paths to analyze"),question:h.string().describe("Question to ask about the files"),save_to_file:h.string().optional().describe("Path to save the analysis result")}),Ax=h.object({providers:h.array(h.string()).min(1).describe("List of provider IDs to compare"),prompt:h.string().describe("Prompt to send to all providers"),aggregate_provider:h.string().optional().describe("Provider ID to synthesize all responses into a unified document. If omitted, returns raw comparisons only."),aggregate_prompt:h.string().optional().describe("Custom synthesis prompt. Default: synthesize and identify agreements/disagreements.")}),Ix=9e4;function bI(){return[{name:"ai_chat",title:"AI Chat",description:"Chat with a specific AI provider. Sends a prompt and returns the response. Optionally saves the response as a workspace document.",inputSchema:J(zx)},{name:"ai_analyze_files",title:"Analyze Files with AI",description:"Analyze files with an AI provider. Reads files from disk, sends contents with a question, and optionally saves the result.",inputSchema:J(Cx)},{name:"ai_compare",title:"Compare AI Providers",description:"Send the same prompt to multiple providers and return a comparison. Optionally aggregate results into a unified synthesis using a designated provider.",inputSchema:J(Ax)}]}async function wI(t,e){let r=zx.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("chat",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=s.chat({prompt:r.prompt,model:r.model,system:r.system,files:r.files?.map(l=>{let d=Ft(l,n);return{path:d,content:Rx(d,"utf-8")}})}),a=e.aiChatTimeoutMs??Ix,c;try{c=await Promise.race([i,new Promise((l,d)=>setTimeout(()=>d(new Error("__AI_CHAT_TIMEOUT__")),a))])}catch(l){if(q(l)==="__AI_CHAT_TIMEOUT__"&&e.jobManager){let p=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5});return{content:[{type:"text",text:`\u23F1 Provider "${r.provider}" timed out after ${a/1e3}s. Auto-submitted as background job.
237
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function ca(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===P.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===P.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=aa(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===P.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ia(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function vv(t,e){if(e.mapStrategy==="record")return ca(t,e);let r=L(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function _v(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function bv(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function wv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var os={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Sv(t,e){if(e.target==="openApi3")return xv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in os&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=os[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return xv(t,e)}var xv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function $v(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:os[t.innerType._def.typeName],nullable:!0}:{type:[os[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=L(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function kv(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",yl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function Pv(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=fR(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=L(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=pR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function pR(t,e){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function fR(t){try{return t.isOptional()}catch{return!0}}var Tv=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return L(t.innerType._def,e);let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Ev=(t,e)=>{if(e.pipeStrategy==="input")return L(t.in._def,e);if(e.pipeStrategy==="output")return L(t.out._def,e);let r=L(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=L(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Rv(t,e){return L(t.type._def,e)}function Iv(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Av(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:L(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Cv(t){return{not:we(t)}}function Dv(t){return we(t)}var zv=(t,e)=>L(t.innerType._def,e);var Ov=(t,e,r)=>{switch(e){case P.ZodString:return aa(t,r);case P.ZodNumber:return kv(t,r);case P.ZodObject:return Pv(t,r);case P.ZodBigInt:return uv(t,r);case P.ZodBoolean:return lv();case P.ZodDate:return vl(t,r);case P.ZodUndefined:return Cv(r);case P.ZodNull:return wv(r);case P.ZodArray:return cv(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return Sv(t,r);case P.ZodIntersection:return hv(t,r);case P.ZodTuple:return Av(t,r);case P.ZodRecord:return ca(t,r);case P.ZodLiteral:return gv(t,r);case P.ZodEnum:return mv(t);case P.ZodNativeEnum:return _v(t);case P.ZodNullable:return $v(t,r);case P.ZodOptional:return Tv(t,r);case P.ZodMap:return vv(t,r);case P.ZodSet:return Iv(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return Rv(t,r);case P.ZodNaN:case P.ZodNever:return bv(r);case P.ZodEffects:return fv(t,r);case P.ZodAny:return we(r);case P.ZodUnknown:return Dv(r);case P.ZodDefault:return pv(t,r);case P.ZodBranded:return ia(t,r);case P.ZodReadonly:return zv(t,r);case P.ZodCatch:return dv(t,r);case P.ZodPipeline:return Ev(t,r);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(n=>{})(e)}};function L(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==sv)return a}if(n&&!r){let a=mR(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Ov(t,t.typeName,e),i=typeof s=="function"?L(s(),e):s;if(i&&hR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var mR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sa(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},hR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ua=(t,e)=>{let r=av(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:L(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=L(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function wl(t){let r=Zi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=by(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function xl(t,e){let r=lr(t,e);if(!r.success)throw r.error;return r.data}var gR=6e4,la=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ki,r=>{this._oncancel(r)}),this.setNotificationHandler(Gi,r=>{this._onprogress(r)}),this.setRequestHandler(Ji,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Yi,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Xi,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new W(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new W(X.InvalidParams,`Task not found: ${s}`);if(!pr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(pr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[dr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ea,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new W(X.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ra,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,`Task not found: ${r.params.taskId}`);if(pr(o.status))throw new W(X.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(X.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof W?o:new W(X.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),W.fromError(X.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Jo(s)||Jy(s)?this._onresponse(s):tl(s)?this._onrequest(s,i):Ky(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=W.fromError(X.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[dr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:X.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=By(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:X.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Jo(e))n(e);else{let i=new W(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Jo(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Jo(e))o(e);else{let i=W.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Ln,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(X.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},pr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new W(X.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new W(X.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[dr]:c}});let m=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let v=S instanceof W?S:new W(X.RequestTimeout,String(S));l(v)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let v=lr(r,S.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??gR,y=()=>m(W.fromError(X.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let S=v=>{let k=this._responseHandlers.get(p);k?k(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qi,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ta,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Qy,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[dr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[dr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[dr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=wl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=xl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=wl(e);this._notificationHandlers.set(n,o=>{let s=xl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&tl(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new W(X.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new W(X.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new W(X.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=es.parse({method:"notifications/tasks/status",params:a});await this.notification(c),pr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new W(X.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(pr(a.status))throw new W(X.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=es.parse({method:"notifications/tasks/status",params:c});await this.notification(u),pr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Mv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jv(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Mv(i)&&Mv(s)?r[o]={...i,...s}:r[o]=s}return r}var Sw=Jp(ap(),1),$w=Jp(xw(),1);function iO(){let t=new Sw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$w.default)(t),t}var Ha=class{constructor(e){this._ajv=e??iO()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ka=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function kw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Pw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ja=class extends la{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ns.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ha,this.setRequestHandler(ol,n=>this._oninitialize(n)),this.setNotificationHandler(sl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(fl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ns.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ka(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=jv(this._capabilities,e)}setRequestHandler(e,r){let o=Zi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(jn(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=lr(rs,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new W(X.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=lr(Ln,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new W(X.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=lr(na,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new W(X.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Pw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&kw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Uy.includes(r)?r:Xu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Hi)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},hl,r):this.request({method:"sampling/createMessage",params:e},ml,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},oa,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},oa,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new W(X.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof W?i:new W(X.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},gl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Ew from"node:process";var Ga=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
238
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),aO(r)}clear(){this._buffer=void 0}};function aO(t){return Gy.parse(JSON.parse(t))}function Tw(t){return JSON.stringify(t)+`
239
+ `}var Ya=class{constructor(e=Ew.stdin,r=Ew.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ga,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Tw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as Kj}from"url";var hp={};Ze(hp,{AI_CHAT_TIMEOUT_MS:()=>Dw,getTools:()=>uO,handleTool:()=>fO});import{readFileSync as Rw}from"fs";function V(t){let e=ua(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var cO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata")}).optional(),Iw=h.object({provider:h.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:h.string().describe("Chat prompt to send"),model:h.string().optional().describe("Model override"),system:h.string().optional().describe("System prompt"),files:h.array(h.string()).optional().describe("File paths to include as context"),save_as_document:cO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Aw=h.object({provider:h.string().describe("Provider ID"),file_paths:h.array(h.string()).min(1).describe("File paths to analyze"),question:h.string().describe("Question to ask about the files"),save_to_file:h.string().optional().describe("Path to save the analysis result")}),Cw=h.object({providers:h.array(h.string()).min(1).describe("List of provider IDs to compare"),prompt:h.string().describe("Prompt to send to all providers"),aggregate_provider:h.string().optional().describe("Provider ID to synthesize all responses into a unified document. If omitted, returns raw comparisons only."),aggregate_prompt:h.string().optional().describe("Custom synthesis prompt. Default: synthesize and identify agreements/disagreements.")}),Dw=9e4;function uO(){return[{name:"ai_chat",title:"AI Chat",description:"Chat with a specific AI provider. Sends a prompt and returns the response. Optionally saves the response as a workspace document.",inputSchema:V(Iw)},{name:"ai_analyze_files",title:"Analyze Files with AI",description:"Analyze files with an AI provider. Reads files from disk, sends contents with a question, and optionally saves the result.",inputSchema:V(Aw)},{name:"ai_compare",title:"Compare AI Providers",description:"Send the same prompt to multiple providers and return a comparison. Optionally aggregate results into a unified synthesis using a designated provider.",inputSchema:V(Cw)}]}async function lO(t,e){let r=Iw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("chat",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=s.chat({prompt:r.prompt,model:r.model,system:r.system,files:r.files?.map(l=>{let d=Bt(l,n);return{path:d,content:Rw(d,"utf-8")}})}),a=e.aiChatTimeoutMs??Dw,c;try{c=await Promise.race([i,new Promise((l,d)=>setTimeout(()=>d(new Error("__AI_CHAT_TIMEOUT__")),a))])}catch(l){if(M(l)==="__AI_CHAT_TIMEOUT__"&&e.jobManager){let p=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5});return{content:[{type:"text",text:`\u23F1 Provider "${r.provider}" timed out after ${a/1e3}s. Auto-submitted as background job.
186
240
 
187
241
  **Job ID:** ${p}
188
242
 
189
243
  Use \`cli_job_status\` to check progress.`}]}}throw l}let u="";if(r.save_as_document&&e.documentManager)try{u=`
190
244
  **Document ID:** ${(await e.documentManager.createDocument({title:r.save_as_document.title,content:c.text,metadata:{...r.save_as_document.metadata,Provider:c.provider,Model:c.model}})).id}`}catch(l){u=`
191
- \u26A0 Document save failed: ${q(l)}`}return{content:[{type:"text",text:`**Provider:** ${c.provider}
245
+ \u26A0 Document save failed: ${M(l)}`}return{content:[{type:"text",text:`**Provider:** ${c.provider}
192
246
  **Model:** ${c.model}${u}
193
247
 
194
- ${c.text}`}]}}async function $I(t,e){let r=Cx.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("analysis",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let a=`${r.file_paths.map(l=>{let d=Ft(l,n),p=Rx(d,"utf-8");return`--- ${d} ---
248
+ ${c.text}`}]}}async function dO(t,e){let r=Aw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("analysis",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let a=`${r.file_paths.map(l=>{let d=Bt(l,n),p=Rw(d,"utf-8");return`--- ${d} ---
195
249
  ${p}`}).join(`
196
250
 
197
251
  `)}
198
252
 
199
253
  ---
200
254
 
201
- Question: ${r.question}`,c=await s.chat({prompt:a});if(r.save_to_file){let l=ht(r.save_to_file,n);ie(l,c.text)}let u=r.save_to_file?`
255
+ Question: ${r.question}`,c=await s.chat({prompt:a});if(r.save_to_file){let l=ht(r.save_to_file,n);se(l,c.text)}let u=r.save_to_file?`
202
256
 
203
257
  _Result saved to: ${r.save_to_file}_`:"";return{content:[{type:"text",text:`**Provider:** ${c.provider}
204
258
  **Files analyzed:** ${r.file_paths.join(", ")}
205
259
 
206
- ${c.text}${u}`}]}}async function SI(t,e){let r=Ax.parse(t),n=r.providers.map(c=>e.registry.get(c)),o=await Promise.all(n.map(async c=>{try{let u=await c.chat({prompt:r.prompt});return{provider:c.id,text:u.text,error:null}}catch(u){return{provider:c.id,text:null,error:q(u)}}})),s=`# Comparison
260
+ ${c.text}${u}`}]}}async function pO(t,e){let r=Cw.parse(t),n=r.providers.map(c=>e.registry.get(c)),o=await Promise.all(n.map(async c=>{try{let u=await c.chat({prompt:r.prompt});return{provider:c.id,text:u.text,error:null}}catch(u){return{provider:c.id,text:null,error:M(u)}}})),s=`# Comparison
207
261
 
208
262
  **Prompt:** ${r.prompt}
209
263
 
@@ -218,21 +272,48 @@ ${c.text}${u}`}]}}async function SI(t,e){let r=Ax.parse(t),n=r.providers.map(c=>
218
272
 
219
273
  ---
220
274
 
221
- ${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${q(p)}]`}}}let a=s;return i&&(a+=`---
275
+ ${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${M(p)}]`}}}let a=s;return i&&(a+=`---
222
276
 
223
277
  # Synthesis
224
278
 
225
- ${i}`),{content:[{type:"text",text:a}]}}async function kI(t,e,r){switch(t){case"ai_chat":return wI(e,r);case"ai_analyze_files":return $I(e,r);case"ai_compare":return SI(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var qd={};We(qd,{getTools:()=>Nd,handleTool:()=>tb});var Ca=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),max_rounds:h.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:h.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:h.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:h.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),Aa=h.object({items:h.array(h.object({provider:h.string().describe("Provider that produced the content"),content:h.string().describe("Content to validate"),task:h.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:h.array(h.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:h.string().optional().describe("Custom validation criteria")}),Ia=h.object({session_id:h.string().describe("Session ID to check")}),Da=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),goal:h.string().optional().describe("Quality goal for the debate"),save_document:h.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),Oa=h.object({debate_id:h.string().describe("Debate session ID"),provider:h.string().describe(`Provider ID to take this turn. Use "claude" to record Claude's own opinion as an independent turn (requires claude_comment).`),claude_comment:h.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:h.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),Ma=h.object({debate_id:h.string().describe("Debate session ID to conclude"),summary:h.string().optional().describe("Claude's final summary of the debate"),quality_scores:h.array(h.object({provider:h.string(),score:h.number().min(0).max(1),feedback:h.string()})).optional().describe("Quality assessment of each provider's contribution")}),Na=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate. `claude` joins when a registered host-backed Claude provider is available."),goal:h.string().optional().describe("Quality goal for the debate"),max_rounds:h.number().int().positive().optional().default(5).describe("Maximum number of rounds (default: 5)"),specialist:h.string().optional().describe("Override specialist agent (default: auto-select from topic)"),save_document:h.boolean().optional().default(!0).describe("Save debate as a workspace document")}),ja=h.object({document:h.string().describe("Document content to review"),providers:h.array(h.string()).min(1).describe("Provider IDs to review the document"),review_prompt:h.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:h.string().optional().describe("Link reviews to an existing debate session's workspace document")}),La=h.object({task_id:h.string().describe("Task ID to review changes for")}),Za=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),qa=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),Dx=h.object({agrees:h.union([h.boolean(),h.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:h.string().optional().default(""),suggestions:h.string().optional()});function Nd(){return[{name:"agent_debate_start",title:"Start AI Debate",description:"Start a multi-provider debate on a topic. Optionally enable enhanced mode with goal-based quality validation.",inputSchema:J(Ca)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:J(Ia)},{name:"agent_cross_validate",title:"Cross-Validate Outputs",description:"Cross-validate work outputs. Each item is reviewed by agent-tier providers. Tool-tier providers cannot be validators.",inputSchema:J(Aa)},{name:"agent_debate_create",title:"Create Turn-Based Debate",description:"Create a turn-based debate session. Returns a debate ID for use with agent_debate_turn and agent_debate_conclude.",inputSchema:J(Da)},{name:"agent_debate_turn",title:"Execute Debate Turn",description:`Execute one provider's turn in a debate. Optionally inject Claude's comment before the provider responds. Returns the provider's response. Use provider: "claude" with claude_comment to record Claude's own independent opinion as a debate turn.`,inputSchema:J(Oa)},{name:"agent_debate_conclude",title:"Conclude Debate",description:"End a debate session and generate the final transcript. Optionally add Claude's summary and quality scores for each provider.",inputSchema:J(Ma)},{name:"agent_debate_review",title:"Review Document with Providers",description:"Send a document to multiple providers for structured review. Each provider responds with agree/disagree and feedback. Use iteratively: review \u2192 revise document based on feedback \u2192 review again until all agree.",inputSchema:J(ja)},{name:"agent_debate_moderate",title:"Run Moderated Debate",description:"Run a fully moderated debate. Creates a debate, runs rounds with the selected providers, checks for consensus after each round, and returns only the final summary. Records specialist selection metadata when the topic suggests one, and applies it to Claude's host-backed turn when available.",inputSchema:J(Na)},{name:"agent_changes_review",title:"Review File Changes",description:"Review file changes made by an external AI in an isolated worktree. Shows diff stat and full diff.",inputSchema:J(La)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:J(Za)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:J(qa)}]}var Ox=18e4;function on(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${Ox/1e3}s)`)),Ox))])}function Nx(t){return new vo({tools:Sc(),baseDir:t})}var jd,Mx;function jx(t){return(!jd||Mx!==t)&&(jd=new go,Mx=t),jd}var TI;function Lx(){return TI??=new ho}function Ld(t,e){let r=t.debateEngine.getState(e);if(!r||r.turns.length<2)return{text:"",reached:!1};let n=t.consensusDetector.analyzeConsensus(r);if(t.debateEngine.recordConsensusCheck(e,n),n.reached)return{text:`
279
+ ${i}`),{content:[{type:"text",text:a}]}}async function fO(t,e,r){switch(t){case"ai_chat":return lO(e,r);case"ai_analyze_files":return dO(e,r);case"ai_compare":return pO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ip={};Ze(Ip,{getTools:()=>gp,handleTool:()=>Ox});var Qa=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),max_rounds:h.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:h.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:h.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:h.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),Xa=h.object({items:h.array(h.object({provider:h.string().describe("Provider that produced the content"),content:h.string().describe("Content to validate"),task:h.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:h.array(h.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:h.string().optional().describe("Custom validation criteria")}),ec=h.object({session_id:h.string().describe("Session ID to check")}),tc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),goal:h.string().optional().describe("Quality goal for the debate"),save_document:h.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),rc=h.object({debate_id:h.string().describe("Debate session ID"),provider:h.string().describe(`Provider ID to take this turn. Use "claude" to record Claude's own opinion as an independent turn (requires claude_comment).`),claude_comment:h.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:h.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),nc=h.object({debate_id:h.string().describe("Debate session ID to conclude"),summary:h.string().optional().describe("Claude's final summary of the debate"),quality_scores:h.array(h.object({provider:h.string(),score:h.number().min(0).max(1),feedback:h.string()})).optional().describe("Quality assessment of each provider's contribution")}),oc=h.object({document:h.string().describe("Document content to review"),providers:h.array(h.string()).min(1).describe("Provider IDs to review the document"),review_prompt:h.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:h.string().optional().describe("Link reviews to an existing debate session's workspace document")}),sc=h.object({task_id:h.string().describe("Task ID to review changes for")}),ic=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),ac=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),zw=h.object({agrees:h.union([h.boolean(),h.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:h.string().optional().default(""),suggestions:h.string().optional()}),cc=h.object({topic:h.string().min(1).describe("Topic for the structured debate"),scope:h.string().optional().describe("What the leader wants debated (file list or task framing). Defaults to topic when omitted."),goal:h.string().optional().describe("Optional quality goal for the debate"),leader:h.string().optional().describe("Participant ID authorized to approve the final synthesis. Defaults to the session-context leader or the first participant."),participants:h.array(h.string()).min(1).describe("Participant IDs. When `auto_inject_specialists` is true (default), `claude-reviewer` and/or `claude-qa` may be added based on the topic."),exclude_participants:h.array(h.string()).optional().describe("Participant IDs to never inject/include. Applied regardless of `auto_inject_specialists`."),auto_inject_specialists:h.boolean().optional().default(!0).describe("When true (default), topic-matching Claude specialists are added to `participants` honoring `exclude_participants`. When false, `participants` is used verbatim."),max_rounds:h.number().int().positive().max(50).optional().describe("Maximum number of rounds. Default: STRUCTURED_DEBATE_DEFAULT_MAX_ROUNDS."),individual_review_prompt:h.string().optional().describe("Override the system prompt used for individual-review fan-out."),files:h.array(h.string()).optional().describe("Optional list of files to pass to participants as context."),locale:h.enum(["ko","zh","ja","en"]).optional().describe("Override config locale for moderator text in this debate only.")}),uc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),leader_note:h.string().optional().describe("Optional note appended to the synthesis footer under 'Leader approval notes'.")}),lc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),additional_rounds:h.union([h.literal(3),h.literal(5),h.literal(10)]).describe("How many extra rounds to run beyond the current round count. Choose one of 3, 5, or 10.")}),dc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),reason:h.string().optional().describe("Optional rejection reason, captured in the debate transcript footer."),spawn_issue:h.boolean().optional().default(!1).describe("If true, write an issue_{sessionIdShort}_{YYYYMMDD}_{seq}.md under individual/ listing all non-accepted proposals (rejected/withdrawn/open/inconclusive/superseded). Default false.")});var pc="agent_debate_structured",no="agent_debate_approve",oo="agent_debate_continue",so="agent_debate_reject";function fc(t){return t.moderatorEngine?t.structuredSessionRegistry?null:{content:[{type:"text",text:"Structured session registry is not initialized for this workspace."}],isError:!0}:{content:[{type:"text",text:"Structured debate engine is not initialized for this workspace. Check MCP server wiring."}],isError:!0}}async function Ow(t,e){let r=fc(e);if(r)return r;let n;try{n=cc.parse(t)}catch(s){return Xt(`Invalid arguments: ${M(s)}`)}let o=mO(n.leader,n.participants,e);if(!o)return Xt("Cannot resolve a leader. Provide `leader` explicitly or ensure the session context exposes one.");try{let s=await e.moderatorEngine.startDebate({topic:n.topic,...n.scope!==void 0?{scope:n.scope}:{},...n.goal!==void 0?{goal:n.goal}:{},leader:o,participants:n.participants,...n.exclude_participants!==void 0?{excludeParticipants:n.exclude_participants}:{},...n.auto_inject_specialists!==void 0?{autoInjectSpecialists:n.auto_inject_specialists}:{},...n.max_rounds!==void 0?{maxRounds:n.max_rounds}:{},...n.locale!==void 0?{locale:n.locale}:{},...n.individual_review_prompt!==void 0?{individualReviewPrompt:n.individual_review_prompt}:{},...n.files!==void 0?{files:n.files}:{}}),i=[s.terminalReport];return i.push(Lw(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(Zw(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(Fw(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
226
280
 
227
- ---
228
- **Consensus reached.** ${n.reason}
229
- Recommendation: conclude the debate with \`agent_debate_conclude\`.`,reached:!0};if(n.signals.some(o=>o.agreedExplicitly)){let o=n.signals.filter(i=>i.agreedExplicitly).map(i=>i.speaker),s=n.signals.filter(i=>!i.agreedExplicitly).map(i=>i.speaker);return{text:`
281
+ `)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return Xt(`Failed to start structured debate: ${M(s)}`)}}async function Mw(t,e){let r=fc(e);if(r)return r;let n;try{n=uc.parse(t)}catch(o){return Xt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.approve({sessionId:n.session_id,...n.leader_note!==void 0?{leaderNote:n.leader_note}:{}}),s=[o.terminalReport];return s.push(`Synthesis document: ${o.synthesisPath}`),s.push(`Status: ${o.snapshot.status} (session ${n.session_id})`),o.idempotentReplay&&s.push("(idempotent replay of existing approved state \u2014 no new synthesis written)"),{content:[{type:"text",text:s.join(`
230
282
 
231
- ---
232
- **Partial consensus:** ${o.join(", ")} agreed. Awaiting: ${s.join(", ")}.`,reached:!1}}return{text:"",reached:!1}}function Zx(t,e,r){let n=.7;if(r&&e){for(let o of r)e.updateQuality(t.id,o.provider,{score:o.score,evaluator:"claude",feedback:o.feedback});n=r.reduce((o,s)=>o+s.score,0)/r.length}else if(e){let o=new Map;for(let a of t.turns){if(a.speaker==="claude")continue;let c=t.turns.filter(d=>d.turnNumber<a.turnNumber).map(d=>({speaker:d.speaker,content:d.content})),u=wo(a.content,c,t.topic),l=o.get(a.speaker)??[];l.push(u.score),o.set(a.speaker,l)}let s=0,i=0;for(let[a,c]of o){let u=c.reduce((l,d)=>l+d,0)/c.length;e.updateQuality(t.id,a,{score:u,evaluator:"auto_rule_based",feedback:`Auto-aggregated from ${c.length} turns`}),s+=u,i++}i>0&&(n=s/i)}return{avgQuality:n}}function Yn(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function qx(t,e){let r=Ca.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),o=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(o.id,"in_progress");let s=e.debateEngine,i=s.create({topic:r.topic,providerIds:r.providers,goal:r.goal}),a=!!(r.goal&&r.validator),c=a?e.registry.get(r.validator):void 0,u=a?r.min_rounds??2:r.max_rounds;return(async()=>{try{let l="";for(let p=0;p<r.max_rounds;p++){for(let[f,g]of n){let y=s.buildPromptForProvider(i.id,f);l&&(y+=`
283
+ `)}]}}catch(o){return Xt(`Approve failed: ${M(o)}`)}}async function jw(t,e){let r=fc(e);if(r)return r;let n;try{n=lc.parse(t)}catch(o){return Xt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds}),s=[o.terminalReport];return s.push(Lw(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(Zw(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(Fw(n.session_id)),{content:[{type:"text",text:s.join(`
284
+
285
+ `)}]}}catch(o){return Xt(`Continue failed: ${M(o)}`)}}async function Nw(t,e){let r=fc(e);if(r)return r;let n;try{n=dc.parse(t)}catch(o){return Xt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.reject({sessionId:n.session_id,...n.reason!==void 0?{reason:n.reason}:{},...n.spawn_issue!==void 0?{spawnIssue:n.spawn_issue}:{}}),s=o.snapshot.documentPaths.debate,i=[`Structured debate session ${n.session_id} rejected.`];return n.reason&&i.push(`Reason: ${n.reason}`),i.push(`Transcript: ${s}`),o.issuePath&&i.push(`Issue document: ${o.issuePath}`),o.idempotentReplay&&i.push("(idempotent replay of existing rejected state \u2014 no new artifacts written)"),{content:[{type:"text",text:i.join(`
286
+ `)}]}}catch(o){return Xt(`Reject failed: ${M(o)}`)}}function mO(t,e,r){if(t&&t.length>0)return t;let n=r.sessionContext?.leaderProviderId;return n&&e.includes(n)||n?n:e[0]}function Lw(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function Fw(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${no}\` with { session_id: "${t}" }`,`- Extend debate: call \`${oo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${so}\` with { session_id: "${t}" }`].join(`
287
+ `)}function Zw(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${oo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${no}\` to accept the current synthesis with open items captured.`,`- \`${so}\` to abandon the session.`,`Session ID: ${t}`].join(`
288
+ `)}function Xt(t){return{content:[{type:"text",text:t}],isError:!0}}function gp(){return[{name:"agent_debate_start",title:"Start AI Debate",description:"Start a multi-provider debate on a topic. Optionally enable enhanced mode with goal-based quality validation.",inputSchema:V(Qa)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:V(ec)},{name:"agent_cross_validate",title:"Cross-Validate Outputs",description:"Cross-validate work outputs. Each item is reviewed by agent-tier providers. Tool-tier providers cannot be validators.",inputSchema:V(Xa)},{name:"agent_debate_create",title:"Create Turn-Based Debate",description:"Create a turn-based debate session. Returns a debate ID for use with agent_debate_turn and agent_debate_conclude.",inputSchema:V(tc)},{name:"agent_debate_turn",title:"Execute Debate Turn",description:`Execute one provider's turn in a debate. Optionally inject Claude's comment before the provider responds. Returns the provider's response. Use provider: "claude" with claude_comment to record Claude's own independent opinion as a debate turn.`,inputSchema:V(rc)},{name:"agent_debate_conclude",title:"Conclude Debate",description:"End a debate session and generate the final transcript. Optionally add Claude's summary and quality scores for each provider.",inputSchema:V(nc)},{name:"agent_debate_review",title:"Review Document with Providers",description:"Send a document to multiple providers for structured review. Each provider responds with agree/disagree and feedback. Use iteratively: review \u2192 revise document based on feedback \u2192 review again until all agree.",inputSchema:V(oc)},{name:"agent_changes_review",title:"Review File Changes",description:"Review file changes made by an external AI in an isolated worktree. Shows diff stat and full diff.",inputSchema:V(sc)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:V(ic)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:V(ac)},{name:pc,title:"Start Structured Debate",description:"Start a structured, approval-gated debate. Each participant submits an individual review, then rounds run until consensus or max rounds. Output is a ready-for-approval session \u2014 call agent_debate_approve/continue/reject to finalize. No synthesis is written until approved.",inputSchema:V(cc)},{name:no,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:V(uc)},{name:oo,title:"Continue Structured Debate",description:"Run additional rounds on a ready-for-approval (or escalated) structured-debate session. Choose 3, 5, or 10 extra rounds.",inputSchema:V(lc)},{name:so,title:"Reject Structured Debate",description:"Reject a ready-for-approval (or escalated/leader-timeout) structured-debate session. Transcript is marked rejected; no synthesis is written.",inputSchema:V(dc)}]}import{readFileSync as gO}from"fs";import{join as Hw}from"path";function Uw(t,e){let r=`${t} ${e??""}`.toLowerCase(),n=[{patterns:[/\breview\b/,/\bcode\s*quality\b/,/\bsecurity\b/,/\baudit\b/,/리뷰/,/보안/,/코드\s*품질/],agent:"agestra-reviewer"},{patterns:[/\bdesign\b/,/\barchitect/,/\bstructur/,/설계/,/아키텍처/,/구조/],agent:"agestra-designer"},{patterns:[/\bidea\b/,/\bimprov/,/\bcompare\b/,/\balternativ/,/\bbrainstorm/,/개선/,/아이디어/,/비교/,/대안/],agent:"agestra-ideator"},{patterns:[/\bverif/,/\bvalidat/,/\bqa\b/,/\btest\b/,/\bcheck\b/,/검증/,/테스트/,/확인/],agent:"agestra-qa"}];for(let o of n)if(o.patterns.some(s=>s.test(r)))return o.agent;return null}var mc="claude-reviewer",hc="claude-qa",hO={"agestra-reviewer":mc,"agestra-qa":hc};function qw(t){let{topic:e,goal:r,participants:n,excludeParticipants:o,autoInjectSpecialists:s}=t,i=new Set(o),a=n.filter(d=>!i.has(d)),c=Uw(e,r),u=c!==null?hO[c]??null:null,l=[];return u===null?{participants:a,skipped:l}:s?i.has(u)?(l.push({participantId:u,reason:"explicitly-excluded"}),{participants:a,skipped:l}):a.includes(u)?(l.push({participantId:u,reason:"already-listed"}),{participants:a,skipped:l}):{participants:[...a,u],skipped:l}:(l.push({participantId:u,reason:"auto-disabled"}),{participants:a,skipped:l})}var vp="claude",_p="claude-cli",yO=new Set([mc,hc]),bp=Object.freeze({[mc]:"agestra-reviewer",[hc]:"agestra-qa"});function vO(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
289
+ `,3);if(e<0)return t;let r=t.indexOf(`
290
+ ---`,e);if(r<0)return t;let n=t.indexOf(`
291
+ `,r+4);return n<0?"":t.slice(n+1)}function _O(t,e){return yO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:bp[t]}:{transport:"cli-bridge",providerId:_p,agentName:bp[t]}:t===vp?e==="claude-code"?{transport:"read-only-chat",providerId:vp}:{transport:"cli-bridge",providerId:_p}:{transport:"read-only-chat",providerId:t}}function Vw(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var Bw=18e4;function yp(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${Bw/1e3}s)`)),Bw))])}function Ww(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=bp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=Hw(r,`${s}.md`);try{let a=vO(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var wp=class{registry;readOnlyAdapter;hostKind;agentsDir;readFile;subagentSpawner;sysPromptCache=new Map;constructor(e){this.registry=e.registry,this.readOnlyAdapter=e.readOnlyAdapter,this.hostKind=e.hostKind,this.agentsDir=e.agentsDir??Hw(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>gO(r,"utf-8")),this.subagentSpawner=e.subagentSpawner}describe(e){return this.resolveDescriptor(e)}async requestTurn(e,r){let n=this.resolveDescriptor(e),o=performance.now();try{switch(n.transport){case"task-subagent":{if(!this.subagentSpawner)return this.buildFailure(e,o,"subagent spawner not wired (integration pending \u2014 T10/T12)");let s=await yp(this.subagentSpawner({agentName:n.agentName??e,prompt:r.prompt,system:r.system}),e);return this.buildSuccess(e,o,s.text)}case"cli-bridge":{let s=n.providerId??_p,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=Ww(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await yp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:Vw(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}case"read-only-chat":{let s=n.providerId??e,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`provider "${s}" not registered`);let a=n.agentName!==void 0?Ww(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await yp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:Vw(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}default:{let s=n.transport;return this.buildFailure(e,o,`unknown transport: ${String(s)}`)}}}catch(s){return this.buildFailure(e,o,M(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=_O(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:vp,agentName:r.agentName}:r}buildSuccess(e,r,n){return{participantId:e,text:n,latencyMs:Math.round(performance.now()-r),failed:!1}}buildFailure(e,r,n){return{participantId:e,text:"",latencyMs:Math.round(performance.now()-r),failed:!0,failureReason:n}}};function Kw(t){return new wp(t)}function Jw(t,e){return e(t)}var bO=/[.,!?;:]/g,wO=/\s+/g;function Gw(t){return t.toLowerCase().replace(bO," ").replace(wO," ").trim()}function Yw(t){return typeof t.location=="string"&&t.location.length>0}function Qw(t,e){if(e.length===0)return t;let r=new Set(t),n=t.slice();for(let o of e)r.has(o)||(r.add(o),n.push(o));return n}function xO(t){let e={id:t.id,proposerIds:t.proposerIds.slice(),title:t.title,severity:t.severity,roundOpened:t.roundOpened,status:t.status,votes:new Map};t.location!==void 0&&(e.location=t.location),t.description!==void 0&&(e.description=t.description),t.supersededBy!==void 0&&(e.supersededBy=t.supersededBy),t.mergedInto!==void 0&&(e.mergedInto=t.mergedInto);for(let[r,n]of t.votes)e.votes.set(r,{...n});return e}function SO(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=Gw(t.title)===Gw(e.title),s=t.severity===e.severity,a=Yw(t)&&Yw(e)&&t.location===e.location,c=[];if(o&&c.push("title"),s&&c.push("severity"),a&&c.push("location"),c.length===0)return{kind:"unrelated"};if(o&&s&&a)return{kind:"hard-merge"};let l;return o?s?l="location":l="severity":l="title",{kind:"alias",pair:{proposalA:t.id,proposalB:e.id,matchedFields:c,missingField:l}}}var io=class t{_proposals=new Map;_aliasCandidates=[];get proposals(){return this._proposals}get aliasCandidates(){return this._aliasCandidates.slice()}addProposal(e){if(this._proposals.has(e.id))throw new Error(`ProposalLedger.addProposal: duplicate id "${e.id}"`);let r={id:e.id,proposerIds:e.proposerIds.slice(),title:e.title,severity:e.severity,roundOpened:e.roundOpened,status:e.status??"open",votes:new Map};e.location!==void 0&&(r.location=e.location),e.description!==void 0&&(r.description=e.description),this._proposals.set(r.id,r)}recordVote(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.recordVote: unknown proposal id "${e}"`);o.votes.set(r,{...n}),o.proposerIds.includes(r)&&n.vote==="revise"&&o.status==="open"&&(o.status="withdrawn-by-author")}countRevisesThisRound(e,r){let n=this._proposals.get(e);if(!n)return 0;let o=0;for(let[s,i]of n.votes)i.vote==="revise"&&i.roundRecorded===r&&(n.proposerIds.includes(s)||(o+=1));return o}markSuperseded(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.markSuperseded: unknown old id "${e}"`);if(!this._proposals.has(r))throw new Error(`ProposalLedger.markSuperseded: successor id "${r}" not registered`);o.status="superseded",o.supersededBy=r;for(let s of o.votes.values())s.supersededAt===void 0&&(s.supersededAt=n)}applyAliasMerge(e,r){if(e===r)throw new Error(`ProposalLedger.applyAliasMerge: cannot merge id "${e}" into itself`);let n=this._proposals.get(e),o=this._proposals.get(r);if(!n)throw new Error(`ProposalLedger.applyAliasMerge: unknown primary id "${e}"`);if(!o)throw new Error(`ProposalLedger.applyAliasMerge: unknown alias id "${r}"`);n.proposerIds=Qw(n.proposerIds,o.proposerIds);for(let[s,i]of o.votes){let a=n.votes.get(s);if(!a){n.votes.set(s,{...i});continue}i.roundRecorded>a.roundRecorded&&n.votes.set(s,{...i})}o.status="merged",o.mergedInto=e;for(let s=this._aliasCandidates.length-1;s>=0;s-=1){let i=this._aliasCandidates[s];(i.proposalA===r||i.proposalB===r||i.proposalA===e||i.proposalB===e)&&this._aliasCandidates.splice(s,1)}}setStatus(e,r){let n=this._proposals.get(e);if(!n)throw new Error(`ProposalLedger.setStatus: unknown proposal id "${e}"`);n.status=r}aggregateRound(e,r,n=[]){let o=new Set(n),s=[];for(let i of this._proposals.values()){if(i.status!=="open")continue;let a={agree:0,disagree:0,abstain:0,revise:0,missing:0};for(let u of r){if(i.proposerIds.includes(u))continue;let l=i.votes.get(u);if(l===void 0||l.roundRecorded!==e){o.has(u)?a.abstain+=1:a.missing+=1;continue}switch(l.vote){case"agree":a.agree+=1;break;case"disagree":a.disagree+=1;break;case"abstain":a.abstain+=1;break;case"revise":a.revise+=1;break;default:{let d=l.vote}}}let c=$O(a);s.push({proposalId:i.id,tally:a,verdict:c})}return s}getOpenProposals(){return this.selectByStatus("open")}getConsensusProposals(){return this.selectByStatus("consensus")}getUnresolved(){return this.selectByStatus("unresolved")}selectByStatus(e){let r=[];for(let n of this._proposals.values())n.status===e&&r.push(xO(n));return r}toJSON(){let e=Array.from(this._proposals.values()).map(n=>{let o=[];for(let[i,a]of n.votes){let c={voter:i,vote:a.vote,roundRecorded:a.roundRecorded};a.reason!==void 0&&(c.reason=a.reason),a.supersededAt!==void 0&&(c.supersededAt=a.supersededAt),o.push(c)}let s={id:n.id,proposerIds:n.proposerIds.slice(),title:n.title,severity:n.severity,roundOpened:n.roundOpened,status:n.status,votes:o};return n.location!==void 0&&(s.location=n.location),n.description!==void 0&&(s.description=n.description),n.supersededBy!==void 0&&(s.supersededBy=n.supersededBy),n.mergedInto!==void 0&&(s.mergedInto=n.mergedInto),s}),r=this._aliasCandidates.map(n=>({proposalA:n.proposalA,proposalB:n.proposalB,matchedFields:n.matchedFields.slice(),missingField:n.missingField}));return{proposals:e,aliasCandidates:r}}static fromJSON(e){let r=new t,n=new Set;for(let o of e.proposals){if(n.has(o.id))throw new Error(`ProposalLedger.fromJSON: duplicate proposal id "${o.id}"`);n.add(o.id);let s={id:o.id,proposerIds:o.proposerIds.slice(),title:o.title,severity:o.severity,roundOpened:o.roundOpened,status:o.status,votes:new Map};o.location!==void 0&&(s.location=o.location),o.description!==void 0&&(s.description=o.description),o.supersededBy!==void 0&&(s.supersededBy=o.supersededBy),o.mergedInto!==void 0&&(s.mergedInto=o.mergedInto);for(let i of o.votes){let a={vote:i.vote,roundRecorded:i.roundRecorded};i.reason!==void 0&&(a.reason=i.reason),i.supersededAt!==void 0&&(a.supersededAt=i.supersededAt),s.votes.set(i.voter,a)}r._proposals.set(s.id,s)}for(let o of e.aliasCandidates)r._aliasCandidates.push({proposalA:o.proposalA,proposalB:o.proposalB,matchedFields:o.matchedFields.slice(),missingField:o.missingField});return r}_rawProposal(e){return this._proposals.get(e)}_pushAliasCandidate(e){this._aliasCandidates.push(e)}_extendProposers(e,r){let n=this._proposals.get(e);n&&(n.proposerIds=Qw(n.proposerIds,r))}_maybeReplaceDescription(e,r){let n=this._proposals.get(e);if(!n||r===void 0)return;let o=n.description??"";r.length>o.length&&(n.description=r)}};function $O(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function Xw(t){let e=new io,r=new Set;for(let s of t){if(r.has(s.id))throw new Error(`buildInitialLedger: duplicate proposal id "${s.id}"`);r.add(s.id),e.addProposal({id:s.id,proposerIds:[s.proposerId],title:s.title,severity:s.severity,...s.location!==void 0?{location:s.location}:{},...s.description!==void 0?{description:s.description}:{},roundOpened:s.roundOpened??1,status:"open"})}let n=new Set,o=t.map(s=>s.id);for(let s=0;s<o.length;s+=1){let i=o[s];if(n.has(i))continue;let a=e._rawProposal(i);if(a)for(let c=s+1;c<o.length;c+=1){let u=o[c];if(n.has(u))continue;let l=e._rawProposal(u);if(!l)continue;let d=SO(a,l);if(d.kind==="hard-merge"){e._extendProposers(i,l.proposerIds),e._maybeReplaceDescription(i,l.description),e._proposals.delete(u),n.add(u);continue}d.kind==="alias"&&e._pushAliasCandidate(d.pair)}}return{ledger:e,aliasCandidates:e.aliasCandidates}}var kO=new Set(lf);function PO(t){return kO.has(t)}var TO=new Set(["disagree","revise"]);function EO(t){let e=`<${ln}>`,r=`</${ln}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function RO(t){let e=`<${ln}>`;return t.includes(e)}var IO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function AO(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return IO[r]??e})}function CO(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=AO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function xp(t,e){let r=EO(t);if(!r)return RO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${ln}> without matching </${ln}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!ex(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!ex(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=CO(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.id,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({proposalId:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!PO(g)){l.push({proposalId:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({proposalId:m,reason:"unknown-id",raw:p.raw});continue}if(d.has(m)){l.push({proposalId:m,reason:"duplicate-id",raw:p.raw});continue}let y=f.reason,_=typeof y=="string"&&y.length>0?y:void 0;if(TO.has(g)&&_===void 0){d.add(m),l.push({proposalId:m,reason:"missing-reason",raw:p.raw});continue}d.add(m);let S={proposalId:m,vote:g};_!==void 0&&(S.reason=_),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}function ex(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var DO=Object.freeze(["same","different","unsure"]),zs="alias-votes",zO=new Set(DO);function OO(t){return zO.has(t)}function MO(t){let e=`<${zs}>`,r=`</${zs}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function jO(t){let e=`<${zs}>`;return t.includes(e)}var NO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function LO(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return NO[r]??e})}function FO(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=LO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function tx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Sp(t,e){let r=MO(t);if(!r)return jO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${zs}> without matching </${zs}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!tx(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!tx(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=FO(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.pair,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({pair:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!OO(g)){l.push({pair:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({pair:m,reason:"unknown-pair",raw:p.raw});continue}if(d.has(m)){l.push({pair:m,reason:"duplicate-pair",raw:p.raw});continue}let y=f.reason,_=typeof y=="string"&&y.length>0?y:void 0;d.add(m);let S={pair:m,vote:g};_!==void 0&&(S.reason=_),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}var ZO="__";function UO(t){return`${t.proposalA}${ZO}${t.proposalB}`}var qO=["You are participating in the alias clarification phase of a structured debate.","The moderator has detected the following proposal pairs that partially match","on title / severity / location but did not satisfy the automatic hard-merge","rule. For each pair, decide whether the two proposals describe the SAME","underlying issue or DIFFERENT issues. If you cannot tell from the material","given, answer `unsure` \u2014 there is no penalty for uncertainty here, this","phase is not the main debate."].join(" "),VO=["For every pair below, emit exactly one `<item>` element inside the","`<alias-votes>` block. The `pair` attribute must match the identifier","printed with each pair. The `vote` attribute must be one of:","`same`, `different`, `unsure`. A `reason` attribute is optional but","encouraged when you answer `different` or `unsure`."].join(" "),BO=["Response format \u2014 append the following block at the end of your reply","(moderator parses only this block; preamble is ignored):","","<alias-votes>",' <item pair="P1__P2" vote="same"/>',' <item pair="P3__P4" vote="different" reason="P3 concerns cache invalidation; P4 concerns read-through."/>',' <item pair="P5__P6" vote="unsure" reason="Insufficient detail on location."/>',"</alias-votes>"].join(`
292
+ `),WO="Candidate pairs:";function HO(t,e){return["Your previous response did not include a valid `<alias-votes>` block.",`Problem: ${e}`,"Reply with ONLY the `<alias-votes>` block. Do not include prose.","<alias-votes>",...t.map(r=>` <item pair="${r}" vote="same|different|unsure" reason="optional"/>`),"</alias-votes>"].join(`
293
+ `)}async function ix(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(UO),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=KO(e,o,s),c=await Promise.allSettled(r.map(async f=>{let m=await n(f,a);return{participantId:f,response:m}})),u=[],l=new Map;for(let f of s)l.set(f,{same:0,different:0,unsure:0,missing:0});for(let f=0;f<c.length;f+=1){let m=c[f],g=r[f];if(m.status==="rejected"){u.push({participantId:g,reason:sx(m.reason)}),gc(l,s);continue}let{response:y}=m.value;if(y.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),gc(l,s);continue}let _=Sp(y.text,s),S=new Set;if(!_.ok){let v=await n(g,HO(s,_.error.details!==void 0?`${_.error.kind}: ${_.error.details}`:_.error.kind)).catch(x=>({text:"",failed:!0,reason:sx(x)}));if(v.failed===!0){u.push({participantId:g,reason:"reason"in v&&typeof v.reason=="string"?v.reason:"retry failed"}),gc(l,s);continue}let k=Sp(v.text,s);if(!k.ok){u.push({participantId:g,reason:k.error.details!==void 0?`${k.error.kind}: ${k.error.details}`:k.error.kind}),gc(l,s);continue}for(let x of k.entries)ox(l,x),S.add(x.pair);for(let x of s)if(!S.has(x)){let z=l.get(x);z!==void 0&&(z.missing+=1)}continue}for(let v of _.entries)ox(l,v),S.add(v.pair);for(let v of s)if(!S.has(v)){let k=l.get(v);k!==void 0&&(k.missing+=1)}}let d=[],p=[];for(let f of s){let m=i.get(f),g=l.get(f);if(m===void 0||g===void 0)continue;let y=GO(g);if(y.kind==="merge"){let _=m.proposalA,S=m.proposalB;if(e.proposals.get(_)===void 0||e.proposals.get(S)===void 0)continue;e.applyAliasMerge(_,S),d.push({primary:_,alias:S,voteBreakdown:{...g}});continue}p.push({pair:m,voteBreakdown:{...g},reason:y.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function KO(t,e,r){let n=[];n.push(qO),n.push(""),n.push(VO),n.push(""),n.push(WO),n.push("");for(let o=0;o<e.length;o+=1){let s=e[o],i=r[o],a=t.proposals.get(s.proposalA),c=t.proposals.get(s.proposalB);n.push(`Pair ${o+1} \u2014 pair="${i}"`),n.push(` matched fields: ${s.matchedFields.join(", ")||"(none)"}`),n.push(` blocking field: ${s.missingField}`),n.push(" Proposal A:"),rx(n,a),n.push(" Proposal B:"),rx(n,c),n.push("")}return n.push(BO),n.join(`
294
+ `)}function rx(t,e){if(e===void 0){t.push(" (proposal unavailable \u2014 already removed from ledger)");return}if(t.push(` id: ${e.id}`),t.push(` title: ${e.title}`),t.push(` severity: ${e.severity}`),t.push(` location: ${e.location!==void 0&&e.location.length>0?e.location:"(empty)"}`),e.description!==void 0&&e.description.length>0){let r=JO(e.description);t.push(` description: ${r}`)}}var nx=400;function JO(t){return t.length<=nx?t:`${t.slice(0,nx)}\u2026`}function ox(t,e){let r=t.get(e.pair);if(r!==void 0)switch(e.vote){case"same":r.same+=1;break;case"different":r.different+=1;break;case"unsure":r.unsure+=1;break;default:{let n=e.vote}}}function gc(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function GO(t){return t.same===0&&t.different===0?{kind:"undecided",reason:"no-votes"}:t.same>t.different?{kind:"merge"}:t.same===t.different?{kind:"undecided",reason:"tie"}:{kind:"undecided",reason:"different-majority"}}function sx(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as YO}from"fs/promises";import{readFileSync as QO,existsSync as $p,unlinkSync as XO,mkdirSync as eM}from"fs";import{join as Os}from"path";var Pp=".approval.json";function kp(t){return`${t}${Pp}`}function tM(t){return t.endsWith(Pp)?t.slice(0,t.length-Pp.length):null}function ax(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+df).toISOString()}var ao=class{debatesDir;cache=new Map;hydrated=!1;constructor(e){if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=Os(e,Us)}getDebatesDir(){return this.debatesDir}async persist(e){if(!e||!e.sessionId)throw new Error("StructuredSessionRegistry.persist: snapshot.sessionId is required");if(e.schemaVersion!==1)throw new Error(`StructuredSessionRegistry.persist: unsupported schemaVersion=${e.schemaVersion}`);eM(this.debatesDir,{recursive:!0});let r=Os(this.debatesDir,kp(e.sessionId));Ue(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=Os(this.debatesDir,kp(e));if(!$p(n))return null;let o=this.readSnapshotFile(n);return o&&this.cache.set(e,o),o}async remove(e){this.cache.delete(e);let r=Os(this.debatesDir,kp(e));if($p(r))try{XO(r)}catch(n){if(n.code!=="ENOENT")throw n}}async hydrateFromDisk(){if(this.cache.clear(),!$p(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await YO(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=tM(r);if(!n)continue;let o=this.readSnapshotFile(Os(this.debatesDir,r));o&&o.sessionId===n&&this.cache.set(n,o)}this.hydrated=!0}get(e){return this.cache.get(e)}getAll(){return Array.from(this.cache.values())}async sweepTimeouts(e=new Date){let r=e.getTime(),n=[];for(let o of this.cache.values()){if(o.status!=="ready-for-approval")continue;let s=Date.parse(o.deadline);if(Number.isNaN(s)||r<=s)continue;let i={...o,status:"leader-timeout",terminalNote:o.terminalNote??"leader-timeout after approval window"};await this.persist(i),n.push(i)}return n}isHydrated(){return this.hydrated}readSnapshotFile(e){let r;try{r=QO(e,"utf-8")}catch(o){if(o.code==="ENOENT")return null;throw o}let n;try{n=JSON.parse(r)}catch{return console.warn(`[session-registry] skipping unparseable snapshot file: ${e}`),null}return rM(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function rM(t){if(!t||typeof t!="object")return!1;let e=t;return e.schemaVersion===1&&typeof e.sessionId=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.readyAt=="string"&&typeof e.deadline=="string"&&typeof e.config=="object"&&e.config!==null&&typeof e.rounds=="number"&&Array.isArray(e.aggregatedVotes)&&typeof e.documentPaths=="object"&&e.documentPaths!==null}function nM(t,e){let r=[];r.push(...iM(t,e)),r.push(""),r.push(...ux(t,e));let n=lx(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...dx(t,e)),r.push(""),r.push(...cM(t,e)),r.join(`
295
+ `)}function oM(t,e){let r=[];r.push(...ux(t,e));let n=uM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=lM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=dM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=lx(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...dx(t,e)),r.join(`
296
+ `)}function cx(){return{renderTerminal:nM,renderSynthesis:oM}}var sM=Object.freeze({running:"report.status.running","ready-for-approval":"report.status.readyForApproval",consensus:"report.status.consensus",escalated:"report.status.escalated",approved:"report.status.approved",rejected:"report.status.rejected","leader-timeout":"report.status.leaderTimeout",error:"report.status.error"});function iM(t,e){let r=e.t(sM[t.status]),n=e.t("report.header.topic"),o=e.t("report.header.participants"),s=e.t("report.header.individualDocs"),i=[`## ${n}: ${t.topic} (${t.rounds}/${t.maxRounds} \u2014 ${r})`,`## ${o}: ${t.participantIds.join(", ")}`,`## ${s}:`],a=Math.min(t.participantIds.length,t.individualPaths.length);for(let c=0;c<a;c+=1)i.push(` - ${t.participantIds[c]}: ${t.individualPaths[c]}`);return i}function ux(t,e){let r=[`## ${e.t("report.section.mainTable")}`,"",`| ${e.t("report.table.proposer")} | ${e.t("report.table.opinion")} | ${e.t("report.table.severity")} | ${e.t("report.table.agreement")} |`,"|---|---|---|---|"];for(let n of t.proposals){let o=n.proposerIds.join(", "),s=aM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function aM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function lx(t,e){if(t.dissentDetails.length===0)return[];let r=[`## ${e.t("report.section.dissentDetail")}`];for(let n of t.dissentDetails){r.push(""),r.push(`### ${n.proposalTitle} (${n.severity})`);for(let o of n.perParticipant)r.push(Tp(o))}return r}function Tp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function dx(t,e){let r=`| ${e.t("report.contribution.ai")} | ${e.t("report.contribution.proposed")} | ${e.t("report.contribution.accepted")} | ${e.t("report.contribution.revises")} | ${e.t("report.contribution.abstains")} |`,n=[`## ${e.t("report.section.contributionSummary")}`,"",r,"|---|---|---|---|---|"];for(let o of t.contributionSummary){let s=o.proposed===0?"\u2014":String(o.consensusReceived);n.push(`| ${o.participantId} | ${o.proposed} | ${s} | ${o.revisesProposed} | ${o.abstains} |`)}return n}function cM(t,e){let r=e.t("report.footer.synthesisPath"),n=e.t("report.footer.debatePath"),o=t.synthesisPath??e.t("report.footer.pendingSynthesis"),s=[`## ${r}: ${o}`,`## ${n}: ${t.debatePath}`];return t.status==="ready-for-approval"&&(s.push(""),s.push(e.t("approval.pending"))),s}function uM(t,e){let r=t.acceptedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.acceptedItems")}`];for(let o of r)n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.proposer")}:** ${o.proposerIds.join(", ")}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`),o.finalStatement.length>0&&(n.push(""),n.push(o.finalStatement));return n}function lM(t,e){let r=t.rejectedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.rejectedItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),o.rejectionReason.length>0&&(n.push(""),n.push(o.rejectionReason));for(let s of o.dissentVotes)n.push(Tp(s))}return n}function dM(t,e){let r=t.openItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.openItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`);for(let s of o.perParticipant)n.push(Tp(s))}return n}var co=class{deps;sessions=new Map;formatter=cx();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??pM)(),n=this.nowIso(),o=qw({topic:e.topic,...e.goal!==void 0?{goal:e.goal}:{},participants:e.participants,excludeParticipants:e.excludeParticipants??[],autoInjectSpecialists:e.autoInjectSpecialists??!0}),s=o.participants,i={topic:e.topic,scope:e.scope??e.topic,participants:s,excludeParticipants:e.excludeParticipants??[],leader:e.leader,maxRounds:e.maxRounds??Cc,locale:e.locale??this.deps.i18n.locale,autoInjectSpecialists:e.autoInjectSpecialists??!0},a=await this.deps.documentManager.createDebateDocument({topic:e.topic,providers:s.slice(),...e.goal!==void 0?{goal:e.goal}:{}}),c={sessionId:r,config:i,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],debateDocId:a.id,debateDocPath:a.path,individualPaths:{},createdAt:n,ledger:new io,rounds:0,maxRounds:i.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1};this.sessions.set(r,c);try{let u=await this.runIndividualPhase(c,o),{ledger:l}=Xw(u);c.ledger=l,c.nextProposalIndex=_M(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,px(c));return await this.deps.registry.persist(d),this.emitTrace(c,"debate_rfa",{status:d.status}),{sessionId:r,status:d.status,snapshot:d,terminalReport:this.renderTerminal(c,d)}}catch(u){let l=this.buildSnapshot(c,"error",yc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:yc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:yc(u)}}}async approve(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="approved"){if(!r.documentPaths.synthesis)throw new Error(`approve: session "${e.sessionId}" is marked approved but has no synthesis path recorded. Snapshot is inconsistent.`);let u=this.sessions.get(e.sessionId);return{snapshot:r,synthesisPath:r.documentPaths.synthesis,terminalReport:this.renderTerminal(u??null,r),idempotentReplay:!0}}Ep(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?this.buildReportData(n,r,e.leaderNote):mx(r,e.leaderNote),s=this.formatter.renderSynthesis(o,this.deps.i18n),i=(r.status==="escalated"||r.status==="ready-for-approval")&&r.status==="escalated"?"escalated":"consensus",a=await this.deps.documentManager.createSynthesis({sessionId:r.sessionId,topic:r.config.topic,status:i,rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:s,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}});await this.deps.documentManager.addComment(n?.debateDocId??vc(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});let c={...r,status:"approved",documentPaths:{...r.documentPaths,synthesis:a.path}};return await this.deps.registry.persist(c),this.emitTrace(n??null,"debate_approved",{sessionId:r.sessionId,synthesisPath:a.path}),{snapshot:c,synthesisPath:a.path,terminalReport:this.renderTerminal(n??null,c)}}async continueDebate(e){if(!Number.isInteger(e.additionalRounds)||e.additionalRounds<=0)throw new Error(`continueDebate: additionalRounds must be a positive integer (got ${e.additionalRounds})`);let r=await this.loadSnapshotOrThrow(e.sessionId);Ep(r,["ready-for-approval","escalated"],"continue");let n=this.sessions.get(e.sessionId);if(!n){if(!r.ledgerState)throw new Error(`continueDebate: snapshot for session "${e.sessionId}" is too old to resume after restart \u2014 missing ledgerState. Use approve or reject instead, or rerun the debate.`);n=this.rehydrateSessionContext(r),this.sessions.set(e.sessionId,n)}n.maxRounds=r.config.maxRounds+e.additionalRounds;for(let i of n.ledger.proposals.values())i.status;await this.runRoundLoop(n);let o=px(n),s=this.buildSnapshot(n,o);return await this.deps.registry.persist(s),this.emitTrace(n,"debate_continued",{additionalRounds:e.additionalRounds,status:s.status}),{snapshot:s,terminalReport:this.renderTerminal(n,s)}}async reject(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="rejected")return{snapshot:r,idempotentReplay:!0,...r.documentPaths.issue!==void 0?{issuePath:r.documentPaths.issue}:{}};Ep(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??vc(r);await this.deps.documentManager.addComment(o,{author:"moderator",content:this.formatRejectionFooter(e.reason)});let s;e.spawnIssue===!0&&(s=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...e.reason!==void 0?{reason:e.reason}:{},items:vM(r)})).path);let i={...r,status:"rejected",terminalNote:e.reason??r.terminalNote,documentPaths:{...r.documentPaths,...s!==void 0?{issue:s}:{}}};return await this.deps.registry.persist(i),this.emitTrace(n??null,"debate_rejected",{sessionId:r.sessionId,...s!==void 0?{issuePath:s}:{}}),{snapshot:i,...s!==void 0?{issuePath:s}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=vc(r);try{await this.deps.documentManager.addComment(n,{author:"moderator",content:this.formatLeaderTimeoutFooter(r)})}catch{}this.emitTrace(this.sessions.get(r.sessionId)??null,"debate_leader_timeout",{sessionId:r.sessionId})}}async runIndividualPhase(e,r){let n=PM(),o=TM(e),s=await Promise.allSettled(e.config.participants.map(async a=>{let c=await this.deps.bridge.requestTurn(a,{prompt:o,system:e.individualReviewPrompt??n,round:0,...e.files.length>0?{files:e.files}:{}});return{participantId:a,resp:c}})),i=[];for(let a of s){if(a.status==="rejected")continue;let{participantId:c,resp:u}=a.value,l=u.failed?`(no response: ${u.failureReason??"unknown"})`:u.text,d=await this.deps.documentManager.createIndividualReview({participantId:c,topic:e.config.topic,content:l,...e.files.length>0?{files:e.files}:{}});if(e.individualPaths[c]=d.path,u.failed)continue;let p=kM(u.text);for(let f of p){let m=fx(e,f.id);i.push({id:m,proposerId:c,title:f.title,severity:f.severity,...f.location!==void 0?{location:f.location}:{},...f.description!==void 0?{description:f.description}:{},roundOpened:1})}}return i}async runAliasClarificationPhase(e){let r=await ix({ledger:e.ledger,participantIds:e.config.participants,askParticipant:async(o,s)=>{let i=await this.deps.bridge.requestTurn(o,{prompt:s,round:0,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=CM(r,this.deps.i18n);n.length>0&&await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:n})}async runRoundLoop(e){for(;e.rounds<e.maxRounds;){if(e.ledger.getOpenProposals().map(p=>p.id).length===0)return;e.rounds+=1;let n=e.rounds,o=e.config.participants.filter(p=>!e.unavailableParticipants.has(p)),s=e.ledger.getOpenProposals(),i=e.pendingVoteWarnings,a=new Map,c=await Promise.allSettled(o.map(async p=>{let f={prompt:EM({round:n,maxRounds:e.maxRounds,topic:e.config.topic,scope:e.config.scope,openProposals:s,previousVoteIssues:i.get(p)}),round:n,...e.files.length>0?{files:e.files}:{}},m=await this.deps.bridge.requestTurn(p,f);return{participantId:p,request:f,resp:m}})),u=[],l=new Set;for(let p=0;p<c.length;p+=1){let f=c[p],m=o[p];if(f.status==="rejected"||f.value.resp.failed){this.registerFailure(e,m);let y=f.status==="rejected"?yc(f.reason):f.value.resp.failureReason??"unknown";u.push({participantId:m,text:`(no response: ${y})`,failed:!0});continue}l.add(m);let g=await this.parseVotesWithRetry(m,f.value.request,f.value.resp.text,s,n);if(u.push({participantId:m,text:g.displayText,failed:!g.ok}),!g.ok){this.registerFailure(e,m),a.set(m,g.warnings);continue}this.clearFailure(e,m);for(let y of g.parsed.entries)e.ledger.recordVote(y.proposalId,m,{vote:y.vote,roundRecorded:n,...y.reason!==void 0?{reason:y.reason}:{}});g.parsed.entryErrors.length>0&&a.set(m,IM(g.parsed.entryErrors))}e.pendingVoteWarnings=a;let d=e.ledger.aggregateRound(n,e.config.participants,Array.from(e.unavailableParticipants));for(let p of d){let f=e.ledger.proposals.get(p.proposalId);if(!f)continue;let m=e.config.participants.filter(g=>!f.proposerIds.includes(g)).length;if(mM(p.tally,m)){e.ledger.setStatus(p.proposalId,"consensus"),e.allAbstainCount.delete(p.proposalId);continue}if(hM(p.tally,m)){e.ledger.setStatus(p.proposalId,"rejected"),e.allAbstainCount.delete(p.proposalId);continue}if(gM(p.tally)){let g=(e.allAbstainCount.get(p.proposalId)??0)+1;e.allAbstainCount.set(p.proposalId,g),g>=zc&&(e.ledger.setStatus(p.proposalId,"unresolved"),e.allAbstainCount.delete(p.proposalId));continue}e.allAbstainCount.delete(p.proposalId)}for(let p of d){if(p.tally.revise===0)continue;let f=e.ledger.proposals.get(p.proposalId);if(!f||f.status!=="open"||e.ledger.countRevisesThisRound(p.proposalId,n)===0)continue;let g=this.synthesizeReviseSuccessor(e,f,n);e.reviseSuccessors.set(f.id,g)}if(await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:AM({round:n,maxRounds:e.maxRounds,openProposals:s,turns:u,aggregation:d,ledger:e.ledger})}),l.size===0)return}}async parseVotesWithRetry(e,r,n,o,s){let i=o.map(p=>p.id),a=xp(n,i);if(a.ok)return{ok:!0,parsed:a,displayText:n};let c={prompt:RM({openProposals:o,errorKind:a.error.kind,errorDetails:a.error.details}),round:s,...r.files!==void 0?{files:r.files}:{}},u=await this.deps.bridge.requestTurn(e,c);if(u.failed)return{ok:!1,displayText:`${n}
297
+
298
+ [retry failed: ${u.failureReason??"unknown"}]`,warnings:[`Missing or malformed <votes> block (${a.error.kind}). Retry failed: ${u.failureReason??"unknown"}.`]};let l=xp(u.text,i),d=`${n}
299
+
300
+ [retry response]
301
+ ${u.text}`;return l.ok?{ok:!0,parsed:l,displayText:d}:{ok:!1,displayText:d,warnings:[`Missing or malformed <votes> block (${l.error.kind}).${l.error.details?` ${l.error.details}`:""}`]}}registerFailure(e,r){let n=(e.consecutiveFailures.get(r)??0)+1;e.consecutiveFailures.set(r,n),n>=Dc&&e.unavailableParticipants.add(r)}clearFailure(e,r){e.consecutiveFailures.delete(r)}synthesizeReviseSuccessor(e,r,n){let o=fx(e),s=[];for(let[,a]of r.votes)a.vote==="revise"&&a.roundRecorded===n&&a.reason&&s.push(a.reason);let i=s.length>0?`Revised from ${r.id}: ${s.join(" / ")}`:`Revised from ${r.id}`;return e.ledger.addProposal({id:o,proposerIds:r.proposerIds,title:`${r.title} (revised)`,severity:r.severity,...r.location!==void 0?{location:r.location}:{},description:i,roundOpened:n+1}),e.ledger.markSuperseded(r.id,o,n),o}rehydrateSessionContext(e){if(!e.ledgerState)throw new Error(`rehydrateSessionContext: snapshot "${e.sessionId}" has no ledgerState`);let r=io.fromJSON(e.ledgerState),n=new Map;if(e.consecutiveFailuresByParticipant)for(let[a,c]of Object.entries(e.consecutiveFailuresByParticipant))c>0&&n.set(a,c);let o=new Set(e.unavailableParticipants??[]),s=0;for(let a of e.ledgerState.proposals.map(c=>c.id)){let c=a.match(/^P(\d+)$/);if(c){let u=Number.parseInt(c[1],10);Number.isFinite(u)&&u>s&&(s=u)}}return{sessionId:e.sessionId,config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],debateDocId:vc(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:r,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:n,unavailableParticipants:o,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:s+1}}buildSnapshot(e,r,n){let o=this.nowIso(),s=fM(r)?Jw(o,ax):o,i=this.snapshotAggregatedVotes(e),a={};for(let[u,l]of e.consecutiveFailures)l>0&&(a[u]=l);return{schemaVersion:1,sessionId:e.sessionId,status:r,createdAt:e.createdAt,readyAt:o,deadline:s,config:{...e.config,maxRounds:e.maxRounds},rounds:e.rounds,aggregatedVotes:i,documentPaths:{individual:{...e.individualPaths},debate:e.debateDocPath},ledgerState:e.ledger.toJSON(),...Object.keys(a).length>0?{consecutiveFailuresByParticipant:a}:{},...e.unavailableParticipants.size>0?{unavailableParticipants:Array.from(e.unavailableParticipants)}:{},...n!==void 0?{terminalNote:n}:{}}}snapshotAggregatedVotes(e){let r=[];for(let n of e.ledger.proposals.values()){if(n.status==="merged")continue;let o={};for(let[s,i]of n.votes)o[s]={vote:i.vote,roundRecorded:i.roundRecorded,...i.reason!==void 0?{reason:i.reason}:{}};r.push({proposalId:n.id,title:n.title,severity:n.severity,...n.location!==void 0?{location:n.location}:{},proposers:n.proposerIds,status:yM(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){let n=e?this.buildReportData(e,r):mx(r);return this.formatter.renderTerminal(n,this.deps.i18n)}buildReportData(e,r,n){let o=[],s=[],i=[],a=[],c=[];for(let l of e.ledger.proposals.values()){if(l.status==="merged"||l.status==="superseded")continue;let d=e.config.participants.filter(f=>!l.proposerIds.includes(f)),p=bM(l,d);o.push({proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,accepted:l.status==="consensus",...p.dissentSummary!==void 0?{dissentSummary:p.dissentSummary}:{}}),p.perParticipant.length>0&&l.status!=="consensus"&&s.push({proposalTitle:l.title,severity:l.severity,perParticipant:p.perParticipant}),l.status==="consensus"?i.push({id:l.id,proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,finalStatement:l.description??""}):l.status==="rejected"||l.status==="withdrawn-by-author"?a.push({id:l.id,title:l.title,severity:l.severity,rejectionReason:l.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:p.perParticipant}):(l.status==="open"||l.status==="unresolved")&&c.push({id:l.id,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,perParticipant:p.perParticipant})}let u=wM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:hx(r.status),participantIds:e.config.participants,individualPaths:Object.values(e.individualPaths),debatePath:e.debateDocPath,...r.documentPaths.synthesis!==void 0?{synthesisPath:r.documentPaths.synthesis}:{},proposals:o,contributionSummary:u,dissentDetails:s,acceptedItems:i,rejectedItems:a,openItems:c,...n!==void 0?{leaderNote:n}:{}}}nowIso(){return(this.deps.now?this.deps.now():new Date).toISOString()}async loadSnapshotOrThrow(e){let r=await this.deps.registry.load(e);if(!r)throw new Error(`Structured debate session "${e}" not found`);return r}formatApprovalFooter(e){let r=this.deps.i18n.t("moderator.narration.approved");if(!e)return r;let n=this.deps.i18n.t("synthesis.narration.leaderNote");return`${r}
302
+
303
+ **${n}:** ${e}`}formatRejectionFooter(e){let r=this.deps.i18n.t("moderator.narration.rejected");return e?`${r}
304
+
305
+ Reason: ${e}`:r}formatLeaderTimeoutFooter(e){let r=this.deps.i18n.t("moderator.narration.leaderTimeoutFooter"),n=Date.parse(e.readyAt),o=Date.parse(e.deadline),s=Number.isFinite(n)&&Number.isFinite(o)&&o>n?Math.round((o-n)/(3600*1e3)):24,i=this.deps.i18n.t("approval.timeout",{hours:s});return`## ${r}
306
+
307
+ ${i}`}emitTrace(e,r,n){if(this.deps.traceWriter)try{this.deps.traceWriter.write({traceId:e?.sessionId??"unknown",action:r,providerId:"moderator-engine",task:e?.config.topic??"",request:{promptSummary:JSON.stringify(n),fileCount:0},response:{success:!0,charLength:0},latencyMs:0})}catch{}}};function pM(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function px(t){for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function fM(t){return t==="ready-for-approval"||t==="escalated"}function mM(t,e){return e===0?t.agree===0&&!1:t.disagree>0||t.revise>0||t.missing>0||t.agree<1?!1:t.agree+t.abstain===e}function hM(t,e){if(e===0||t.agree>0||t.revise>0)return!1;let r=Math.ceil(e/2);return t.disagree>=r}function gM(t){return t.abstain>0&&t.agree===0&&t.disagree===0&&t.revise===0&&t.missing===0}function Ep(t,e,r){if(!e.includes(t.status))throw new Error(`Operation \`${r}\` is not allowed in state \`${t.status}\`. Allowed states: ${e.join(", ")}`)}function yM(t){switch(t){case"consensus":return"accepted";case"rejected":return"rejected";case"withdrawn-by-author":return"withdrawn-by-author";case"superseded":return"superseded";case"unresolved":return"inconclusive";default:return"open"}}function hx(t){switch(t){case"running":return"running";case"ready-for-approval":return"ready-for-approval";case"escalated":return"escalated";case"approved":return"approved";case"rejected":return"rejected";case"leader-timeout":return"leader-timeout";default:return"error"}}function yc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function vc(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function vM(t){let e=[];for(let r of t.aggregatedVotes){if(r.status==="accepted")continue;let n={agree:0,disagree:0,abstain:0,revise:0,total:0};for(let o of Object.values(r.votes))switch(n.total+=1,o.vote){case"agree":n.agree+=1;break;case"disagree":n.disagree+=1;break;case"abstain":n.abstain+=1;break;case"revise":n.revise+=1;break}e.push({title:r.title,severity:r.severity,status:r.status,proposerIds:r.proposers,...r.location!==void 0?{location:r.location}:{},votes:n})}return e}function _M(t){let e=0;for(let r of t){let n=r.id.match(/^P(\d+)$/);if(n){let o=Number.parseInt(n[1],10);Number.isFinite(o)&&o>e&&(e=o)}}return e+1}function fx(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function bM(t,e){let r=0,n=0,o=[];for(let a of e){let c=t.votes.get(a);if(!c){o.push({participantId:a,vote:"missing"});continue}o.push({participantId:a,vote:c.vote,...c.reason!==void 0?{reason:c.reason}:{}}),c.vote==="agree"?r+=1:c.vote==="abstain"&&(n+=1)}let s=e.length-n,i=[];for(let a of o)a.vote==="agree"||a.vote==="abstain"||i.push(`${a.participantId} ${a.vote}`);return{agree:r,denominator:s,perParticipant:o,...i.length>0?{dissentSummary:i.join(", ")}:{}}}function wM(t){let e=new Map;for(let r of t.config.participants)e.set(r,{proposed:0,consensusReceived:0,revisesProposed:0,abstains:0});for(let r of t.ledger.proposals.values())if(r.status!=="merged"){for(let n of r.proposerIds){let o=e.get(n);o&&(o.proposed+=1,r.status==="consensus"&&(o.consensusReceived+=1))}for(let[n,o]of r.votes){let s=e.get(n);s&&(o.vote==="revise"&&(s.revisesProposed+=1),o.vote==="abstain"&&(s.abstains+=1))}}return Array.from(e.entries()).map(([r,n])=>({participantId:r,proposed:n.proposed,consensusReceived:n.consensusReceived,revisesProposed:n.revisesProposed,abstains:n.abstains}))}function mx(t,e){let r=[],n=[],o=[],s=[],i=[];for(let a of t.aggregatedVotes){let c=t.config.participants.filter(m=>!a.proposers.includes(m)),u=c.map(m=>{let g=a.votes[m];return g?{participantId:m,vote:g.vote,...g.reason!==void 0?{reason:g.reason}:{}}:{participantId:m,vote:"missing"}}),l=0,d=0;for(let m of u)m.vote==="agree"?l+=1:m.vote==="abstain"&&(d+=1);let p=c.length-d;r.push({proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,accepted:a.status==="accepted"}),a.status==="accepted"?n.push({id:a.proposalId,proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,finalStatement:""}):a.status==="rejected"||a.status==="withdrawn-by-author"?o.push({id:a.proposalId,title:a.title,severity:a.severity,rejectionReason:a.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:u}):a.status==="open"&&s.push({id:a.proposalId,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,perParticipant:u}),u.some(m=>m.vote!=="agree"&&m.vote!=="abstain")&&a.status!=="accepted"&&i.push({proposalTitle:a.title,severity:a.severity,perParticipant:u})}return{topic:t.config.topic,rounds:t.rounds,maxRounds:t.config.maxRounds,status:hx(t.status),participantIds:t.config.participants,individualPaths:Object.values(t.documentPaths.individual),debatePath:t.documentPaths.debate,...t.documentPaths.synthesis!==void 0?{synthesisPath:t.documentPaths.synthesis}:{},proposals:r,contributionSummary:[],dissentDetails:i,acceptedItems:n,rejectedItems:o,openItems:s}}var xM=/<proposals>([\s\S]*?)<\/proposals>/i,SM=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,$M=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function kM(t){let e=xM.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(SM.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp($M.source,"g"),l;for(;(l=u.exec(i))!==null;)c[l[1]]=l[2];let d=c.id,p=c.title,f=c.severity;if(!d||!p||!f)continue;let m={id:d,title:p,severity:f,...c.location?{location:c.location}:{},...a.length>0?{description:a}:{}};n.push(m)}return n}function PM(){return["You are a participant in the individual-review phase of a structured multi-AI debate.","Produce a concise review of the stated topic and propose concrete findings.","Findings must be emitted inside a `<proposals>` XML block using the exact shape:","<proposals>",' <item id="P1" title="Short title" severity="CRITICAL|HIGH|MEDIUM|LOW" location="file:line or component">'," Multi-line description / evidence."," </item>","</proposals>","Rules:","- Do NOT emit `<votes>` in this phase.","- Use stable, unique `id` attributes (e.g. P1, P2).","- Severity labels are free-form but stick to the four levels above.","- Description text is AI-native; the moderator preserves it verbatim."].join(`
308
+ `)}function TM(t){let e=[];if(e.push(`Topic: ${t.config.topic}`),t.goal&&e.push(`Goal: ${t.goal}`),e.push(`Scope: ${t.config.scope}`),t.files.length>0){e.push("Files examined:");for(let r of t.files)e.push(` - ${r}`)}return t.individualReviewPrompt&&(e.push(""),e.push(t.individualReviewPrompt)),e.push(""),e.push("Return your review followed by the required `<proposals>` block."),e.join(`
309
+ `)}function EM(t){let e=[];if(e.push(`Structured debate \u2014 round ${t.round} of ${t.maxRounds}.`),e.push(`Topic: ${t.topic}`),e.push(`Scope: ${t.scope}`),t.previousVoteIssues&&t.previousVoteIssues.length>0){e.push(""),e.push("Previous round vote issues in your response:");for(let r of t.previousVoteIssues)e.push(`- ${r}`);e.push("Correct these issues in this round. Every open proposal still needs an explicit vote.")}e.push(""),e.push("Open proposals:");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`),r.description&&e.push(` ${r.description}`);e.push(""),e.push("Respond with your analysis followed by a `<votes>` block:"),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`. Vote on every open proposal."),e.join(`
310
+ `)}function RM(t){let e=[];e.push("Your previous response did not include a valid `<votes>` block."),e.push(`Problem: ${t.errorKind}.`),t.errorDetails&&e.push(`Details: ${t.errorDetails}`),e.push("Reply with ONLY the `<votes>` block. Do not include prose."),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`."),e.join(`
311
+ `)}function IM(t){return t.map(e=>`${e.proposalId??"unparsed entry"}: ${e.reason}`)}function AM(t){let e=[];e.push(`## Round ${t.round} / ${t.maxRounds}`),e.push(""),e.push("### Proposal Ledger (open at round start)");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`);e.push(""),e.push("### Turns");for(let r of t.turns)e.push(""),e.push(`#### [${r.participantId}]${r.failed?" (failed)":""}`),e.push(r.text);e.push(""),e.push("### Aggregation");for(let r of t.aggregation){let o=t.ledger.proposals.get(r.proposalId)?.status??"open";e.push(`- ${r.proposalId} \u2192 ${o} (${r.verdict}; agree=${r.tally.agree}, disagree=${r.tally.disagree}, abstain=${r.tally.abstain}, revise=${r.tally.revise}, missing=${r.tally.missing})`)}return e.join(`
312
+ `)}function CM(t,e){let n=[`## ${e.t("moderator.narration.aliasClarification")}`];if(t.mergesApplied.length>0){n.push(""),n.push("Applied merges:");for(let o of t.mergesApplied)n.push(`- ${o.alias} \u2192 ${o.primary} (same=${o.voteBreakdown.same}, different=${o.voteBreakdown.different}, unsure=${o.voteBreakdown.unsure}, missing=${o.voteBreakdown.missing})`)}if(t.undecided.length>0){n.push(""),n.push("Undecided pairs (kept separate):");for(let o of t.undecided)n.push(`- ${o.pair.proposalA} \u2194 ${o.pair.proposalB} (${o.reason})`)}return n.join(`
313
+ `)}var gx=18e4;function js(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${gx/1e3}s)`)),gx))])}function _x(t){return new Rn({tools:Si(),baseDir:t})}var Rp,yx;function bx(t){return(!Rp||yx!==t)&&(Rp=new Po,yx=t),Rp}var Ms;function _c(t,e){if(Ms&&Ms.registry===t&&Ms.hostKind===e)return Ms.bridge;let r=new Rn({tools:Si(),baseDir:process.cwd()}),n=Kw({registry:t,readOnlyAdapter:r,hostKind:e});return Ms={bridge:n,registry:t,hostKind:e},n}var vx=new Map;function wx(t){let e=vx.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new co({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return vx.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function xx(t,e,r){let n=.7;if(r&&e){for(let o of r)e.updateQuality(t.id,o.provider,{score:o.score,evaluator:"claude",feedback:o.feedback});n=r.reduce((o,s)=>o+s.score,0)/r.length}else if(e){let o=new Map;for(let a of t.turns){if(a.speaker==="claude")continue;let c=t.turns.filter(d=>d.turnNumber<a.turnNumber).map(d=>({speaker:d.speaker,content:d.content})),u=Ao(a.content,c,t.topic),l=o.get(a.speaker)??[];l.push(u.score),o.set(a.speaker,l)}let s=0,i=0;for(let[a,c]of o){let u=c.reduce((l,d)=>l+d,0)/c.length;e.updateQuality(t.id,a,{score:u,evaluator:"auto_rule_based",feedback:`Auto-aggregated from ${c.length} turns`}),s+=u,i++}i>0&&(n=s/i)}return{avgQuality:n}}function bc(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function Sx(t,e){let r=Qa.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),o=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(o.id,"in_progress");let s=e.debateEngine,i=s.create({topic:r.topic,providerIds:r.providers,goal:r.goal}),a=!!(r.goal&&r.validator),c=a?e.registry.get(r.validator):void 0,u=a?r.min_rounds??2:r.max_rounds;return(async()=>{try{let l="";for(let p=0;p<r.max_rounds;p++){for(let[f,m]of n){let g=s.buildPromptForProvider(i.id,f);l&&(g+=`
233
314
 
234
315
  Validator feedback from previous round:
235
- ${l}`);let m=await on(e.readOnlyAdapter.chat(g,{prompt:y}),f);s.addTurn(i.id,f,m.text)}if(a&&c&&p+1>=u){let f=s.buildTurnTranscript(i.id),g=`Evaluate this debate against the goal: "${r.goal}"
316
+ ${l}`);let y=await js(e.readOnlyAdapter.chat(m,{prompt:g}),f);s.addTurn(i.id,f,y.text)}if(a&&c&&p+1>=u){let f=s.buildTurnTranscript(i.id),m=`Evaluate this debate against the goal: "${r.goal}"
236
317
 
237
318
  Current discussion:
238
319
  ${f}
@@ -244,12 +325,12 @@ Respond in JSON:
244
325
  "accuracy": true/false,
245
326
  "consistency": true/false,
246
327
  "feedback": "..."
247
- }`,y=await on(e.readOnlyAdapter.chat(c,{prompt:g}),c.id);try{let m=JSON.parse(y.text);if(m.goalAchievement&&m.completeness&&m.accuracy&&m.consistency)break;l=String(m.feedback??"")}catch{l=y.text}}}let d=Yn(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=q(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
328
+ }`,g=await js(e.readOnlyAdapter.chat(c,{prompt:m}),c.id);try{let y=JSON.parse(g.text);if(y.goalAchievement&&y.completeness&&y.accuracy&&y.consistency)break;l=String(y.feedback??"")}catch{l=g.text}}}let d=bc(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=M(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
248
329
  **Session ID:** ${o.id}
249
330
  **Topic:** ${r.topic}
250
331
  **Participants:** ${r.providers.join(", ")}
251
332
 
252
- Use \`agent_debate_status\` to check progress.`}]}}async function Fx(t,e){let r=Ia.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${n.id}
333
+ Use \`agent_debate_status\` to check progress.`}]}}async function $x(t,e){let r=ec.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${n.id}
253
334
  **Type:** ${n.type}
254
335
  **Status:** ${n.status}
255
336
  **Created:** ${n.createdAt}
@@ -259,7 +340,7 @@ Use \`agent_debate_status\` to check progress.`}]}}async function Fx(t,e){let r=
259
340
 
260
341
  ---
261
342
 
262
- ${n.result}`),{content:[{type:"text",text:o}]}}async function Ux(t,e){let r=Aa.parse(t),n=new _o(e.registry,e.readOnlyAdapter);try{let o=await n.validate({items:r.items.map(i=>({providerId:i.provider,content:i.content,task:i.task})),validators:r.validators?.map(i=>e.registry.get(i)),criteria:r.criteria}),s=`**Cross-Validation ${o.overallPass?"PASSED":"FAILED"}**
343
+ ${n.result}`),{content:[{type:"text",text:o}]}}async function kx(t,e){let r=Xa.parse(t),n=new Eo(e.registry,e.readOnlyAdapter);try{let o=await n.validate({items:r.items.map(i=>({providerId:i.provider,content:i.content,task:i.task})),validators:r.validators?.map(i=>e.registry.get(i)),criteria:r.criteria}),s=`**Cross-Validation ${o.overallPass?"PASSED":"FAILED"}**
263
344
 
264
345
  `;for(let i of o.reviews)s+=`### ${i.targetProvider} reviewed by ${i.reviewerProvider}
265
346
  `,s+=`**Result:** ${i.passed?"PASS":"FAIL"}
@@ -269,35 +350,13 @@ ${n.result}`),{content:[{type:"text",text:o}]}}async function Ux(t,e){let r=Aa.p
269
350
  `;return o.conflicts.length>0&&(s+=`## Conflicts
270
351
  ${o.conflicts.map(i=>`- ${i}`).join(`
271
352
  `)}
272
- `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${q(o)}`}],isError:!0}}}async function Vx(t,e){let r=Da.parse(t);for(let s of r.providers)s!=="claude"&&e.registry.get(s);let n;return r.save_document&&(n=(await e.documentManager.createDebateDocument({topic:r.topic,providers:r.providers,goal:r.goal})).id),{content:[{type:"text",text:`**Debate created**
353
+ `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${M(o)}`}],isError:!0}}}async function Px(t,e){let r=tc.parse(t);for(let s of r.providers)s!=="claude"&&e.registry.get(s);let n;return r.save_document&&(n=(await e.documentManager.createDebateDocument({topic:r.topic,providers:r.providers,goal:r.goal})).id),{content:[{type:"text",text:`**Debate created**
273
354
  **Debate ID:** ${e.debateEngine.create({topic:r.topic,providerIds:r.providers,goal:r.goal,documentId:n}).id}
274
355
  **Topic:** ${r.topic}
275
356
  **Participants:** ${r.providers.join(", ")}${n?`
276
- **Document ID:** ${n}`:""}`}]}}async function Wx(t,e){let r=Oa.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};if(n.status==="concluded")return{content:[{type:"text",text:`Debate already concluded: ${r.debate_id}`}],isError:!0};if(r.provider==="claude"){if(!r.claude_comment)return{content:[{type:"text",text:'provider: "claude" requires claude_comment to be set.'}],isError:!0};e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment});let f=Ld(e,r.debate_id);return{content:[{type:"text",text:`**[claude]:** ${r.claude_comment}${f.text}`}]}}let o=e.registry.get(r.provider);r.claude_comment&&(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}));let s=e.debateEngine.buildPromptForProvider(r.debate_id,r.provider),i=e.traceWriter?{candidateProviders:n.providerIds,selectedProvider:r.provider,selectionReason:`Debate turn: ${r.provider}'s turn to respond`,memoryHit:!1}:void 0,a=performance.now(),c;try{c=await e.readOnlyAdapter.chat(o,{prompt:s})}catch(f){let g=Math.round(performance.now()-a),y=q(f);return e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!1,charLength:0,error:y},latencyMs:g,reasoning:i}),{content:[{type:"text",text:`**Debate turn failed (${r.provider}):** ${y}`}],isError:!0}}let u=Math.round(performance.now()-a);e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!0,charLength:c.text.length},latencyMs:u,reasoning:i});let l=n.turns.map(f=>({speaker:f.speaker,content:f.content})),d=wo(c.text,l,n.topic);e.traceWriter&&e.traceWriter.updateQuality(n.id,r.provider,{score:d.score,evaluator:"auto_rule_based",feedback:JSON.stringify(d.breakdown)}),e.debateEngine.addTurn(r.debate_id,r.provider,c.text),n.documentId&&await e.documentManager.addComment(n.documentId,{author:r.provider,content:c.text});let p=Ld(e,r.debate_id);return{content:[{type:"text",text:`**[${r.provider}]:** ${c.text}
277
-
278
- _Quality: ${d.score.toFixed(2)}_${p.text}`}]}}function Zd(t,e){let r=`${t} ${e??""}`.toLowerCase(),n=[{patterns:[/\breview\b/,/\bcode\s*quality\b/,/\bsecurity\b/,/\baudit\b/,/리뷰/,/보안/,/코드\s*품질/],agent:"agestra-reviewer"},{patterns:[/\bdesign\b/,/\barchitect/,/\bstructur/,/설계/,/아키텍처/,/구조/],agent:"agestra-designer"},{patterns:[/\bidea\b/,/\bimprov/,/\bcompare\b/,/\balternativ/,/\bbrainstorm/,/개선/,/아이디어/,/비교/,/대안/],agent:"agestra-ideator"},{patterns:[/\bverif/,/\bvalidat/,/\bqa\b/,/\btest\b/,/\bcheck\b/,/검증/,/테스트/,/확인/],agent:"agestra-qa"}];for(let o of n)if(o.patterns.some(s=>s.test(r)))return o.agent;return null}function Bx(t,e){return Zd(t,e)==="agestra-reviewer"}function Fa(t,e){let r=[],n=[];for(let o of t){if(o==="claude"){r.push(o);continue}if(e.registry.get(o).type==="ollama"){n.push({id:o,reason:"Excluded from review workflows due to low-fidelity review output."});continue}r.push(o)}return{included:r,excluded:n}}function Ua(t){return t.length===0?"":`
279
- **Excluded Providers:** ${t.map(r=>`${r.id} (${r.reason})`).join(", ")}`}function Hx(t,e=!1){return t?`
280
- **Specialist:** ${t}
281
- **Specialist Status:** ${e?"Selected and applied to the Claude host-backed debate turn.":"Selection only; no autonomous specialist turn was executed in moderated mode."}`:""}async function _r(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function Va(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function Wa(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
282
-
283
- **Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
284
-
285
- **Raw response:**
286
-
287
- ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function Gx(t,e,r,n,o){if(!e)return;let s=await t.documentManager.createReview({files:[],rules:[`Independent review from ${o.provider}`,`Parent document: ${e}`,...r?[`Debate ID: ${r}`]:[]],provider:o.provider,topic:`review-${e.slice(0,12)}`});await t.documentManager.addComment(s.id,{author:"Moderator",content:`## Review Target
288
-
289
- Parent document: ${e}${r?`
290
- Debate ID: ${r}`:""}
291
-
292
- ## Reviewed Content
357
+ **Document ID:** ${n}`:""}`}]}}async function Tx(t,e){let r=rc.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};if(n.status==="concluded")return{content:[{type:"text",text:`Debate already concluded: ${r.debate_id}`}],isError:!0};if(r.provider==="claude")return r.claude_comment?(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}),{content:[{type:"text",text:`**[claude]:** ${r.claude_comment}`}]}):{content:[{type:"text",text:'provider: "claude" requires claude_comment to be set.'}],isError:!0};let o=e.registry.get(r.provider);r.claude_comment&&(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}));let s=e.debateEngine.buildPromptForProvider(r.debate_id,r.provider),i=e.traceWriter?{candidateProviders:n.providerIds,selectedProvider:r.provider,selectionReason:`Debate turn: ${r.provider}'s turn to respond`,memoryHit:!1}:void 0,a=performance.now(),c;try{c=await e.readOnlyAdapter.chat(o,{prompt:s})}catch(p){let f=Math.round(performance.now()-a),m=M(p);return e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!1,charLength:0,error:m},latencyMs:f,reasoning:i}),{content:[{type:"text",text:`**Debate turn failed (${r.provider}):** ${m}`}],isError:!0}}let u=Math.round(performance.now()-a);e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!0,charLength:c.text.length},latencyMs:u,reasoning:i});let l=n.turns.map(p=>({speaker:p.speaker,content:p.content})),d=Ao(c.text,l,n.topic);return e.traceWriter&&e.traceWriter.updateQuality(n.id,r.provider,{score:d.score,evaluator:"auto_rule_based",feedback:JSON.stringify(d.breakdown)}),e.debateEngine.addTurn(r.debate_id,r.provider,c.text),n.documentId&&await e.documentManager.addComment(n.documentId,{author:r.provider,content:c.text}),{content:[{type:"text",text:`**[${r.provider}]:** ${c.text}
293
358
 
294
- ${n}`});let i=o.rawResponse?`
295
-
296
- **Raw response:**
297
-
298
- ${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${Va(o.outcome)}**
299
-
300
- ${Wa(o.outcome)}${i}`}),s.id}async function Jx(t,e){let r=Ma.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};r.summary&&(e.debateEngine.addTurn(r.debate_id,"claude",r.summary),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude (Summary)",content:r.summary})),e.debateEngine.conclude(r.debate_id);let{avgQuality:o}=Zx(n,e.traceWriter,r.quality_scores),s=Yn(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
359
+ _Quality: ${d.score.toFixed(2)}_`}]}}async function Ex(t,e){let r=nc.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};r.summary&&(e.debateEngine.addTurn(r.debate_id,"claude",r.summary),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude (Summary)",content:r.summary})),e.debateEngine.conclude(r.debate_id);let{avgQuality:o}=xx(n,e.traceWriter,r.quality_scores),s=bc(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
301
360
  **Debate ID:** ${r.debate_id}
302
361
  **Topic:** ${n.topic}
303
362
  **Turns:** ${n.turns.length}`;return n.documentId&&(i+=`
@@ -305,57 +364,44 @@ ${Wa(o.outcome)}${i}`}),s.id}async function Jx(t,e){let r=Ma.parse(t),n=e.debate
305
364
 
306
365
  ---
307
366
 
308
- ${s}`,{content:[{type:"text",text:i}]}}async function Kx(t,e){let r=Na.parse(t),n=Bx(r.topic,r.goal)?Fa(r.providers,e):{included:[...r.providers],excluded:[]},o=n.included,s=Ua(n.excluded);if(o.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${s}`}],isError:!0};let i=new Map;for(let y of o){let m=e.registry.get(y);if(!m.isAvailable())return{content:[{type:"text",text:`Provider is registered but unavailable for moderated debate: ${y}`}],isError:!0};i.set(y,m)}let a=r.specialist??Zd(r.topic,r.goal),c=Hx(a,o.includes("claude")),u;r.save_document&&(u=(await e.documentManager.createDebateDocument({topic:r.topic,providers:o,goal:r.goal})).id,await _r(e,u,"Moderator",`## Debate Setup
309
-
310
- **Topic:** ${r.topic}
311
- **Participants:** ${o.join(", ")}${s}${c}${r.goal?`
312
- **Goal:** ${r.goal}`:""}`));let d=e.debateEngine.create({topic:r.topic,providerIds:o,goal:r.goal,documentId:u}).id,p=[];for(let y=1;y<=r.max_rounds;y++){let m=[];for(let _ of o){let w=i.get(_),k=e.debateEngine.buildPromptForProvider(d,_),P=_==="claude"&&a?`You are participating in a moderated multi-provider debate. Adopt the perspective of ${a} while remaining an independent participant. Respond directly to the topic and prior turns.`:void 0;try{let U=await on(e.readOnlyAdapter.chat(w,{prompt:k,system:P}),_);e.debateEngine.addTurn(d,_,U.text),u&&await e.documentManager.addComment(u,{author:_,content:U.text}),m.push(`**${_}:** ${U.text.slice(0,200)}${U.text.length>200?"...":""}`)}catch(U){let Z=q(U);m.push(`**${_}:** [Skipped: ${Z}]`)}}let b=e.debateEngine.getState(d);if(b&&b.turns.length>=2){let _=e.consensusDetector.analyzeConsensus(b);e.debateEngine.recordConsensusCheck(d,_);let w=`### Round ${y}
313
- ${m.join(`
314
- `)}
315
- **Consensus:** ${_.reason}`;if(p.push(w),await _r(e,u,`Moderator (Round ${y} Summary)`,w),_.reached){let k=Yn(e,d,{topic:r.topic,providerIds:o}),P=`**Moderated debate concluded \u2014 consensus reached in round ${y}**
316
- **Topic:** ${r.topic}
317
- **Participants:** ${o.join(", ")}${s}${c}
318
-
319
- ${p.join(`
367
+ ${s}`,{content:[{type:"text",text:i}]}}async function Rx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function wc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function xc(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
320
368
 
321
- `)}
369
+ **Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
322
370
 
323
- ---
371
+ **Raw response:**
324
372
 
325
- ${k}`;return await _r(e,u,"Moderator (Final Summary)",P),{content:[{type:"text",text:`${P}${u?`
373
+ ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function Ix(t,e,r,n,o){if(!e)return;let s=await t.documentManager.createReview({files:[],rules:[`Independent review from ${o.provider}`,`Parent document: ${e}`,...r?[`Debate ID: ${r}`]:[]],provider:o.provider,topic:`review-${e.slice(0,12)}`});await t.documentManager.addComment(s.id,{author:"Moderator",content:`## Review Target
326
374
 
327
- **Document ID:** ${u}`:""}`}]}}}else{let _=`### Round ${y}
328
- ${m.join(`
329
- `)}`;p.push(_),await _r(e,u,`Moderator (Round ${y} Summary)`,_)}}let f=Yn(e,d,{topic:r.topic,providerIds:o}),g=`**Moderated debate concluded \u2014 max rounds reached (${r.max_rounds})**
330
- **Topic:** ${r.topic}
331
- **Participants:** ${o.join(", ")}${s}${c}
375
+ Parent document: ${e}${r?`
376
+ Debate ID: ${r}`:""}
332
377
 
333
- ${p.join(`
378
+ ## Reviewed Content
334
379
 
335
- `)}
380
+ ${n}`});let i=o.rawResponse?`
336
381
 
337
- ---
382
+ **Raw response:**
338
383
 
339
- ${f}`;return await _r(e,u,"Moderator (Final Summary)",g),{content:[{type:"text",text:`${g}${u?`
384
+ ${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${wc(o.outcome)}**
340
385
 
341
- **Document ID:** ${u}`:""}`}]}}function PI(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
342
- ${bp}`}function EI(t){let e=Pn(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=Dx.safeParse(e);if(!r.success)return{kind:"parseError",rawResponse:t,reason:`Response JSON did not match review contract: ${r.error.message}`};let{agrees:n,feedback:o,suggestions:s}=r.data;return n?{kind:"agree",feedback:o,suggestions:s}:{kind:"disagree",feedback:o,suggestions:s}}async function Qx(t,e){let r=ja.parse(t),n=Fa(r.providers,e),o=n.included,s=[...n.excluded],i=r.debate_id?e.debateEngine.getState(r.debate_id):void 0,a=i?.documentId;if(r.debate_id&&i){let _=new Set(e.debateEngine.getActiveProviders(r.debate_id)),w=[];for(let k of o)if(k==="claude"||_.has(k))w.push(k);else{let P=(i.unavailableProviders??[]).find(U=>U.providerId===k);s.push({id:k,reason:P?`Marked unavailable for this debate: ${P.reason}`:"Not currently active in this debate."})}o=w}let c=Ua(s);if(o.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${c}`}],isError:!0};let u=PI(r.review_prompt),l=[],d=o.map(async _=>{if(_==="claude")return null;let w=e.registry.get(_),k=`${u}
386
+ ${xc(o.outcome)}${i}`}),s.id}function DM(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
387
+ ${mf}`}function zM(t){let e=En(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=zw.safeParse(e);if(!r.success)return{kind:"parseError",rawResponse:t,reason:`Response JSON did not match review contract: ${r.error.message}`};let{agrees:n,feedback:o,suggestions:s}=r.data;return n?{kind:"agree",feedback:o,suggestions:s}:{kind:"disagree",feedback:o,suggestions:s}}async function Ax(t,e){let r=oc.parse(t),n=[...r.providers],o=[],s=r.debate_id?e.debateEngine.getState(r.debate_id):void 0,i=s?.documentId;if(r.debate_id&&s){let _=new Set(e.debateEngine.getActiveProviders(r.debate_id)),S=[];for(let v of n)if(v==="claude"||_.has(v))S.push(v);else{let k=(s.unavailableProviders??[]).find(x=>x.providerId===v);o.push({id:v,reason:k?`Marked unavailable for this debate: ${k.reason}`:"Not currently active in this debate."})}n=S}let a=o.length===0?"":`
388
+ **Excluded Providers:** ${o.map(_=>`${_.id} (${_.reason})`).join(", ")}`;if(n.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${a}`}],isError:!0};let c=DM(r.review_prompt),u=[],l=n.map(async _=>{if(_==="claude")return null;let S=e.registry.get(_),v=`${c}
343
389
 
344
390
  ---
345
391
 
346
- ${r.document}`,P,U;try{let j=await on(e.readOnlyAdapter.chat(w,{prompt:k}),_);P=j.text,U=EI(j.text)}catch(j){let Se=q(j);if(U={kind:"unavailable",reason:Se},r.debate_id&&i){let Q=j instanceof me?`Provider reported unavailable: ${Se}`:`Chat failed: ${Se}`;e.debateEngine.markProviderUnavailable(r.debate_id,_,Q),i=e.debateEngine.getState(r.debate_id)}}let Z={provider:_,outcome:U,rawResponse:P};if(Z.linkedDocumentId=await Gx(e,a,r.debate_id,r.document,Z),a){let j=Wa(Z.outcome),Se=Z.linkedDocumentId?`
392
+ ${r.document}`,k,x;try{let O=await js(e.readOnlyAdapter.chat(S,{prompt:v}),_);k=O.text,x=zM(O.text)}catch(O){let Z=M(O);if(x={kind:"unavailable",reason:Z},r.debate_id&&s){let De=O instanceof me?`Provider reported unavailable: ${Z}`:`Chat failed: ${Z}`;e.debateEngine.markProviderUnavailable(r.debate_id,_,De),s=e.debateEngine.getState(r.debate_id)}}let z={provider:_,outcome:x,rawResponse:k};if(z.linkedDocumentId=await Ix(e,i,r.debate_id,r.document,z),i){let O=xc(z.outcome),Z=z.linkedDocumentId?`
347
393
 
348
- **Independent review document:** ${Z.linkedDocumentId}`:"";await e.documentManager.addComment(a,{author:`${_} (review)`,content:`**${Va(Z.outcome)}**
394
+ **Independent review document:** ${z.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${_} (review)`,content:`**${wc(z.outcome)}**
349
395
 
350
- ${j}${Se}`})}return Z}),p=await Promise.all(d);for(let _ of p)_&&l.push(_);let f=l.filter(_=>_.outcome.kind==="agree"||_.outcome.kind==="disagree"),g=l.length>0&&f.length===l.length&&f.every(_=>_.outcome.kind==="agree"),y=l.filter(_=>_.outcome.kind==="parseError"||_.outcome.kind==="unavailable"),b=`**Document Review** \u2014 ${g?"ALL AGREE \u2713":y.length>0&&f.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${c}
396
+ ${O}${Z}`})}return z}),d=await Promise.all(l);for(let _ of d)_&&u.push(_);let p=u.filter(_=>_.outcome.kind==="agree"||_.outcome.kind==="disagree"),f=u.length>0&&p.length===u.length&&p.every(_=>_.outcome.kind==="agree"),m=u.filter(_=>_.outcome.kind==="parseError"||_.outcome.kind==="unavailable"),y=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
351
397
 
352
- `;for(let _ of l)b+=`### ${_.provider}: ${Va(_.outcome)}
353
- `,b+=`${Wa(_.outcome)}
354
- `,_.linkedDocumentId&&(b+=`**Independent review document:** ${_.linkedDocumentId}
355
- `),b+=`
356
- `;if(!g){let _=y.length>0?`Revise the document addressing the feedback above. Note: ${y.length} provider(s) did not return a definite agree/disagree (parseError or unavailable) \u2014 they are NOT counted as agreement. Call \`agent_debate_review\` again with an updated document or a narrower providers list.`:"Revise the document addressing the feedback above, then call `agent_debate_review` again to check for consensus.";b+=`---
398
+ `;for(let _ of u)y+=`### ${_.provider}: ${wc(_.outcome)}
399
+ `,y+=`${xc(_.outcome)}
400
+ `,_.linkedDocumentId&&(y+=`**Independent review document:** ${_.linkedDocumentId}
401
+ `),y+=`
402
+ `;if(!f){let _=m.length>0?`Revise the document addressing the feedback above. Note: ${m.length} provider(s) did not return a definite agree/disagree (parseError or unavailable) \u2014 they are NOT counted as agreement. Call \`agent_debate_review\` again with an updated document or a narrower providers list.`:"Revise the document addressing the feedback above, then call `agent_debate_review` again to check for consensus.";y+=`---
357
403
 
358
- **Next step:** ${_}`}return await _r(e,a,"Moderator (Review Aggregation)",b),{content:[{type:"text",text:b}]}}async function Yx(t,e){let r=La.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};let n;try{n=e.cliWorkerManager.reviewChanges(r.task_id)}catch(s){return{content:[{type:"text",text:q(s)}],isError:!0}}let o=`**File Change Review**
404
+ **Next step:** ${_}`}return await Rx(e,i,"Moderator (Review Aggregation)",y),{content:[{type:"text",text:y}]}}async function Cx(t,e){let r=sc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};let n;try{n=e.cliWorkerManager.reviewChanges(r.task_id)}catch(s){return{content:[{type:"text",text:M(s)}],isError:!0}}let o=`**File Change Review**
359
405
  **Task ID:** ${r.task_id}
360
406
  **Worktree:** ${n.worktreePath}
361
407
  **Branch:** ${n.branch}
@@ -369,25 +415,25 @@ ${n.diffStat}
369
415
  ### Changes
370
416
  \`\`\`diff
371
417
  ${n.fullDiff}
372
- \`\`\``,{content:[{type:"text",text:o}]}}async function Xx(t,e){let r=Za.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{let n=e.cliWorkerManager.acceptChanges(r.task_id,r.message);return{content:[{type:"text",text:`**Changes accepted**
418
+ \`\`\``,{content:[{type:"text",text:o}]}}async function Dx(t,e){let r=ic.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{let n=e.cliWorkerManager.acceptChanges(r.task_id,r.message);return{content:[{type:"text",text:`**Changes accepted**
373
419
  **Task ID:** ${r.task_id}
374
420
  **Merged files:** ${n.merged.length}
375
421
 
376
422
  ${n.merged.map(o=>`- ${o}`).join(`
377
- `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${q(n)}`}],isError:!0}}}async function eb(t,e){let r=qa.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{e.cliWorkerManager.rejectChanges(r.task_id)}catch(o){return{content:[{type:"text",text:q(o)}],isError:!0}}let n=`**Changes rejected**
423
+ `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${M(n)}`}],isError:!0}}}async function zx(t,e){let r=ac.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{e.cliWorkerManager.rejectChanges(r.task_id)}catch(o){return{content:[{type:"text",text:M(o)}],isError:!0}}let n=`**Changes rejected**
378
424
  **Task ID:** ${r.task_id}`;return r.reason&&(n+=`
379
- **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}async function tb(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o={...r,debateEngine:jx(n),consensusDetector:Lx(),readOnlyAdapter:Nx(n)};switch(t){case"agent_debate_start":return qx(e,o);case"agent_debate_status":return Fx(e,o);case"agent_cross_validate":return Ux(e,o);case"agent_debate_create":return Vx(e,o);case"agent_debate_turn":return Wx(e,o);case"agent_debate_conclude":return Jx(e,o);case"agent_debate_review":return Qx(e,o);case"agent_debate_moderate":return Kx(e,o);case"agent_changes_review":return Yx(e,o);case"agent_changes_accept":return Xx(e,o);case"agent_changes_reject":return eb(e,o);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Fd={};We(Fd,{getTools:()=>RI,handleTool:()=>NI});var rb=h.object({files:h.array(h.string()).min(1).describe("File paths to include in the review"),rules:h.array(h.string()).describe("Review rules/guidelines to apply")}),nb=h.object({doc_id:h.string().describe("Document ID to request review for"),provider:h.union([h.string(),h.array(h.string()).min(1)]).describe("Provider ID(s) to perform the review")}),ob=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),sb=h.object({doc_id:h.string().describe("Document ID to comment on"),author:h.string().describe("Comment author name"),content:h.string().describe("Comment content")}),ib=h.object({doc_id:h.string().describe("Document ID to read")}),ab=h.object({title:h.string().describe("Document title"),content:h.string().describe("Document content (markdown)"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)")}),cb=h.object({});function RI(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:J(rb)},{name:"workspace_request_review",title:"Request Code Review",description:"Request AI provider(s) to perform a code review on an existing review document. Returns immediately with a session ID. Use workspace_review_status to check progress.",inputSchema:J(nb)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:J(ob)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:J(sb)},{name:"workspace_create_document",title:"Create Document",description:"Create a general-purpose workspace document with a title, content, and optional metadata. Use for independent analysis documents, aggregated reports, or any structured output.",inputSchema:J(ab)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:J(ib)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:J(cb)}]}async function zI(t,e){let r=rb.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
425
+ **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as OM}from"path";var MM="unknown";async function Ox(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new ao(OM(n,mo)),s=_c(r.registry,r.sessionContext?.hostKind??MM),i=r.moderatorEngine??wx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:bx(n),readOnlyAdapter:_x(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return Sx(e,a);case"agent_debate_status":return $x(e,a);case"agent_cross_validate":return kx(e,a);case"agent_debate_create":return Px(e,a);case"agent_debate_turn":return Tx(e,a);case"agent_debate_conclude":return Ex(e,a);case"agent_debate_review":return Ax(e,a);case"agent_changes_review":return Cx(e,a);case"agent_changes_accept":return Dx(e,a);case"agent_changes_reject":return zx(e,a);case pc:return Ow(e,a);case no:return Mw(e,a);case oo:return jw(e,a);case so:return Nw(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ap={};Ze(Ap,{getTools:()=>jM,handleTool:()=>BM});var Mx=h.object({files:h.array(h.string()).min(1).describe("File paths to include in the review"),rules:h.array(h.string()).describe("Review rules/guidelines to apply")}),jx=h.object({doc_id:h.string().describe("Document ID to request review for"),provider:h.union([h.string(),h.array(h.string()).min(1)]).describe("Provider ID(s) to perform the review")}),Nx=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),Lx=h.object({doc_id:h.string().describe("Document ID to comment on"),author:h.string().describe("Comment author name"),content:h.string().describe("Comment content")}),Fx=h.object({doc_id:h.string().describe("Document ID to read")}),Zx=h.object({title:h.string().describe("Document title"),content:h.string().describe("Document content (markdown)"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)")}),Ux=h.object({});function jM(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:V(Mx)},{name:"workspace_request_review",title:"Request Code Review",description:"Request AI provider(s) to perform a code review on an existing review document. Returns immediately with a session ID. Use workspace_review_status to check progress.",inputSchema:V(jx)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:V(Nx)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:V(Lx)},{name:"workspace_create_document",title:"Create Document",description:"Create a general-purpose workspace document with a title, content, and optional metadata. Use for independent analysis documents, aggregated reports, or any structured output.",inputSchema:V(Zx)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:V(Fx)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:V(Ux)}]}async function NM(t,e){let r=Mx.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
380
426
  **Document ID:** ${n.id}
381
427
  **Path:** ${n.path}
382
428
  **Files:** ${r.files.join(", ")}
383
- **Rules:** ${r.rules.length}`}]}}async function CI(t,e){let r=nb.parse(t),n=Array.isArray(r.provider)?r.provider:[r.provider],o=[];for(let c of n){let u=e.registry.get(c);o.push({id:c,provider:u})}let s=await e.documentManager.read(r.doc_id),i=e.sessionManager.createSession("review",{doc_id:r.doc_id,providers:n,completed:[],failed:[]});e.sessionManager.updateSessionStatus(i.id,"in_progress");let a=o.map(async({id:c,provider:u})=>{try{let l=await u.chat({prompt:`Please review the following document and provide feedback:
429
+ **Rules:** ${r.rules.length}`}]}}async function LM(t,e){let r=jx.parse(t),n=Array.isArray(r.provider)?r.provider:[r.provider],o=[];for(let c of n){let u=e.registry.get(c);o.push({id:c,provider:u})}let s=await e.documentManager.read(r.doc_id),i=e.sessionManager.createSession("review",{doc_id:r.doc_id,providers:n,completed:[],failed:[]});e.sessionManager.updateSessionStatus(i.id,"in_progress");let a=o.map(async({id:c,provider:u})=>{try{let l=await u.chat({prompt:`Please review the following document and provide feedback:
384
430
 
385
- ${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=q(l);try{await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:`**Review failed:** ${d}`})}catch{}let p=e.sessionManager.getSession(i.id);if(p){let f=p.config.failed||[];f.push(c),p.config.failed=f}}});return Promise.all(a).then(()=>{try{let c=e.sessionManager.getSession(i.id),u=c?.config.completed||[],l=c?.config.failed||[],d=`Completed: ${u.join(", ")||"none"}. Failed: ${l.join(", ")||"none"}.`,p=wc({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
431
+ ${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=M(l);try{await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:`**Review failed:** ${d}`})}catch{}let p=e.sessionManager.getSession(i.id);if(p){let f=p.config.failed||[];f.push(c),p.config.failed=f}}});return Promise.all(a).then(()=>{try{let c=e.sessionManager.getSession(i.id),u=c?.config.completed||[],l=c?.config.failed||[],d=`Completed: ${u.join(", ")||"none"}. Failed: ${l.join(", ")||"none"}.`,p=su({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
386
432
  **Session ID:** ${i.id}
387
433
  **Document ID:** ${r.doc_id}
388
434
  **Providers:** ${n.join(", ")}
389
435
 
390
- Use \`workspace_review_status\` with session_id to check progress.`}]}}async function AI(t,e){let r=ob.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=n.config.providers||[],s=n.config.completed||[],i=n.config.failed||[],a=o.filter(u=>!s.includes(u)&&!i.includes(u)),c=`**Review Session Status**
436
+ Use \`workspace_review_status\` with session_id to check progress.`}]}}async function FM(t,e){let r=Nx.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=n.config.providers||[],s=n.config.completed||[],i=n.config.failed||[],a=o.filter(u=>!s.includes(u)&&!i.includes(u)),c=`**Review Session Status**
391
437
  `;return c+=`**Session ID:** ${n.id}
392
438
  `,c+=`**Status:** ${n.status}
393
439
  `,c+=`**Document:** ${n.config.doc_id}
@@ -397,30 +443,30 @@ Use \`workspace_review_status\` with session_id to check progress.`}]}}async fun
397
443
  `,c+=`- Failed: ${i.join(", ")||"none"}
398
444
  `,c+=`- Pending: ${a.join(", ")||"none"}
399
445
  `,n.result&&(c+=`
400
- **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function II(t,e){let r=sb.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
446
+ **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function ZM(t,e){let r=Lx.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
401
447
  **Document ID:** ${r.doc_id}
402
448
  **Author:** ${r.author}
403
449
 
404
- ${r.content}`}]}}async function DI(t,e){let r=ab.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata});return{content:[{type:"text",text:`**Document created**
450
+ ${r.content}`}]}}async function UM(t,e){let r=Zx.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata});return{content:[{type:"text",text:`**Document created**
405
451
  **Document ID:** ${n.id}
406
452
  **Path:** ${n.path}
407
- **Title:** ${r.title}`}]}}async function OI(t,e){let r=ib.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
453
+ **Title:** ${r.title}`}]}}async function qM(t,e){let r=Fx.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
408
454
  **Path:** ${n.path}
409
455
 
410
- ${n.content}`}]}}async function MI(t,e){cb.parse(t);let r=await e.documentManager.list();if(r.length===0)return{content:[{type:"text",text:"No workspace documents found."}]};let n=`# Workspace Documents
456
+ ${n.content}`}]}}async function VM(t,e){Ux.parse(t);let r=await e.documentManager.list();if(r.length===0)return{content:[{type:"text",text:"No workspace documents found."}]};let n=`# Workspace Documents
411
457
 
412
458
  **Total:** ${r.length}
413
459
 
414
460
  `;for(let o of r){let s=o.content.slice(0,100).replace(/\n/g," ");n+=`- **${o.id}** \u2014 ${s}...
415
- `}return{content:[{type:"text",text:n}]}}async function NI(t,e,r){switch(t){case"workspace_create_review":return zI(e,r);case"workspace_request_review":return CI(e,r);case"workspace_review_status":return AI(e,r);case"workspace_add_comment":return II(e,r);case"workspace_create_document":return DI(e,r);case"workspace_read":return OI(e,r);case"workspace_list":return MI(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ud={};We(Ud,{getTools:()=>LI,handleTool:()=>FI});function Ba(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var jI=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function LI(){return[{name:"provider_list",title:"List AI Providers",description:"List all registered AI providers with their availability status and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"provider_health",title:"Check Provider Health",description:"Run health checks on AI providers. Optionally specify a provider ID, or omit to check all.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider ID to check (omit to check all)"}},required:[]}}]}async function ZI(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
461
+ `}return{content:[{type:"text",text:n}]}}async function BM(t,e,r){switch(t){case"workspace_create_review":return NM(e,r);case"workspace_request_review":return LM(e,r);case"workspace_review_status":return FM(e,r);case"workspace_add_comment":return ZM(e,r);case"workspace_create_document":return UM(e,r);case"workspace_read":return qM(e,r);case"workspace_list":return VM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Cp={};Ze(Cp,{getTools:()=>HM,handleTool:()=>GM});function Sc(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var WM=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function HM(){return[{name:"provider_list",title:"List AI Providers",description:"List all registered AI providers with their availability status and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"provider_health",title:"Check Provider Health",description:"Run health checks on AI providers. Optionally specify a provider ID, or omit to check all.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider ID to check (omit to check all)"}},required:[]}}]}async function KM(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
416
462
 
417
463
  `;t.sessionContext&&(r+=`## Host Session
418
464
  `,r+=`- **Host:** ${t.sessionContext.hostId} (${t.sessionContext.hostKind})
419
465
  `,r+=`- **Leader Provider:** ${t.sessionContext.leaderProviderId}
420
- `,r+=`- **Execution Mode:** ${Ba(t.sessionContext.executionMode,t.sessionContext.hostKind)}
466
+ `,r+=`- **Execution Mode:** ${Sc(t.sessionContext.executionMode,t.sessionContext.hostKind)}
421
467
  `,r+=`- **Participants:** ${t.sessionContext.participantProviderIds.join(", ")}
422
468
 
423
- `);for(let n of e){let o=n.isAvailable(),s=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):Qt(n,s),a=o?"Available":"Unavailable";r+=`## ${n.id} (${n.type})
469
+ `);for(let n of e){let o=n.isAvailable(),s=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):tr(n,s),a=o?"Available":"Unavailable";r+=`## ${n.id} (${n.type})
424
470
  `,r+=`- **Status:** ${a}
425
471
  `,r+=`- **Invocation:** ${i.invocation}
426
472
  `,r+=`- **Roles:** ${i.roles.join(", ")}
@@ -435,30 +481,32 @@ ${n.content}`}]}}async function MI(t,e){cb.parse(t);let r=await e.documentManage
435
481
  `,s.strengths.length>0&&(r+=`- **Strengths:** ${s.strengths.join(", ")}
436
482
  `),s.models.length>0&&(r+=`- **Models:** ${s.models.map(c=>c.name).join(", ")}
437
483
  `),r+=`
438
- `}return{content:[{type:"text",text:r}]}}async function qI(t,e){let r=jI.parse(t),n=r.provider?[e.registry.get(r.provider)]:e.registry.getAll();if(n.length===0)return{content:[{type:"text",text:"No providers to check."}]};let o=await Promise.all(n.map(async i=>{try{let a=await i.healthCheck();return{id:i.id,type:i.type,status:a.status,message:a.message,details:a.details,error:null}}catch(a){return{id:i.id,type:i.type,status:"error",message:q(a),details:void 0,error:q(a)}}})),s=`# Health Check Results
484
+ `}return{content:[{type:"text",text:r}]}}async function JM(t,e){let r=WM.parse(t),n=r.provider?[e.registry.get(r.provider)]:e.registry.getAll();if(n.length===0)return{content:[{type:"text",text:"No providers to check."}]};let o=await Promise.all(n.map(async i=>{try{let a=await i.healthCheck();return{id:i.id,type:i.type,status:a.status,message:a.message,details:a.details,error:null}}catch(a){return{id:i.id,type:i.type,status:"error",message:M(a),details:void 0,error:M(a)}}})),s=`# Health Check Results
439
485
 
440
486
  `;for(let i of o){let a=i.status==="ok"?"OK":i.status==="degraded"?"DEGRADED":"ERROR";s+=`## ${i.id} (${i.type})
441
487
  `,s+=`- **Status:** ${a}
442
488
  `,i.message&&(s+=`- **Message:** ${i.message}
443
489
  `),i.error&&(s+=`- **Error:** ${i.error}
444
490
  `),s+=`
445
- `}return{content:[{type:"text",text:s}]}}async function FI(t,e,r){switch(t){case"provider_list":return ZI(r);case"provider_health":return qI(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Vd={};We(Vd,{getTools:()=>VI,handleTool:()=>HI});var UI=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function VI(){return[{name:"ollama_models",title:"List Ollama Models",description:"List installed Ollama models with their sizes and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"ollama_pull",title:"Pull Ollama Model",description:"Download (pull) a model from the Ollama registry.",inputSchema:{type:"object",properties:{model:{type:"string",description:"Model name to download (e.g. 'llama3', 'codellama')"}},required:["model"]}}]}function ub(t){let e=t.ollamaProviderId||"ollama",r=t.registry.get(e);if(r.type!=="ollama")throw new Error(`Provider '${e}' is not an Ollama provider (type: ${r.type})`);return r}async function WI(t){let r=ub(t).getModels();if(r.length===0)return{content:[{type:"text",text:"No models installed. Use `ollama_pull` to download a model."}]};let n=`# Installed Ollama Models (${r.length})
491
+ `}return{content:[{type:"text",text:s}]}}async function GM(t,e,r){switch(t){case"provider_list":return KM(r);case"provider_health":return JM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var zp={};Ze(zp,{getTools:()=>lj,handleTool:()=>fj});import{existsSync as nj,readFileSync as oj}from"fs";import{join as sj}from"path";import{readFileSync as YM,existsSync as QM}from"fs";import{join as XM}from"path";var ej={ollama:{executionPolicy:"workspace-write",config:{host:fo,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Vt("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Vt("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Vt("claude-cli"),config:{timeout:12e4}}};async function uo(){let t=[{id:"ollama",type:"ollama",provider:new qr({id:"ollama",host:fo})},{id:"gemini",type:"gemini-cli",provider:new Vr({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Br({id:"codex"})},{id:"claude-cli",type:"claude-cli",provider:new Wr({id:"claude-cli"})}],e=[],r=[];await Promise.all(t.map(async o=>{try{await o.provider.initialize()}catch{}let s=o.provider.isAvailable();e.push({id:o.id,type:o.type,available:s}),s&&r.push(o.provider)}));let n=["ollama","gemini","codex","claude-cli"];return e.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),r.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),{results:e,providers:r}}function tj(t){if(!QM(t))return null;try{return JSON.parse(YM(t,"utf-8"))}catch{return null}}function rj(t){return t==="auto"?"auto":"default-only"}function qx(t,e,r){let n=XM(t,"providers.config.json"),o=tj(n),s=new Set(r.enabledIds??[]),i=new Map((o?.providers??[]).map(m=>[m.id,m])),a=e.map(m=>{let g=ej[m.type]||{executionPolicy:Vt(m.type),config:{}},y=i.get(m.id);return i.delete(m.id),{id:m.id,type:m.type,enabled:m.available&&s.has(m.id),executionPolicy:y?.executionPolicy??g.executionPolicy,config:{...y?.config??g.config}}});for(let m of i.values())a.push({...m,enabled:s.has(m.id)?m.enabled:!1});if(a.length===0)throw new Error("No providers available to write into providers.config.json");let c=a.find(m=>m.enabled),u=r.defaultProvider&&a.some(m=>m.id===r.defaultProvider&&m.enabled)?r.defaultProvider:void 0,l={selectionPolicy:rj(r.selectionPolicy??o?.selectionPolicy),...u!==void 0?{defaultProvider:u}:c!==void 0?{defaultProvider:c.id}:{},...r.locale!==void 0?{locale:r.locale}:o?.locale!==void 0?{locale:o.locale}:{},providers:a},d=o?JSON.stringify(o):null,p=JSON.stringify(l),f=d===null?"created":d===p?"unchanged":"updated";return!r.dryRun&&f!=="unchanged"&&Ue(n,l),{action:f,path:n,config:l}}function Vx(t,e){Dp(t,e)}function Dp(t,e,r){let n=[];for(let o of t)e.has(o.id)||r?.excludeIds?.has(o.id)||r?.excludeTypes?.has(o.type)||(e.register(o),n.push(o));return n}var ij=h.object({}),aj=h.object({enabled_providers:h.array(h.string()).describe("Provider IDs to enable for Agestra workflows."),default_provider:h.string().optional().describe("Default provider ID. Must be one of the enabled providers when supplied."),locale:h.enum(["ko","en","ja","zh"]).describe("UI language for moderator/setup-facing text."),selection_policy:h.enum(["default-only","auto"]).optional().default("default-only").describe("Provider selection policy stored in providers.config.json."),dry_run:h.boolean().optional().default(!1).describe("When true, compute the resulting config without writing it to disk.")});function cj(t){let e=sj(t,"providers.config.json");if(!nj(e))return null;try{return JSON.parse(oj(e,"utf-8"))}catch{return null}}function uj(t){if(!t)return["Current config: not found"];let e=t.providers.filter(r=>r.enabled);return[`Current config: ${e.length>0?"present":"present (no providers enabled)"}`,`Enabled providers: ${e.length>0?e.map(r=>r.id).join(", "):"(none)"}`,`Default provider: ${t.defaultProvider??"(none)"}`,`Locale: ${t.locale??"(default)"}`,`Selection policy: ${t.selectionPolicy}`]}function lj(){return[{name:"setup_status",title:"Read Agestra Setup Status",description:"Detect available AI providers and show the current Agestra setup state from providers.config.json.",inputSchema:{type:"object",properties:{},required:[]}},{name:"setup_apply",title:"Apply Agestra Setup",description:"Write the selected AI providers and locale into providers.config.json for Agestra workflows.",inputSchema:{type:"object",properties:{enabled_providers:{type:"array",items:{type:"string"},description:"Provider IDs to enable"},default_provider:{type:"string",description:"Default provider ID"},locale:{type:"string",enum:["ko","en","ja","zh"],description:"UI locale"},selection_policy:{type:"string",enum:["default-only","auto"],description:"Stored provider selection policy"},dry_run:{type:"boolean",description:"Preview without writing providers.config.json"}},required:["enabled_providers","locale"]}}]}async function dj(t){let e=t.workspaceBaseDir??process.cwd(),r=cj(e),{results:n}=await uo(),o=["# Agestra Setup"];if(o.push(""),o.push(...uj(r)),o.push(""),o.push("Detected providers:"),n.length===0)o.push("- (none detected)");else for(let s of n)o.push(`- ${s.id} (${s.type}) \u2014 ${s.available?"available":"unavailable"}`);return{content:[{type:"text",text:o.join(`
492
+ `)}]}}async function pj(t,e){let r=aj.parse(t),n=e.workspaceBaseDir??process.cwd(),{results:o}=await uo();if(o.length===0)return{content:[{type:"text",text:"No AI providers were detected, so setup could not be applied."}],isError:!0};let s=new Set(o.filter(l=>l.available).map(l=>l.id)),i=r.enabled_providers.filter(l=>!s.has(l));if(i.length>0)return{content:[{type:"text",text:`These providers are not currently available and cannot be enabled: ${i.join(", ")}`}],isError:!0};if(r.default_provider!==void 0&&!r.enabled_providers.includes(r.default_provider))return{content:[{type:"text",text:"`default_provider` must be included in `enabled_providers`."}],isError:!0};let a=qx(n,o,{enabledIds:r.enabled_providers,...r.default_provider!==void 0?{defaultProvider:r.default_provider}:{},locale:r.locale,selectionPolicy:r.selection_policy,dryRun:r.dry_run}),c=a.config.providers.filter(l=>l.enabled);return{content:[{type:"text",text:[r.dry_run?"# Agestra Setup Preview":"# Agestra Setup Applied","",`Config path: ${a.path}`,`Action: ${a.action}`,`Enabled providers: ${c.length>0?c.map(l=>l.id).join(", "):"(none)"}`,`Default provider: ${a.config.defaultProvider??"(none)"}`,`Locale: ${a.config.locale??"(default)"}`,`Selection policy: ${a.config.selectionPolicy}`].join(`
493
+ `)}]}}async function fj(t,e,r){switch(t){case"setup_status":return ij.parse(e),dj(r);case"setup_apply":return pj(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Op={};Ze(Op,{getTools:()=>hj,handleTool:()=>vj});var mj=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function hj(){return[{name:"ollama_models",title:"List Ollama Models",description:"List installed Ollama models with their sizes and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"ollama_pull",title:"Pull Ollama Model",description:"Download (pull) a model from the Ollama registry.",inputSchema:{type:"object",properties:{model:{type:"string",description:"Model name to download (e.g. 'llama3', 'codellama')"}},required:["model"]}}]}function Bx(t){let e=t.ollamaProviderId||"ollama",r=t.registry.get(e);if(r.type!=="ollama")throw new Error(`Provider '${e}' is not an Ollama provider (type: ${r.type})`);return r}async function gj(t){let r=Bx(t).getModels();if(r.length===0)return{content:[{type:"text",text:"No models installed. Use `ollama_pull` to download a model."}]};let n=`# Installed Ollama Models (${r.length})
446
494
 
447
495
  `;for(let o of r){let s=(o.size/1e9).toFixed(1);n+=`## ${o.name}
448
496
  `,n+=`- **Size:** ${s} GB
449
497
  `,o.strengths.length>0&&(n+=`- **Strengths:** ${o.strengths.join(", ")}
450
498
  `),n+=`
451
- `}return{content:[{type:"text",text:n}]}}async function BI(t,e){let r=UI.parse(t),n=ub(e);try{let o=n.getConnectionInfo().host,s=await fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.model,stream:!1})});if(!s.ok){let a=await s.text();return{content:[{type:"text",text:`**Pull failed**
499
+ `}return{content:[{type:"text",text:n}]}}async function yj(t,e){let r=mj.parse(t),n=Bx(e);try{let o=n.getConnectionInfo().host,s=await fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.model,stream:!1})});if(!s.ok){let a=await s.text();return{content:[{type:"text",text:`**Pull failed**
452
500
  **Model:** ${r.model}
453
501
  **Error:** HTTP ${s.status}: ${a}`}],isError:!0}}let i=await s.json();return{content:[{type:"text",text:`**Model pulled successfully**
454
502
  **Model:** ${r.model}
455
- **Status:** ${i.status||"success"}`}]}}catch(o){let s=q(o);return{content:[{type:"text",text:`**Pull failed**
503
+ **Status:** ${i.status||"success"}`}]}}catch(o){let s=M(o);return{content:[{type:"text",text:`**Pull failed**
456
504
  **Model:** ${r.model}
457
- **Error:** ${s}`}],isError:!0}}}async function HI(t,e,r){switch(t){case"ollama_models":return WI(r);case"ollama_pull":return BI(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Wd={};We(Wd,{getTools:()=>GI,handleTool:()=>QI});var lb=h.object({provider:h.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:h.string().describe("Prompt to send to the provider CLI"),timeout:h.number().int().positive().optional().describe("Timeout in ms (default: 300000)")}).strict(),db=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function GI(){return[{name:"cli_job_submit",title:"Submit CLI Job",description:"Submit a long-running CLI job to a provider. Returns a job ID immediately. Use cli_job_status to check progress.",inputSchema:J(lb)},{name:"cli_job_status",title:"Check CLI Job Status",description:"Check the status of a CLI job. Returns state, output (on completion), and stderr.",inputSchema:J(db)}]}async function JI(t,e){let r=lb.parse(t);return{content:[{type:"text",text:`**Job submitted**
505
+ **Error:** ${s}`}],isError:!0}}}async function vj(t,e,r){switch(t){case"ollama_models":return gj(r);case"ollama_pull":return yj(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Mp={};Ze(Mp,{getTools:()=>_j,handleTool:()=>xj});var Wx=h.object({provider:h.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:h.string().describe("Prompt to send to the provider CLI"),timeout:h.number().int().positive().optional().describe("Timeout in ms (default: 300000)")}).strict(),Hx=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function _j(){return[{name:"cli_job_submit",title:"Submit CLI Job",description:"Submit a long-running CLI job to a provider. Returns a job ID immediately. Use cli_job_status to check progress.",inputSchema:V(Wx)},{name:"cli_job_status",title:"Check CLI Job Status",description:"Check the status of a CLI job. Returns state, output (on completion), and stderr.",inputSchema:V(Hx)}]}async function bj(t,e){let r=Wx.parse(t);return{content:[{type:"text",text:`**Job submitted**
458
506
  **Job ID:** ${e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout})}
459
507
  **Provider:** ${r.provider}
460
508
 
461
- Use \`cli_job_status\` with this job_id to check progress.`}]}}async function KI(t,e){let r=db.parse(t),n=e.jobManager.getResult(r.job_id);if(!n)return{content:[{type:"text",text:`Job not found: ${r.job_id}`}],isError:!0};let o=`**Job ID:** ${n.id}
509
+ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function wj(t,e){let r=Hx.parse(t),n=e.jobManager.getResult(r.job_id);if(!n)return{content:[{type:"text",text:`Job not found: ${r.job_id}`}],isError:!0};let o=`**Job ID:** ${n.id}
462
510
  **State:** ${n.state}`;return n.exitCode!==void 0&&(o+=`
463
511
  **Exit Code:** ${n.exitCode}`),n.output&&(o+=`
464
512
 
@@ -468,10 +516,10 @@ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function KI
468
516
  ${n.output}`),n.error&&(o+=`
469
517
 
470
518
  **Stderr:**
471
- ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function QI(t,e,r){switch(t){case"cli_job_submit":return JI(e,r);case"cli_job_status":return KI(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Bd={};We(Bd,{getTools:()=>YI,handleTool:()=>XI});var pb=h.object({provider_id:h.string().optional(),task:h.string().optional(),trace_id:h.string().optional(),days_back:h.number().optional().default(7),limit:h.number().optional().default(50)}),fb=h.object({days_back:h.number().optional().default(30)}),mb=h.object({trace_id:h.string()});function YI(){return[{name:"trace_query",title:"Query Trace Records",description:"Query trace records with filtering. Returns recent provider interactions with latency, quality scores, and reasoning.",inputSchema:J(pb)},{name:"trace_summary",title:"Summarize Trace Stats",description:"Get quality and performance stats per provider and task type. Shows average quality scores, latency, and success rates.",inputSchema:J(fb)},{name:"trace_visualize",title:"Visualize Trace Flow",description:"Generate a Mermaid diagram showing the flow of a traced operation. Shows provider selection, execution, and quality assessment.",inputSchema:J(mb)}]}async function XI(t,e,r){if(!r.traceWriter)return{content:[{type:"text",text:"Trace tools require traceWriter to be configured."}],isError:!0};let n={traceWriter:r.traceWriter};switch(t){case"trace_query":return eD(e,n);case"trace_summary":return tD(e,n);case"trace_visualize":return rD(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function eD(t,e){let r=pb.parse(t),n=e.traceWriter.query({providerId:r.provider_id,task:r.task,traceId:r.trace_id,daysBack:r.days_back,limit:r.limit});if(n.length===0)return{content:[{type:"text",text:"No trace records found."}]};let o=`**Trace Records** (${n.length} results)
519
+ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function xj(t,e,r){switch(t){case"cli_job_submit":return bj(e,r);case"cli_job_status":return wj(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var jp={};Ze(jp,{getTools:()=>Sj,handleTool:()=>$j});var Kx=h.object({provider_id:h.string().optional(),task:h.string().optional(),trace_id:h.string().optional(),days_back:h.number().optional().default(7),limit:h.number().optional().default(50)}),Jx=h.object({days_back:h.number().optional().default(30)}),Gx=h.object({trace_id:h.string()});function Sj(){return[{name:"trace_query",title:"Query Trace Records",description:"Query trace records with filtering. Returns recent provider interactions with latency, quality scores, and reasoning.",inputSchema:V(Kx)},{name:"trace_summary",title:"Summarize Trace Stats",description:"Get quality and performance stats per provider and task type. Shows average quality scores, latency, and success rates.",inputSchema:V(Jx)},{name:"trace_visualize",title:"Visualize Trace Flow",description:"Generate a Mermaid diagram showing the flow of a traced operation. Shows provider selection, execution, and quality assessment.",inputSchema:V(Gx)}]}async function $j(t,e,r){if(!r.traceWriter)return{content:[{type:"text",text:"Trace tools require traceWriter to be configured."}],isError:!0};let n={traceWriter:r.traceWriter};switch(t){case"trace_query":return kj(e,n);case"trace_summary":return Pj(e,n);case"trace_visualize":return Tj(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function kj(t,e){let r=Kx.parse(t),n=e.traceWriter.query({providerId:r.provider_id,task:r.task,traceId:r.trace_id,daysBack:r.days_back,limit:r.limit});if(n.length===0)return{content:[{type:"text",text:"No trace records found."}]};let o=`**Trace Records** (${n.length} results)
472
520
 
473
521
  `;for(let s of n)o+=`| ${s.timestamp?.slice(0,19)} | ${s.providerId} | ${s.task} | ${s.latencyMs}ms | ${s.response.success?"OK":"FAIL"} |`,s.quality&&(o+=` quality: ${s.quality.score}`),o+=`
474
- `;return{content:[{type:"text",text:o}]}}function tD(t,e){let r=fb.parse(t),n=e.traceWriter.getQualityStats(r.days_back);if(n.size===0)return{content:[{type:"text",text:"No quality data available yet."}]};let o=`**Provider Quality Summary** (last ${r.days_back} days)
522
+ `;return{content:[{type:"text",text:o}]}}function Pj(t,e){let r=Jx.parse(t),n=e.traceWriter.getQualityStats(r.days_back);if(n.size===0)return{content:[{type:"text",text:"No quality data available yet."}]};let o=`**Provider Quality Summary** (last ${r.days_back} days)
475
523
 
476
524
  `;o+=`| Provider:Task | Avg Quality | Count | Avg Latency |
477
525
  `,o+=`|---|---|---|---|
@@ -479,23 +527,23 @@ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state=
479
527
  `;let s=new Map;for(let[a,c]of n){let u=a.split(":")[0],l=s.get(u)??{totalScore:0,count:0};l.totalScore+=c.avgScore*c.count,l.count+=c.count,s.set(u,l)}let i=["low","medium","high"];o+=`
480
528
  **Provider Difficulty Qualification**
481
529
 
482
- `,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Es.medium}) | High (>=${Es.high}) |
530
+ `,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Ws.medium}) | High (>=${Ws.high}) |
483
531
  `,o+=`|---|---|---|---|---|---|
484
- `;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Rs(u,d)?"YES":"no");o+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
485
- `}return{content:[{type:"text",text:o}]}}function rD(t,e){let r=mb.parse(t),n=e.traceWriter.query({traceId:r.trace_id});if(n.length===0)return{content:[{type:"text",text:`No records found for trace: ${r.trace_id}`}],isError:!0};let o="```mermaid\ngraph LR\n";o+=` A[User Request] --> B{Provider Selection}
532
+ `;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Hs(u,d)?"YES":"no");o+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
533
+ `}return{content:[{type:"text",text:o}]}}function Tj(t,e){let r=Gx.parse(t),n=e.traceWriter.query({traceId:r.trace_id});if(n.length===0)return{content:[{type:"text",text:`No records found for trace: ${r.trace_id}`}],isError:!0};let o="```mermaid\ngraph LR\n";o+=` A[User Request] --> B{Provider Selection}
486
534
  `;for(let i=0;i<n.length;i++){let a=n[i],c=String.fromCharCode(67+i),u=a.reasoning?.selectionReason?a.reasoning.selectionReason.slice(0,40):`${a.latencyMs}ms`;o+=` B -->|${u}| ${c}[${a.providerId}]
487
535
  `;let l=a.response.success?`${a.response.charLength} chars, ${a.latencyMs}ms`:`FAIL: ${a.response.error?.slice(0,30)??"error"}`;o+=` ${c} --> ${c}R[${l}]
488
536
  `,a.quality&&(o+=` ${c}R --> ${c}Q[Quality: ${a.quality.score}]
489
537
  `)}return o+="```",{content:[{type:"text",text:`**Trace Visualization: ${r.trace_id}**
490
538
 
491
- ${o}`}]}}var Gd={};We(Gd,{getTools:()=>iD,handleTool:()=>uD,resetCache:()=>aD});import{execFile as nD}from"child_process";import{promisify as oD}from"util";var gb=oD(nD),yb=5e3;async function Ss(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await gb(e,[t],{timeout:yb,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function sD(){try{return await gb("git",["worktree","list"],{timeout:yb,encoding:"utf-8"}),!0}catch{return!1}}function iD(){return[{name:"environment_check",title:"Check Environment",description:"Check installed AI CLI tools (codex, gemini), infrastructure (tmux, git worktree), and Ollama models. Returns a capability map showing available v3 orchestration modes. Results are cached per session \u2014 call with force_refresh to re-check.",inputSchema:{type:"object",properties:{force_refresh:{type:"boolean",description:"Force re-check even if cached (default: false)"}},required:[]}}]}var Ha=null,Hd=null;function aD(){Ha=null,Hd=null}async function cD(t,e){let r=JSON.stringify(e.sessionContext??null);if(Ha&&Hd===r&&!t.force_refresh)return{content:[{type:"text",text:hb(Ha)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(Q=>Q.isAvailable()),o=n.find(Q=>Q.type==="claude-cli"),s=n.find(Q=>Q.type==="claude-host"),i=n.find(Q=>Q.type==="codex-cli"),a=n.find(Q=>Q.type==="codex-host"),c=n.find(Q=>Q.type==="gemini-cli"),u=n.find(Q=>Q.type==="gemini-host"),[l,d,p,f,g,y]=await Promise.all([Ss("claude"),Ss("codex"),Ss("gemini"),Ss("tmux"),Ss("git"),sD()]),m=[],b=e.registry.getAll(),_=b.find(Q=>Q.id==="ollama");if(_?.isAvailable()){let Q=_.getCapabilities();for(let sn of Q.models){let eo=sn.sizeGb??0;m.push({name:sn.name,size_gb:eo,tier:rc(eo)})}}let w=i!==void 0||c!==void 0,k=f!==null,P=g!==null&&y,U=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",Z=b.some(Q=>Q.isAvailable()&&!Q.type.endsWith("-host")&&Q.id!=="ollama"),j=[U?"leader_only":"claude_only"];(Z||m.length>0)&&j.push("independent","debate"),w&&P&&j.push("team");let Se={host:e.sessionContext?{id:e.sessionContext.hostId,kind:e.sessionContext.hostKind,leader_provider:e.sessionContext.leaderProviderId,execution_mode:e.sessionContext.executionMode,participant_providers:e.sessionContext.participantProviderIds}:void 0,providers:{ollama:{available:_?.isAvailable()??!1,models:m},claude:{available:o!==void 0||s!==void 0,cli_path:l,host_backed:s!==void 0},gemini:{available:c!==void 0||u!==void 0,cli_path:p,autonomous_capable:c!==void 0,host_backed:u!==void 0},codex:{available:i!==void 0||a!==void 0,cli_path:d,autonomous_capable:i!==void 0,host_backed:a!==void 0}},infrastructure:{tmux:{available:k,path:f},git:{available:g!==null,worktree_support:P}},capabilities:{can_autonomous_work:w&&P,can_tmux_visible:k,can_parallel_workers:w&&P,max_parallel_workers:w?3:0,available_modes:j}};return Ha=Se,Hd=r,{content:[{type:"text",text:hb(Se)}]}}function hb(t){let e=`# Environment Check
539
+ ${o}`}]}}var Lp={};Ze(Lp,{getTools:()=>Aj,handleTool:()=>zj,resetCache:()=>Cj});import{execFile as Ej}from"child_process";import{promisify as Rj}from"util";var Qx=Rj(Ej),Xx=5e3;async function Ns(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await Qx(e,[t],{timeout:Xx,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function Ij(){try{return await Qx("git",["worktree","list"],{timeout:Xx,encoding:"utf-8"}),!0}catch{return!1}}function Aj(){return[{name:"environment_check",title:"Check Environment",description:"Check installed AI CLI tools (codex, gemini), infrastructure (tmux, git worktree), and Ollama models. Returns a capability map showing available v3 orchestration modes. Results are cached per session \u2014 call with force_refresh to re-check.",inputSchema:{type:"object",properties:{force_refresh:{type:"boolean",description:"Force re-check even if cached (default: false)"}},required:[]}}]}var $c=null,Np=null;function Cj(){$c=null,Np=null}async function Dj(t,e){let r=JSON.stringify(e.sessionContext??null);if($c&&Np===r&&!t.force_refresh)return{content:[{type:"text",text:Yx($c)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(Y=>Y.isAvailable()),o=n.find(Y=>Y.type==="claude-cli"),s=n.find(Y=>Y.type==="claude-host"),i=n.find(Y=>Y.type==="codex-cli"),a=n.find(Y=>Y.type==="codex-host"),c=n.find(Y=>Y.type==="gemini-cli"),u=n.find(Y=>Y.type==="gemini-host"),[l,d,p,f,m,g]=await Promise.all([Ns("claude"),Ns("codex"),Ns("gemini"),Ns("tmux"),Ns("git"),Ij()]),y=[],_=e.registry.getAll(),S=_.find(Y=>Y.id==="ollama");if(S?.isAvailable()){let Y=S.getCapabilities();for(let kt of Y.models){let wr=kt.sizeGb??0;y.push({name:kt.name,size_gb:wr,tier:Mc(wr)})}}let v=i!==void 0||c!==void 0,k=f!==null,x=m!==null&&g,z=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",O=_.some(Y=>Y.isAvailable()&&!Y.type.endsWith("-host")&&Y.id!=="ollama"),Z=[z?"leader_only":"claude_only"];(O||y.length>0)&&Z.push("independent","debate"),v&&x&&Z.push("team");let De={host:e.sessionContext?{id:e.sessionContext.hostId,kind:e.sessionContext.hostKind,leader_provider:e.sessionContext.leaderProviderId,execution_mode:e.sessionContext.executionMode,participant_providers:e.sessionContext.participantProviderIds}:void 0,providers:{ollama:{available:S?.isAvailable()??!1,models:y},claude:{available:o!==void 0||s!==void 0,cli_path:l,host_backed:s!==void 0},gemini:{available:c!==void 0||u!==void 0,cli_path:p,autonomous_capable:c!==void 0,host_backed:u!==void 0},codex:{available:i!==void 0||a!==void 0,cli_path:d,autonomous_capable:i!==void 0,host_backed:a!==void 0}},infrastructure:{tmux:{available:k,path:f},git:{available:m!==null,worktree_support:x}},capabilities:{can_autonomous_work:v&&x,can_tmux_visible:k,can_parallel_workers:v&&x,max_parallel_workers:v?3:0,available_modes:Z}};return $c=De,Np=r,{content:[{type:"text",text:Yx(De)}]}}function Yx(t){let e=`# Environment Check
492
540
 
493
541
  `;t.host&&(e+=`## Host Session
494
542
 
495
543
  `,e+=`- **Host:** ${t.host.id}
496
544
  `,e+=`- **Kind:** ${t.host.kind}
497
545
  `,e+=`- **Leader Provider:** ${t.host.leader_provider}
498
- `,e+=`- **Execution Mode:** ${Ba(t.host.execution_mode,t.host.kind)}
546
+ `,e+=`- **Execution Mode:** ${Sc(t.host.execution_mode,t.host.kind)}
499
547
  `,e+=`- **Participants:** ${t.host.participant_providers.join(", ")}
500
548
 
501
549
  `),e+=`## Providers
@@ -519,14 +567,14 @@ ${o}`}]}}var Gd={};We(Gd,{getTools:()=>iD,handleTool:()=>uD,resetCache:()=>aD});
519
567
  `,e+=`- **tmux visible:** ${t.capabilities.can_tmux_visible?"Yes":"No"}
520
568
  `,e+=`- **Parallel workers:** ${t.capabilities.can_parallel_workers?`Yes (max ${t.capabilities.max_parallel_workers})`:"No"}
521
569
  `,e+=`- **Available modes:** ${t.capabilities.available_modes.join(", ")}
522
- `,e}async function uD(t,e,r){return t==="environment_check"?cD(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Jd={};We(Jd,{getTools:()=>lD,handleTool:()=>vD});var _b=h.object({provider:h.string().trim().min(1),task_description:h.string().trim().min(1),working_dir:h.string().trim().min(1),files_to_read:h.array(h.string().trim().min(1)).optional(),files_to_modify:h.array(h.string().trim().min(1)).optional(),constraints:h.string().optional(),success_criteria:h.array(h.string().trim().min(1)).optional(),timeout_minutes:h.number().positive().optional(),use_worktree:h.boolean().optional(),use_tmux:h.boolean().optional()}).strict(),vb=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),xb=h.object({worker_id:h.string().trim().min(1)}).strict(),bb=h.object({worker_id:h.string().trim().min(1)}).strict();function lD(){return[{name:"cli_worker_spawn",title:"Spawn CLI Worker",description:"Spawn a CLI AI worker (any registered provider; use `provider_list` to discover available) in autonomous mode. The worker runs in the background and can be monitored with cli_worker_status.",inputSchema:J(_b)},{name:"cli_worker_status",title:"Check CLI Worker Status",description:"Get the status of a CLI worker by ID, or list all tracked workers if no ID is given.",inputSchema:J(vb)},{name:"cli_worker_collect",title:"Collect CLI Worker Results",description:"Collect results from a successful COLLECTING worker, a completed worker, or a failed CLI worker. Returns full output, git diff, and changed files.",inputSchema:J(xb)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:J(bb)}]}function Ga(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function St(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function dD(t){let e=`# Worker Spawned
570
+ `,e}async function zj(t,e,r){return t==="environment_check"?Dj(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Fp={};Ze(Fp,{getTools:()=>Oj,handleTool:()=>Vj});var eS=h.object({provider:h.string().trim().min(1),task_description:h.string().trim().min(1),working_dir:h.string().trim().min(1),files_to_read:h.array(h.string().trim().min(1)).optional(),files_to_modify:h.array(h.string().trim().min(1)).optional(),constraints:h.string().optional(),success_criteria:h.array(h.string().trim().min(1)).optional(),timeout_minutes:h.number().positive().optional(),use_worktree:h.boolean().optional(),use_tmux:h.boolean().optional()}).strict(),tS=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),rS=h.object({worker_id:h.string().trim().min(1)}).strict(),nS=h.object({worker_id:h.string().trim().min(1)}).strict();function Oj(){return[{name:"cli_worker_spawn",title:"Spawn CLI Worker",description:"Spawn a CLI AI worker (any registered provider; use `provider_list` to discover available) in autonomous mode. The worker runs in the background and can be monitored with cli_worker_status.",inputSchema:V(eS)},{name:"cli_worker_status",title:"Check CLI Worker Status",description:"Get the status of a CLI worker by ID, or list all tracked workers if no ID is given.",inputSchema:V(tS)},{name:"cli_worker_collect",title:"Collect CLI Worker Results",description:"Collect results from a successful COLLECTING worker, a completed worker, or a failed CLI worker. Returns full output, git diff, and changed files.",inputSchema:V(rS)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:V(nS)}]}function kc(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function $t(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function Mj(t){let e=`# Worker Spawned
523
571
 
524
572
  `;return e+=`- **Worker ID:** ${t.workerId}
525
573
  `,e+=`- **Provider:** ${t.provider}
526
574
  `,e+=`- **State:** ${t.state}
527
575
  `,e+=`- **PID:** ${t.pid??"N/A"}
528
576
  `,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
529
- `),e}function pD(t){let e=`# Worker Status
577
+ `),e}function jj(t){let e=`# Worker Status
530
578
 
531
579
  `;return e+=`- **Worker ID:** ${t.workerId}
532
580
  `,e+=`- **Provider:** ${t.provider}
@@ -535,18 +583,18 @@ ${o}`}]}}var Gd={};We(Gd,{getTools:()=>iD,handleTool:()=>uD,resetCache:()=>aD});
535
583
  `,e+=`- **PID:** ${t.pid??"N/A"}
536
584
  `,e+=`- **Retry Count:** ${t.retryCount}
537
585
  `,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
538
- `),t.state===ke.COLLECTING&&(e+="- **Next Step:** Worker exited successfully and is ready for `cli_worker_collect`\n"),t.outputTail&&(e+=`
586
+ `),t.state===$e.COLLECTING&&(e+="- **Next Step:** Worker exited successfully and is ready for `cli_worker_collect`\n"),t.outputTail&&(e+=`
539
587
  ## Recent Output
540
588
 
541
589
  \`\`\`
542
590
  ${t.outputTail}
543
591
  \`\`\`
544
- `),e}function fD(t){if(t.length===0)return`# Workers
592
+ `),e}function Nj(t){if(t.length===0)return`# Workers
545
593
 
546
594
  No tracked workers.`;let e=`# Workers (${t.length})
547
595
 
548
596
  `;for(let r of t)e+=`- **${r.workerId}** \u2014 ${r.provider} \u2014 ${r.state}`,r.pid&&(e+=` (PID ${r.pid})`),e+=`
549
- `;return e}function mD(t){let e=`# Worker Results
597
+ `;return e}function Lj(t){let e=`# Worker Results
550
598
 
551
599
  `;if(e+=`- **Worker ID:** ${t.workerId}
552
600
  `,e+=`- **State:** ${t.state}
@@ -568,7 +616,7 @@ ${t.gitDiff}
568
616
  \`\`\`
569
617
  ${t.outputFull}
570
618
  \`\`\`
571
- `),e}async function hD(t,e){let r=Ga(e),n=_b.parse(t),o=r.knownProviders();if(!o.includes(n.provider))return St(`Unknown provider: "${n.provider}". Known: [${o.join(", ")}]`,!0);let s={provider:n.provider,taskDescription:n.task_description,workingDir:n.working_dir,filesToRead:n.files_to_read,filesToModify:n.files_to_modify,constraints:n.constraints,successCriteria:n.success_criteria,timeoutMinutes:n.timeout_minutes,useWorktree:n.use_worktree,useTmux:n.use_tmux};try{let i=r.spawn(s);return St(dD(i))}catch(i){let a=q(i);return St(`Error spawning worker: ${a}`,!0)}}async function gD(t,e){let r=Ga(e),n=vb.parse(t);if(!n.worker_id){let s=r.listAll();return St(fD(s))}let o=r.getStatus(n.worker_id);return o?St(pD(o)):St(`Worker not found: ${n.worker_id}`,!0)}async function yD(t,e){let r=Ga(e),n=xb.parse(t),o=r.collect(n.worker_id);return o?St(mD(o)):St(`Worker not found: ${n.worker_id}`,!0)}async function _D(t,e){let r=Ga(e),n=bb.parse(t);return r.stop(n.worker_id),St(`Stop signal sent to worker: ${n.worker_id}`)}async function vD(t,e,r){try{switch(t){case"cli_worker_spawn":return await hD(e??{},r);case"cli_worker_status":return await gD(e??{},r);case"cli_worker_collect":return await yD(e??{},r);case"cli_worker_stop":return await _D(e??{},r);default:return St(`Unknown tool: ${t}`,!0)}}catch(n){let o=q(n);return St(`Error: ${o}`,!0)}}var Kd={};We(Kd,{getTools:()=>xD,handleTool:()=>wD});var wb=h.object({design_doc:h.string().optional().describe("Optional design document path to verify against"),build_profile:h.enum(["auto","tsc","vitest","npm-build","npm-test"]).optional().describe("QA build profile to execute. Defaults to 'auto' which detects from project structure."),timeout_ms:h.number().int().positive().optional().describe("Timeout per command in milliseconds")}).strict();function xD(){return[{name:"qa_run",title:"Run Auto QA",description:"Run automatic QA for the current project. Detects build/test commands, optionally includes a design document reference, and returns a PASS/FAIL summary with captured output.",inputSchema:J(wb)}]}function bD(t){let e=`# Auto QA
619
+ `),e}async function Fj(t,e){let r=kc(e),n=eS.parse(t),o=r.knownProviders();if(!o.includes(n.provider))return $t(`Unknown provider: "${n.provider}". Known: [${o.join(", ")}]`,!0);let s={provider:n.provider,taskDescription:n.task_description,workingDir:n.working_dir,filesToRead:n.files_to_read,filesToModify:n.files_to_modify,constraints:n.constraints,successCriteria:n.success_criteria,timeoutMinutes:n.timeout_minutes,useWorktree:n.use_worktree,useTmux:n.use_tmux};try{let i=r.spawn(s);return $t(Mj(i))}catch(i){let a=M(i);return $t(`Error spawning worker: ${a}`,!0)}}async function Zj(t,e){let r=kc(e),n=tS.parse(t);if(!n.worker_id){let s=r.listAll();return $t(Nj(s))}let o=r.getStatus(n.worker_id);return o?$t(jj(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function Uj(t,e){let r=kc(e),n=rS.parse(t),o=r.collect(n.worker_id);return o?$t(Lj(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function qj(t,e){let r=kc(e),n=nS.parse(t);return r.stop(n.worker_id),$t(`Stop signal sent to worker: ${n.worker_id}`)}async function Vj(t,e,r){try{switch(t){case"cli_worker_spawn":return await Fj(e??{},r);case"cli_worker_status":return await Zj(e??{},r);case"cli_worker_collect":return await Uj(e??{},r);case"cli_worker_stop":return await qj(e??{},r);default:return $t(`Unknown tool: ${t}`,!0)}}catch(n){let o=M(n);return $t(`Error: ${o}`,!0)}}var Zp={};Ze(Zp,{getTools:()=>Bj,handleTool:()=>Hj});var oS=h.object({design_doc:h.string().optional().describe("Optional design document path to verify against"),build_profile:h.enum(["auto","tsc","vitest","npm-build","npm-test"]).optional().describe("QA build profile to execute. Defaults to 'auto' which detects from project structure."),timeout_ms:h.number().int().positive().optional().describe("Timeout per command in milliseconds")}).strict();function Bj(){return[{name:"qa_run",title:"Run Auto QA",description:"Run automatic QA for the current project. Detects build/test commands, optionally includes a design document reference, and returns a PASS/FAIL summary with captured output.",inputSchema:V(oS)}]}function Wj(t){let e=`# Auto QA
572
620
 
573
621
  ${t.summary}
574
622
  `;return t.designDoc&&(e+=`
@@ -585,12 +633,12 @@ ${t.buildOutput||"(no output)"}
585
633
  \`\`\`
586
634
  ${t.testOutput||"(no output)"}
587
635
  \`\`\`
588
- `,e}async function wD(t,e,r){if(t==="qa_run"){let n=wb.parse(e??{}),s=await new bo(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:bD(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var kb=[Md,qd,Fd,Ud,Vd,Wd,Bd,Gd,Jd,Kd];function Tb(){let t=[];for(let e of kb)t.push(...e.getTools());return t}var Sb=new Map;function SD(t){return t.sessionId??"__default__"}function kD(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return $D(e.uri)}catch{}}async function TD(t,e,r){let n=SD(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=kD(o.roots);if(s)return Sb.set(n,s),s}catch{}return Sb.get(n)??e.workspaceBaseDir??process.cwd()}function PD(t,e){return t.filter(r=>Pb(r.name,e))}function ED(t,e){let r=Qt(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return Ms(n)}function Pb(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>ED(i,e.providerPolicies));return t.startsWith("ollama_")?o:t.startsWith("cli_worker_")||t.startsWith("agent_changes_")?s&&e.cliWorkerManager!==void 0:t.startsWith("ai_")||t.startsWith("agent_debate_")||t==="agent_cross_validate"?n:!0}function RD(t,e){let r=[],n=0;for(let o of t){let s=Buffer.byteLength(o,"utf-8");if(n+s>e)break;r.push(o),n+=s}return r.join("")}var Qd=null;function zD(){if(Qd)return Qd;let t=new Map;for(let e of kb)for(let r of e.getTools())t.set(r.name,e);return Qd=t,t}function Eb(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:RD(r.text,51200)+`
636
+ `,e}async function Hj(t,e,r){if(t==="qa_run"){let n=oS.parse(e??{}),s=await new Io(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:Wj(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var aS=[hp,Ip,Ap,Cp,zp,Op,Mp,jp,Lp,Fp,Zp];function cS(){let t=[];for(let e of aS)t.push(...e.getTools());return t}var iS=new Map;function Jj(t){return t.sessionId??"__default__"}function Gj(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return Kj(e.uri)}catch{}}async function Yj(t,e,r){let n=Jj(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=Gj(o.roots);if(s)return iS.set(n,s),s}catch{}return iS.get(n)??e.workspaceBaseDir??process.cwd()}function Qj(t,e){return t.filter(r=>uS(r.name,e))}function Xj(t,e){let r=tr(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return ei(n)}function uS(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>Xj(i,e.providerPolicies));return t.startsWith("ollama_")?o:t.startsWith("cli_worker_")||t.startsWith("agent_changes_")?s&&e.cliWorkerManager!==void 0:t.startsWith("ai_")||t.startsWith("agent_debate_")||t==="agent_cross_validate"?n:!0}function eN(t,e){let r=[],n=0;for(let o of t){let s=Buffer.byteLength(o,"utf-8");if(n+s>e)break;r.push(o),n+=s}return r.join("")}var Up=null;function tN(){if(Up)return Up;let t=new Map;for(let e of aS)for(let r of e.getTools())t.set(r.name,e);return Up=t,t}function lS(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:eN(r.text,51200)+`
589
637
 
590
- ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function Rb(t,e,r){let o=zD().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!Pb(t,r))return{content:[{type:"text",text:`Tool unavailable in current environment: ${t}`}],isError:!0};let s={registry:r.registry,sessionManager:r.sessionManager,documentManager:r.documentManager,jobManager:r.jobManager,traceWriter:r.traceWriter,qualityStatsProvider:r.qualityStatsProvider,messageQueue:r.messageQueue,cliWorkerManager:r.cliWorkerManager,sessionContext:r.resolveSessionContext?.()??r.sessionContext,workspaceBaseDir:r.workspaceBaseDir},i=await o.handleTool(t,e,s);return Eb(i)}function Yd(t){let e=new Ea({name:"agestra",version:cp},{capabilities:{tools:{}}});return e.setRequestHandler(Iu,async()=>({tools:PD(Tb(),t)})),e.setRequestHandler(Bo,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await TD(e,t,n),a=t.resolveWorkspaceServices?.(i)??{},c=await Rb(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${q(i)}`}],isError:!0}}}),e}async function Xd(t){let e=new za;await t.connect(e)}function zb(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function CD(t){return Array.isArray(t)?t.filter(zb).map(e=>e.text).join(`
638
+ ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function dS(t,e,r){let o=tN().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!uS(t,r))return{content:[{type:"text",text:`Tool unavailable in current environment: ${t}`}],isError:!0};let s={registry:r.registry,sessionManager:r.sessionManager,documentManager:r.documentManager,jobManager:r.jobManager,traceWriter:r.traceWriter,qualityStatsProvider:r.qualityStatsProvider,cliWorkerManager:r.cliWorkerManager,sessionContext:r.resolveSessionContext?.()??r.sessionContext,workspaceBaseDir:r.workspaceBaseDir,i18n:r.i18n,structuredSessionRegistry:r.structuredSessionRegistry,moderatorEngine:r.moderatorEngine},i=await o.handleTool(t,e,s);return lS(i)}function qp(t){let e=new Ja({name:"agestra",version:Gp},{capabilities:{tools:{}}});return e.setRequestHandler(pl,async()=>({tools:Qj(cS(),t)})),e.setRequestHandler(rs,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await Yj(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await dS(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${M(i)}`}],isError:!0}}}),e}async function Vp(t){let e=new Ya;await t.connect(e)}function pS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function rN(t){return Array.isArray(t)?t.filter(pS).map(e=>e.text).join(`
591
639
 
592
- `).trim():zb(t)?t.text:""}function Cb(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function Ab(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function Ja(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function ep(t,e,r){let n=()=>Ja(t.getClientVersion()?.name);return{providerId:e,isAvailable(){return!!t.getClientCapabilities()?.sampling&&n()===r.expectedHostKind},async healthCheck(){if(!t.getClientCapabilities()?.sampling)return{status:"error",message:"Client does not support MCP sampling"};let o=n();return o!==r.expectedHostKind?{status:"error",message:`${r.displayName} host bridge requires a ${r.displayName} host, got ${o}`}:{status:"ok",message:`${r.displayName} host bridge available via ${t.getClientVersion()?.name??"unknown client"}`}},async runTurn(o){if(!this.isAvailable())throw new Error(r.unavailableMessage);let s=await t.createMessage({messages:[{role:"user",content:{type:"text",text:o.prompt}}],systemPrompt:o.system,includeContext:"none",maxTokens:Cb(o.metadata,"maxTokens")??4096,temperature:Cb(o.metadata,"temperature"),modelPreferences:Ab(o.metadata,"model")?{hints:[{name:Ab(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=CD(s.content);if(!i)throw new Error("Claude host bridge returned no text content");return{text:i,metadata:{model:s.model,stopReason:s.stopReason,hostKind:n()}}}}}function Ka(t,e="claude"){return ep(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Qa(t,e="codex-host"){return ep(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Ya(t,e="gemini-host"){return ep(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var AD=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new Ks({id:e,bridge:Ka(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new Qs({id:e,bridge:Qa(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new Ys({id:e,bridge:Ya(t,e)})}];function Xn(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function ID(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function DD(t,e){switch(t){case"claude-code":return Xn(e,"claude-host","claude");case"codex-cli":return Xn(e,"codex-host","codex-host");case"gemini-cli":return Xn(e,"gemini-host","gemini-host");default:return}}function OD(t,e){return t.some(o=>o.roles.includes("worker")&&o.supportsAutonomousExecution)?"team":t.some(o=>o.id!==e&&o.supportsReadOnlyChat)&&t.length>1?"debate":"claude-only"}function tp(t,e){let r=()=>Ja(t.getClientVersion()?.name),n=()=>ID(r()),o=()=>DD(r(),e);return{get id(){return r()},get kind(){return r()},get leaderProviderId(){return o()},get leaderProviderType(){return n()},get supportsHooks(){return r()==="claude-code"},get supportsInteractiveChoices(){return r()!=="unknown"},get supportsSampling(){return!!t.getClientCapabilities()?.sampling},createLeaderBridge(){switch(r()){case"claude-code":{let s=Xn(e,"claude-host","claude");return Ka(t,s)}case"codex-cli":{let s=Xn(e,"codex-host","codex-host");return Qa(t,s)}case"gemini-cli":{let s=Xn(e,"gemini-host","gemini-host");return Ya(t,s)}default:return null}},createHostProviders(){let s=r();return AD.flatMap(i=>{if(s==="unknown"||!i.supportedHosts.includes(s))return[];let a=e?.providers.find(u=>u.type===i.type||u.id===i.defaultId);if(a?.enabled===!1)return[];let c=a?.id??i.defaultId;return[{id:c,type:i.type,executionPolicy:a?.executionPolicy??rr(i.type),provider:i.createProvider(t,c)}]})},createSessionContext(s){let i=s.filter(u=>u.supportsReadOnlyChat);if(i.length===0)return;let a=o(),c=(a?i.find(u=>u.id===a):void 0)??(n()?i.find(u=>u.type===n()):void 0)??i.find(u=>u.roles.includes("leader"))??i[0];return{hostId:r(),hostKind:r(),leaderProviderId:c.id,participantProviderIds:i.map(u=>u.id),executionMode:OD(i,c.id)}}}}async function rp(t,e,r,n){let o=t.createHostProviders();for(let s of o)e.has(s.id)||(await s.provider.initialize(),e.register(s.provider),r.set(s.id,s.executionPolicy),n(`Registered provider: ${s.id} (${s.type})`))}function np(t,e){let r=typeof e.getAvailableDescriptors=="function"?e.getAvailableDescriptors():e.getAvailable().map(n=>typeof e.getDescriptor=="function"?e.getDescriptor(n.id):{id:n.id,type:n.type,invocation:"unknown",roles:["participant"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0,supportsToolUse:n.getCapabilities().supportsToolUse});return t.createSessionContext?.(r)}var B4={ollama:{executionPolicy:"workspace-write",config:{host:to,defaultModel:"auto"}},"gemini-cli":{executionPolicy:rr("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:rr("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:rr("claude-cli"),config:{timeout:12e4}}};async function op(){let t=[{id:"ollama",type:"ollama",provider:new Zr({id:"ollama",host:to})},{id:"gemini",type:"gemini-cli",provider:new qr({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Fr({id:"codex"})},{id:"claude-cli",type:"claude-cli",provider:new Ur({id:"claude-cli"})}],e=[],r=[];await Promise.all(t.map(async o=>{try{await o.provider.initialize()}catch{}let s=o.provider.isAvailable();e.push({id:o.id,type:o.type,available:s}),s&&r.push(o.provider)}));let n=["ollama","gemini","codex","claude-cli"];return e.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),r.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),{results:e,providers:r}}function Ib(t,e){sp(t,e)}function sp(t,e,r){let n=[];for(let o of t)e.has(o.id)||r?.excludeIds?.has(o.id)||r?.excludeTypes?.has(o.type)||(e.register(o),n.push(o));return n}import{existsSync as Db}from"fs";import{dirname as Nb,join as Ob,resolve as jb}from"path";import{fileURLToPath as MD}from"url";function ND(t){return Db(Ob(t,"package.json"))&&Db(Ob(t,"AGENTS.md"))}function Mb(t){let e=jb(t);for(;;){if(ND(e))return e;let r=Nb(e);if(r===e)return null;e=r}}function jD(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return jb(t);let e=Nb(MD(import.meta.url));return Mb(process.cwd())??Mb(e)??process.cwd()}function Lb(){let t=jD();return process.cwd()!==t&&process.chdir(t),t}var Zb={ollama:t=>new Zr({id:t.id,host:t.config?.host||to}),"gemini-cli":t=>new qr({id:t.id,timeout:t.config?.timeout}),"codex-cli":t=>new Fr({id:t.id,timeout:t.config?.timeout}),"claude-cli":t=>new Ur({id:t.id,timeout:t.config?.timeout})};async function qD(t,e,r){if(t.getAll().length>0)return r("Providers already registered, skipping auto-detect."),{detected:0};r("No providers found \u2014 running auto-detect...");try{let{results:n,providers:o}=await op(),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(Ib(o,t),r(`Auto-detected ${s.length} provider(s): ${s.map(i=>i.id).join(", ")}`),{detected:s.length})}catch(n){return r(`Auto-detect failed (non-fatal): ${q(n)}`),{detected:0}}}async function FD(){let t=m=>process.stderr.write(`[mcp-server] ${m}
593
- `),e=Lb(),r=Xa(e,"providers.config.json"),n;try{let m=LD(r,"utf-8");n=JSON.parse(m)}catch(m){t(`Warning: Could not load ${r}: ${q(m)}`),t("Starting with empty provider registry."),n=null}let o=new zs,s=null;if(n)try{s=Op(n)}catch(m){t(`Warning: Invalid provider config in ${r}: ${q(m)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}if(s){let m=s.enabledProviders.map(_=>{let w=Zb[_.type];if(!w)return t(`Unknown provider type: ${_.type} (id: ${_.id}), skipping`),null;let k=w(_);return{pc:_,provider:k}}).filter(_=>_!==null),b=await Promise.allSettled(m.map(async({pc:_,provider:w})=>(await w.initialize(),{pc:_,provider:w})));for(let _ of b)if(_.status==="fulfilled"){let{pc:w,provider:k}=_.value;o.register(k),t(`Registered provider: ${w.id} (${w.type})`)}else t(`Failed to initialize provider: ${q(_.reason)}`)}if(await qD(o,e,t),s){let m=s.providers.filter(b=>!b.enabled&&!o.has(b.id));if(m.length>0){let b=await Promise.allSettled(m.map(async _=>{let w=Zb[_.type];if(!w)return null;let k=w(_);return await k.initialize(),k.isAvailable()?{pc:_,provider:k}:null}));for(let _ of b)if(_.status==="fulfilled"&&_.value){let{pc:w,provider:k}=_.value;o.register(k),t(`Re-enabled previously disabled provider: ${w.id} (${w.type})`)}}}if(s){let m=new Set(s.providers.filter(_=>!_.enabled).map(_=>_.id)),b=new Set(s.providers.filter(_=>!_.enabled).map(_=>_.type));try{let{providers:_}=await op(),w=sp(_,o,{excludeIds:m,excludeTypes:b});for(let k of w)t(`Registered newly detected provider: ${k.id} (${k.type})`)}catch(_){t(`Supplemental provider detection failed (non-fatal): ${q(_)}`)}}let i=new Map(s?.providers.map(m=>[m.id,m.executionPolicy])??[]),a=new Map(o.getAll().map(m=>[m.id,i.get(m.id)??rr(m.type)])),c=new Map,u=m=>{let b=c.get(m);if(b)return b;let _=new yo(Xa(m,fp)),w=new $o(Xa(m,mp)),k=new qs(m),P=new Fs(m);P.cleanup(30);let U=new Hs(P,{ttlMs:6e4}),Z=new So(Xa(m,hp)),j=new fo(m,{providerPolicies:a}),Se={sessionManager:_,documentManager:w,jobManager:k,traceWriter:P,qualityStatsProvider:U,messageQueue:Z,cliWorkerManager:j};return c.set(m,Se),Se},l=u(e),d={registry:o,...l,providerPolicies:a,workspaceBaseDir:e,resolveWorkspaceServices:m=>u(m)},p=Yd(d),f=tp(p,s);await rp(f,o,a,t),d.resolveSessionContext=()=>np(f,o);let g=!1,y=async()=>{if(!g){g=!0,t("Shutting down...");for(let m of c.values())m.traceWriter.shutdown();for(let m of o.getAll())if(m.shutdown)try{await m.shutdown()}catch{}}};process.on("SIGTERM",()=>{y().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{y().finally(()=>process.exit(0))}),process.on("uncaughtException",m=>{for(let b of c.values())b.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${m}
594
- `),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await Xd(p),t("MCP server connected via stdio.")}var UD=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=ZD(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();UD&&FD().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
595
- `),process.exit(1)});export{qD as autoDetectIfNeeded,Tb as collectTools,Xd as connectStdio,Ka as createClaudeLeaderBridge,Qa as createCodexLeaderBridge,Ya as createGeminiLeaderBridge,tp as createRuntimeHostAdapter,Yd as createServer,Rb as dispatch,Ja as inferHostKindFromClientName,rp as registerHostBackedProviders,np as resolveSessionContext,Eb as truncateResponse};
640
+ `).trim():pS(t)?t.text:""}function fS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function mS(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function lo(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function Bp(t,e,r){let n=()=>lo(t.getClientVersion()?.name);return{providerId:e,isAvailable(){return!!t.getClientCapabilities()?.sampling&&n()===r.expectedHostKind},async healthCheck(){if(!t.getClientCapabilities()?.sampling)return{status:"error",message:"Client does not support MCP sampling"};let o=n();return o!==r.expectedHostKind?{status:"error",message:`${r.displayName} host bridge requires a ${r.displayName} host, got ${o}`}:{status:"ok",message:`${r.displayName} host bridge available via ${t.getClientVersion()?.name??"unknown client"}`}},async runTurn(o){if(!this.isAvailable())throw new Error(r.unavailableMessage);let s=await t.createMessage({messages:[{role:"user",content:{type:"text",text:o.prompt}}],systemPrompt:o.system,includeContext:"none",maxTokens:fS(o.metadata,"maxTokens")??4096,temperature:fS(o.metadata,"temperature"),modelPreferences:mS(o.metadata,"model")?{hints:[{name:mS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=rN(s.content);if(!i)throw new Error("Claude host bridge returned no text content");return{text:i,metadata:{model:s.model,stopReason:s.stopReason,hostKind:n()}}}}}function Pc(t,e="claude"){return Bp(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Tc(t,e="codex-host"){return Bp(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Ec(t,e="gemini-host"){return Bp(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var nN=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new hi({id:e,bridge:Pc(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new gi({id:e,bridge:Tc(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new yi({id:e,bridge:Ec(t,e)})}];function po(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function oN(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function sN(t,e){switch(t){case"claude-code":return po(e,"claude-host","claude");case"codex-cli":return po(e,"codex-host","codex-host");case"gemini-cli":return po(e,"gemini-host","gemini-host");default:return}}function iN(t,e){return t.some(o=>o.roles.includes("worker")&&o.supportsAutonomousExecution)?"team":t.some(o=>o.id!==e&&o.supportsReadOnlyChat)&&t.length>1?"debate":"claude-only"}function Wp(t,e){let r=()=>lo(t.getClientVersion()?.name),n=()=>oN(r()),o=()=>sN(r(),e);return{get id(){return r()},get kind(){return r()},get leaderProviderId(){return o()},get leaderProviderType(){return n()},get supportsHooks(){return r()==="claude-code"},get supportsInteractiveChoices(){return r()!=="unknown"},get supportsSampling(){return!!t.getClientCapabilities()?.sampling},createLeaderBridge(){switch(r()){case"claude-code":{let s=po(e,"claude-host","claude");return Pc(t,s)}case"codex-cli":{let s=po(e,"codex-host","codex-host");return Tc(t,s)}case"gemini-cli":{let s=po(e,"gemini-host","gemini-host");return Ec(t,s)}default:return null}},createHostProviders(){let s=r();return nN.flatMap(i=>{if(s==="unknown"||!i.supportedHosts.includes(s))return[];let a=e?.providers.find(u=>u.type===i.type||u.id===i.defaultId);if(a?.enabled===!1)return[];let c=a?.id??i.defaultId;return[{id:c,type:i.type,executionPolicy:a?.executionPolicy??Vt(i.type),provider:i.createProvider(t,c)}]})},createSessionContext(s){let i=s.filter(u=>u.supportsReadOnlyChat);if(i.length===0)return;let a=o(),c=(a?i.find(u=>u.id===a):void 0)??(n()?i.find(u=>u.type===n()):void 0)??i.find(u=>u.roles.includes("leader"))??i[0];return{hostId:r(),hostKind:r(),leaderProviderId:c.id,participantProviderIds:i.map(u=>u.id),executionMode:iN(i,c.id)}}}}async function Hp(t,e,r,n){let o=t.createHostProviders();for(let s of o)e.has(s.id)||(await s.provider.initialize(),e.register(s.provider),r.set(s.id,s.executionPolicy),n(`Registered provider: ${s.id} (${s.type})`))}function Kp(t,e){let r=typeof e.getAvailableDescriptors=="function"?e.getAvailableDescriptors():e.getAvailable().map(n=>typeof e.getDescriptor=="function"?e.getDescriptor(n.id):{id:n.id,type:n.type,invocation:"unknown",roles:["participant"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0,supportsToolUse:n.getCapabilities().supportsToolUse});return t.createSessionContext?.(r)}import{existsSync as hS}from"fs";import{dirname as vS,join as gS,resolve as _S}from"path";import{fileURLToPath as aN}from"url";function cN(t){return hS(gS(t,"package.json"))&&hS(gS(t,"AGENTS.md"))}function yS(t){let e=_S(t);for(;;){if(cN(e))return e;let r=vS(e);if(r===e)return null;e=r}}function uN(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return _S(t);let e=vS(aN(import.meta.url));return yS(process.cwd())??yS(e)??process.cwd()}function bS(){let t=uN();return process.cwd()!==t&&process.chdir(t),t}var wS={ollama:t=>new qr({id:t.id,host:t.config?.host||fo}),"gemini-cli":t=>new Vr({id:t.id,timeout:t.config?.timeout}),"codex-cli":t=>new Br({id:t.id,timeout:t.config?.timeout}),"claude-cli":t=>new Wr({id:t.id,timeout:t.config?.timeout})};async function pN(t,e,r){if(t.getAll().length>0)return r("Providers already registered, skipping auto-detect."),{detected:0};r("No providers found \u2014 running auto-detect...");try{let{results:n,providers:o}=await uo(),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(Vx(o,t),r(`Auto-detected ${s.length} provider(s): ${s.map(i=>i.id).join(", ")}`),{detected:s.length})}catch(n){return r(`Auto-detect failed (non-fatal): ${M(n)}`),{detected:0}}}async function fN(){let t=v=>process.stderr.write(`[mcp-server] ${v}
641
+ `),e=bS(),r=Rc(e,"providers.config.json"),n;try{let v=lN(r,"utf-8");n=JSON.parse(v)}catch(v){t(`Warning: Could not load ${r}: ${M(v)}`),t("Starting with empty provider registry."),n=null}let o=new Ks,s=null;if(n)try{s=Ef(n)}catch(v){t(`Warning: Invalid provider config in ${r}: ${M(v)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}if(s){let v=s.enabledProviders.map(x=>{let z=wS[x.type];if(!z)return t(`Unknown provider type: ${x.type} (id: ${x.id}), skipping`),null;let O=z(x);return{pc:x,provider:O}}).filter(x=>x!==null),k=await Promise.allSettled(v.map(async({pc:x,provider:z})=>(await z.initialize(),{pc:x,provider:z})));for(let x of k)if(x.status==="fulfilled"){let{pc:z,provider:O}=x.value;o.register(O),t(`Registered provider: ${z.id} (${z.type})`)}else t(`Failed to initialize provider: ${M(x.reason)}`)}if(await pN(o,e,t),s){let v=s.providers.filter(k=>!k.enabled&&!o.has(k.id));if(v.length>0){let k=await Promise.allSettled(v.map(async x=>{let z=wS[x.type];if(!z)return null;let O=z(x);return await O.initialize(),O.isAvailable()?{pc:x,provider:O}:null}));for(let x of k)if(x.status==="fulfilled"&&x.value){let{pc:z,provider:O}=x.value;o.register(O),t(`Re-enabled previously disabled provider: ${z.id} (${z.type})`)}}}if(s){let v=new Set(s.providers.filter(x=>!x.enabled).map(x=>x.id)),k=new Set(s.providers.filter(x=>!x.enabled).map(x=>x.type));try{let{providers:x}=await uo(),z=Dp(x,o,{excludeIds:v,excludeTypes:k});for(let O of z)t(`Registered newly detected provider: ${O.id} (${O.type})`)}catch(x){t(`Supplemental provider detection failed (non-fatal): ${M(x)}`)}}let i=new Map(s?.providers.map(v=>[v.id,v.executionPolicy])??[]),a=new Map(o.getAll().map(v=>[v.id,i.get(v.id)??Vt(v.type)])),c=dm(s?.locale);t(`Localization active: ${c.locale}`);let u=new Map,l=()=>"unknown",d=async v=>{let k=u.get(v);if(k)return k;let x=new To(Rc(v,tf)),z=new zo(Rc(v,mo)),O=new ii(v),Z=new ai(v);Z.cleanup(30);let De=new pi(Z,{ttlMs:6e4}),Y=new $o(v,{providerPolicies:a}),kt=new ao(Rc(v,mo));try{await kt.hydrateFromDisk()}catch(xS){t(`Structured session registry hydrate failed for ${v}: ${M(xS)}`)}let wr=_c(o,l()),Ls=new co({bridge:wr,documentManager:z,registry:kt,i18n:c,traceWriter:Z}),Fs={sessionManager:x,documentManager:z,jobManager:O,traceWriter:Z,qualityStatsProvider:De,cliWorkerManager:Y,structuredSessionRegistry:kt,moderatorEngine:Ls};return u.set(v,Fs),Fs},p=await d(e),f={registry:o,...p,providerPolicies:a,workspaceBaseDir:e,resolveWorkspaceServices:async v=>d(v),i18n:c},m=qp(f),g=Wp(m,s);l=()=>lo(m.getClientVersion()?.name),await Hp(g,o,a,t),f.resolveSessionContext=()=>Kp(g,o);let y=setInterval(()=>{(async()=>{for(let v of u.values())try{let k=await v.structuredSessionRegistry.sweepTimeouts();k.length>0&&await v.moderatorEngine.handleTimedOutSnapshots(k)}catch(k){t(`Session sweep failed: ${M(k)}`)}})()},pf);y.unref?.();let _=!1,S=async()=>{if(!_){_=!0,t("Shutting down..."),clearInterval(y);for(let v of u.values())v.traceWriter.shutdown();for(let v of o.getAll())if(v.shutdown)try{await v.shutdown()}catch{}}};process.on("SIGTERM",()=>{S().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{S().finally(()=>process.exit(0))}),process.on("uncaughtException",v=>{for(let k of u.values())k.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${v}
642
+ `),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await Vp(m),t("MCP server connected via stdio.")}var mN=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=dN(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();mN&&fN().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
643
+ `),process.exit(1)});export{pN as autoDetectIfNeeded,cS as collectTools,Vp as connectStdio,Pc as createClaudeLeaderBridge,Tc as createCodexLeaderBridge,Ec as createGeminiLeaderBridge,Wp as createRuntimeHostAdapter,qp as createServer,dS as dispatch,lo as inferHostKindFromClientName,Hp as registerHostBackedProviders,Kp as resolveSessionContext,lS as truncateResponse};
596
644
  //# sourceMappingURL=bundle.js.map