agestra 4.10.2 → 4.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -1,59 +1,63 @@
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 PS=Object.create;var Ic=Object.defineProperty;var TS=Object.getOwnPropertyDescriptor;var ES=Object.getOwnPropertyNames;var RS=Object.getPrototypeOf,IS=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})},AS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ES(e))!IS.call(t,o)&&o!==r&&Ic(t,o,{get:()=>e[o],enumerable:!(n=TS(e,o))||n.enumerable});return t};var Jp=(t,e,r)=>(r=t!=null?PS(RS(t)):{},AS(e||!t||!t.__esModule?Ic(r,"default",{value:t,enumerable:!0}):r,t));var Yp,fo,Qp,Xp,ef,tf,rf,mo,nf,qs,of,sf,af,cf,uf,lf,Vs,Ac,Cc,xj,df,ln,Dc,zc,pf,ff,Bs,xr,Oc,mf,hf,dn,jt=an(()=>{"use strict";Yp="4.10.2",fo="http://localhost:11434",Qp="llama3",Xp=".agestra/.jobs",ef=".agestra/traces",tf=".agestra/worktrees",rf=".agestra/sessions",mo=".agestra/workspace",nf="individual",qs="debates",of="synthesis",sf="issue",af=".agestra/workers",cf=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),uf=2,lf=6e4,Vs=20,Ac=5e4,Cc=10,xj=Object.freeze([3,5,10]),df=Object.freeze(["agree","disagree","abstain","revise"]),ln="votes",Dc=2,zc=2,pf=1440*60*1e3,ff=3600*1e3,Bs=Object.freeze(["ko","zh","ja","en"]),xr="ko",Oc="en",mf="[REDACTED]",hf=["","--- 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 CS}from"child_process";function pn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return CS("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 DS,spawn as zS}from"child_process";import{existsSync as OS}from"fs";function NS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:MS.has(t.toLowerCase())}function jS(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 LS(t){let e=t.toLowerCase();if(fn.has(e))return fn.get(e)??null;try{let n=DS("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(OS(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(!NS(t))return{command:t,args:e};let r=LS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>jS(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=zS(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,x=null,v=!1,P=()=>{!v&&g+y>a&&(_=!0,v=!0,er(p))};p.stdout.on("data",Z=>{g+=Z.length,g<=a&&(f+=Z.toString()),P()}),p.stderr.on("data",Z=>{y+=Z.length;let De=Z.toString();if(y<=a&&(m+=De),P(),!v&&c){let Y=c(De);Y&&(x=Y,v=!0,er(p))}}),i&&p.stdin&&(p.stdin.write(i),p.stdin.end());let S=()=>{er(p),l(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`))},N=setTimeout(S,n),L=()=>{clearTimeout(N),N=setTimeout(S,n)};p.stdout.on("data",L),p.stderr.on("data",L),p.on("close",Z=>{if(clearTimeout(N),x){l(x);return}u({stdout:f,stderr:m,exitCode:Z??1,truncated:_})}),p.on("error",Z=>{clearTimeout(N),l(new Error(`CLI spawn error: ${Z.message}`))})})}var MS,fn,mn=an(()=>{"use strict";ho();MS=new Set(["codex","gemini","npm","npx"]),fn=new Map});import{writeFileSync as ck,mkdirSync as bo,openSync as Fc,writeSync as Zc,fsyncSync as Df,closeSync as Uc,renameSync as uk,unlinkSync as lk,appendFileSync as dk}from"fs";import{dirname as wo,join as pk}from"path";import{randomUUID as fk}from"crypto";function se(t,e){let r=wo(t);bo(r,{recursive:!0});let n=pk(r,`.tmp-${fk().slice(0,8)}`);try{ck(n,e,"utf-8"),uk(n,t)}catch(o){try{lk(n)}catch{}throw o}}function Ue(t,e){se(t,JSON.stringify(e,null,2))}function ni(t,e){let r=wo(t);bo(r,{recursive:!0});let n=Fc(t,"a");try{Zc(n,e),Df(n)}finally{Uc(n)}}var ri,oi=an(()=>{"use strict";ri=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)ni(e,r);else{let s=wo(e);bo(s,{recursive:!0}),dk(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=wo(e);bo(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join("")),Df(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=wo(e);bo(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join(""))}finally{Uc(o)}this.buffer.delete(e)}}});import{existsSync as zf,realpathSync as mk}from"fs";import{basename as hk,dirname as gk,isAbsolute as Nf,join as yk,normalize as vk,resolve as qc,relative as _k}from"path";function bk(t){return t===""||!t.startsWith("..")&&!Nf(t)}function Of(t){let e=[],r=qc(t);for(;!zf(r);){let o=gk(r);if(o===r)break;e.unshift(hk(r)),r=o}let n=zf(r)?mk(r):r;return e.reduce((o,s)=>yk(o,s),n)}function jf(t,e){let r=Of(e),n=Of(t),o=_k(r,n);return bk(o)}function Vc(t,e){let r=qc(e,t);return jf(r,e)}function ht(t,e){let r=qc(e,t);if(!jf(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(Nf(t)){let r=vk(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 si(t){return wk.test(t)}function ii(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(!Mf.has(t))throw new tt(t,`command is not in the allowlist (${[...Mf].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(xk.has(r))throw new tt(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var wk,Mf,xk,tt,xo=an(()=>{"use strict";wk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Mf=new Set(["gemini","codex","npx","node","npm","tsc"]),xk=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 Zf={};Ze(Zf,{CLI_PROVIDERS:()=>Lf,resolveCliConfig:()=>Ff});import{readFileSync as Bc}from"fs";import{join as rt}from"path";import{spawn as Sk}from"child_process";function Ff(t){let e=$k[t.provider]??t.provider;return Lf[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 kk(){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=Ff(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{ii(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=Sk(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 $k,Lf,Pk,Uf=an(()=>{"use strict";oi();ho();xo();mn();$k={"gemini-cli":"gemini","codex-cli":"codex"},Lf={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--skip-git-repo-check","--full-auto","--ephemeral",t]}};Pk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");Pk&&kk().catch(()=>process.exit(1))});var cs=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 is=class{};ne._CodeOrName=is;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Jr=class extends is{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=Jr;var lt=class extends is{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 Jr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ne._Code=lt;ne.nil=new lt("");function Uv(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._=Uv;var Sl=new lt("+");function qv(t,...e){let r=[as(t[0])],n=0;for(;n<e.length;)r.push(Sl),$l(r,e[n]),r.push(Sl,as(t[++n]));return SR(r),new lt(r)}ne.str=qv;function $l(t,e){e instanceof lt?t.push(...e._items):e instanceof Jr?t.push(e):t.push(PR(e))}ne.addCodeArg=$l;function SR(t){let e=1;for(;e<t.length-1;){if(t[e]===Sl){let r=$R(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function $R(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Jr||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 Jr))return`"${t}${e.slice(1)}`}function kR(t,e){return e.emptyStr()?t:t.emptyStr()?e:qv`${t}${e}`}ne.strConcat=kR;function PR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:as(Array.isArray(t)?t.join(","):t)}function TR(t){return new lt(as(t))}ne.stringify=TR;function as(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ne.safeStringify=as;function ER(t){return typeof t=="string"&&ne.IDENTIFIER.test(t)?new lt(`.${t}`):Uv`[${t}]`}ne.getProperty=ER;function RR(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=RR;function IR(t){return new lt(t.toString())}ne.regexpCode=IR});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=cs(),kl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},pa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(pa||(Qe.UsedValueState=pa={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var fa=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=fa;var ma=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=ma;var AR=(0,Ye._)`\n`,Pl=class extends fa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?AR:Ye.nil}}get(){return this._scope}name(e){return new ma(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,pa.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,pa.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=cs(),_t=Tl(),fr=cs();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 va=Tl();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return va.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return va.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return va.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return va.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:{}}},ha=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 ya(e,this.rhs)}},Rl=class extends ha{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:{}}},us=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)||(CR(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),{})}},Gt=class extends us{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zl=class extends us{},Zn=class extends Gt{};Zn.kind="else";var Yr=class t extends Gt{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(Vv(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 ya(e,this.condition),this.else&&Xr(e,this.else.names),e}};Yr.kind="if";var Qr=class extends Gt{};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=ya(super.names,this.from);return ya(e,this.to)}},ga=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)}},ls=class extends Gt{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)}};ls.kind="func";var ds=class extends us{render(e){return"return "+super.render(e)}};ds.kind="return";var Nl=class extends Gt{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}},ps=class extends Gt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ps.kind="catch";var fs=class extends Gt{render(e){return"finally"+super.render(e)}};fs.kind="finally";var jl=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 ha(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 ga("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 ga("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 ds;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ds)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Nl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ps(s),r(s)}return n&&(this._currNode=o.finally=new fs,this.code(n)),this._endBlockNode(ps,fs)}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 ls(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ls)}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=jl;function Xr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ya(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 CR(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Vv(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${Ll(t)}`}K.not=Vv;var DR=Bv(K.operators.AND);function zR(...t){return t.reduce(DR)}K.and=zR;var OR=Bv(K.operators.OR);function MR(...t){return t.reduce(OR)}K.or=MR;function Bv(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(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=H(),NR=cs();function jR(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=jR;function LR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Kv(t,e),!Gv(e,t.self.RULES.all))}G.alwaysValidSchema=LR;function Kv(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]||Qv(t,`unknown keyword: "${s}"`)}G.checkUnknownRules=Kv;function Gv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=Gv;function FR(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=FR;function ZR({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=ZR;function UR(t){return Jv(decodeURIComponent(t))}G.unescapeFragment=UR;function qR(t){return encodeURIComponent(Zl(t))}G.escapeFragment=qR;function Zl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=Zl;function Jv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=Jv;function VR(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=VR;function Wv({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:Wv({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:Yv}),items:Wv({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 Yv(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=Yv;function Ul(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}G.setEvaluated=Ul;var Hv={};function BR(t,e){return t.scopeValue("func",{ref:e,code:Hv[e.code]||(Hv[e.code]=new NR._Code(e.code))})}G.useFunc=BR;var Fl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Fl||(G.Type=Fl={}));function WR(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)}G.getErrorPath=WR;function Qv(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=Qv});var Jt=E(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var je=H(),HR={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")};ql.default=HR});var ms=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(),_a=oe(),Be=Jt();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 KR(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=t_(t,e,r);n??(i||a)?Xv(s,c):e_(o,(0,re._)`[${c}]`)}Le.reportError=KR;function GR(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=t_(t,e,r);Xv(o,a),s||i||e_(n,Be.default.vErrors)}Le.reportExtraError=GR;function JR(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=JR;function YR({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=YR;function Xv(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 e_(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 t_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:QR(t,e,r)}function QR(t,e,r={}){let{gen:n,it:o}=t,s=[XR(o,r),eI(t,r)];return tI(t,e,s),n.object(...s)}function XR({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,_a.getErrorPath)(e,_a.Type.Str)}`:t;return[Be.default.instancePath,(0,re.strConcat)(Be.default.instancePath,r)]}function eI({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,_a.getErrorPath)(r,_a.Type.Str)}`),[en.schemaPath,o]}function tI(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 n_=E(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.boolOrEmptySchema=qn.topBoolOrEmptySchema=void 0;var rI=ms(),nI=H(),oI=Jt(),sI={message:"boolean schema is false"};function iI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?r_(t,!1):typeof r=="object"&&r.$async===!0?e.return(oI.default.data):(e.assign((0,nI._)`${n}.errors`,null),e.return(!0))}qn.topBoolOrEmptySchema=iI;function aI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),r_(t)):r.var(e,!0)}qn.boolOrEmptySchema=aI;function r_(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,rI.reportError)(o,sI,void 0,e)}});var Vl=E(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.getRules=Vn.isJSONType=void 0;var cI=["string","number","integer","boolean","null","object","array"],uI=new Set(cI);function lI(t){return typeof t=="string"&&uI.has(t)}Vn.isJSONType=lI;function dI(){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=dI});var Bl=E(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.shouldUseRule=mr.shouldUseGroup=mr.schemaHasRulesForType=void 0;function pI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&o_(t,n)}mr.schemaHasRulesForType=pI;function o_(t,e){return e.rules.some(r=>s_(t,r))}mr.shouldUseGroup=o_;function s_(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=s_});var hs=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 fI=Vl(),mI=Bl(),hI=ms(),q=H(),i_=oe(),Bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bn||(Fe.DataType=Bn={}));function gI(t){let e=a_(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=gI;function a_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(fI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=a_;function yI(t,e){let{gen:r,data:n,opts:o}=t,s=vI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,mI.schemaHasRulesForType)(t,e[0]));if(i){let a=Hl(e,n,o.strictNumbers,Bn.Wrong);r.if(a,()=>{s.length?_I(t,e,s):Kl(t)})}return i}Fe.coerceAndCheckDataType=yI;var c_=new Set(["string","number","integer","boolean","null"]);function vI(t,e){return e?t.filter(r=>c_.has(r)||e==="array"&&r==="array"):[]}function _I(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)(c_.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),bI(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 bI({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,i_.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 wI={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=xI(t);(0,hI.reportError)(e,wI)}Fe.reportTypeError=Kl;function xI(t){let{gen:e,data:r,schema:n}=t,o=(0,i_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var l_=E(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.assignDefaults=void 0;var Wn=H(),SI=oe();function $I(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)u_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>u_(t,s,o.default))}ba.assignDefaults=$I;function u_(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,SI.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(),Gl=oe(),hr=Jt(),kI=oe();function PI(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=PI;function TI({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=TI;function EI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=EI;function d_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=d_;function Jl(t,e,r){return(0,ge._)`${d_(t)}.call(${e}, ${r})`}ue.isOwnProperty=Jl;function RI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Jl(t,e,r)}`:o}ue.propertyInData=RI;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)(Jl(t,e,r))):o}ue.noPropertyInData=Yl;function p_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=p_;function II(t,e){return p_(e).filter(r=>!(0,Gl.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=II;function AI({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=AI;var CI=(0,ge._)`new RegExp`;function DI({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"?CI:(0,kI.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=DI;function zI(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=zI;function OI(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=OI});var h_=E(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;var We=H(),tn=Jt(),MI=dt(),NI=ms();function jI(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=m_(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=jI;function LI(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;ZI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=m_(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&&f_(t),y(()=>t.error());else{let _=e.async?f():m();e.modifying&&f_(t),y(()=>FI(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,We._)`await `),x=>n.assign(d,!1).if((0,We._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,We._)`${x}.errors`),()=>n.throw(x))),_}function m(){let _=(0,We._)`${l}.errors`;return n.assign(_,null),g(We.nil),_}function g(_=e.async?(0,We._)`await `:We.nil){let x=c.opts.passContext?tn.default.this:tn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${_}${(0,MI.callValidateCode)(t,l,x,v)}`,e.modifying)}function y(_){var x;n.if((0,We.not)((x=e.valid)!==null&&x!==void 0?x:d),_)}}Ct.funcKeywordCode=LI;function f_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function FI(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,NI.extendErrors)(t)},()=>t.error())}function ZI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function m_(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 UI(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=UI;function qI({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=qI});var y_=E(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.extendSubschemaMode=gr.extendSubschemaData=gr.getSubschema=void 0;var Dt=H(),g_=oe();function VI(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,g_.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=VI;function BI(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,g_.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=BI;function WI(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=WI});var Ql=E((C4,v_)=>{"use strict";v_.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 b_=E((D4,__)=>{"use strict";var yr=__.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(){};wa(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 wa(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++)wa(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)wa(t,e,r,d[f],o+"/"+l+"/"+HI(f),s,o,l,n,f)}else(l in yr.keywords||t.allKeys&&!(l in yr.skipKeywords))&&wa(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function HI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gs=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 KI=oe(),GI=Ql(),JI=b_(),YI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function QI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Xl(t):e?w_(t)<=e:!1}Xe.inlineRef=QI;var XI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Xl(t){for(let e in t){if(XI.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 w_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!YI.has(r)&&(typeof t[r]=="object"&&(0,KI.eachItem)(t[r],n=>e+=w_(n)),e===1/0))return 1/0}return e}function x_(t,e="",r){r!==!1&&(e=Hn(e));let n=t.parse(e);return S_(t,n)}Xe.getFullPath=x_;function S_(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=S_;var eA=/#\/?$/;function Hn(t){return t?t.replace(eA,""):""}Xe.normalizeId=Hn;function tA(t,e,r){return r=Hn(r),t.resolve(e,r)}Xe.resolveUrl=tA;var rA=/^[a-z_][-a-z0-9._]*$/i;function nA(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Hn(t[r]||e),s={"":o},i=x_(n,o,!1),a={},c=new Set;return JI(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])),x.call(this,d.$anchor),x.call(this,d.$dynamicAnchor),s[p]=y;function _(v){let P=this.opts.uriResolver.resolve;if(v=Hn(y?P(y,v):v),c.has(v))throw l(v);c.add(v);let S=this.refs[v];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(d,S.schema,v):v!==Hn(g)&&(v[0]==="#"?(u(d,a[v],v),a[v]=d):this.refs[v]=g),v}function x(v){if(typeof v=="string"){if(!rA.test(v))throw new Error(`invalid anchor "${v}"`);_.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!GI(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Xe.getSchemaRefs=nA});var _s=E(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.getData=vr.KeywordCxt=vr.validateFunctionCode=void 0;var E_=n_(),$_=hs(),td=Bl(),xa=hs(),oA=l_(),vs=h_(),ed=y_(),D=H(),F=Jt(),sA=gs(),Yt=oe(),ys=ms();function iA(t){if(A_(t)&&(C_(t),I_(t))){uA(t);return}R_(t,()=>(0,E_.topBoolOrEmptySchema)(t))}vr.validateFunctionCode=iA;function R_({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"; ${k_(r,o)}`),cA(t,o),t.code(s)}):t.func(e,(0,D._)`${F.default.data}, ${aA(o)}`,n.$async,()=>t.code(k_(r,o)).code(s))}function aA(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 cA(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 uA(t){let{schema:e,opts:r,gen:n}=t;R_(t,()=>{r.$comment&&e.$comment&&z_(t),mA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&lA(t),D_(t),yA(t)})}function lA(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 k_(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 dA(t,e){if(A_(t)&&(C_(t),I_(t))){pA(t,e);return}(0,E_.boolOrEmptySchema)(t,e)}function I_({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 A_(t){return typeof t.schema!="boolean"}function pA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&z_(t),hA(t),gA(t);let s=n.const("_errs",F.default.errors);D_(t,s),n.var(e,(0,D._)`${s} === ${F.default.errors}`)}function C_(t){(0,Yt.checkUnknownRules)(t),fA(t)}function D_(t,e){if(t.opts.jtd)return P_(t,[],!1,e);let r=(0,$_.getSchemaTypes)(t.schema),n=(0,$_.coerceAndCheckDataType)(t,r);P_(t,r,!n,e)}function fA(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 mA(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 hA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,sA.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function gA(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,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 yA(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&&vA(t),e.return((0,D._)`${F.default.errors} === 0`))}function vA({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 P_(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(()=>M_(t,"$ref",l.all.$ref.definition));return}c.jtd||_A(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,xa.checkDataType)(p.type,i,c.strictNumbers)),T_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,xa.reportTypeError)(t)),o.endIf()):T_(t,p),a||o.if((0,D._)`${F.default.errors} === ${n||0}`))}}function T_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,oA.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,td.shouldUseRule)(n,s)&&M_(t,s.keyword,s.definition,e.type)})}function _A(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(bA(t,e),t.opts.allowUnionTypes||wA(t,e),xA(t,t.dataTypes))}function bA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{O_(t.dataTypes,r)||rd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),$A(t,e)}}function wA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&rd(t,"use allowUnionTypes to allow union type keyword")}function xA(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=>SA(e,i))&&rd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function SA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function O_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function $A(t,e){let r=[];for(let n of t.dataTypes)O_(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 Sa=class{constructor(e,r,n){if((0,vs.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",N_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,vs.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?ys.reportExtraError:ys.reportError)(this,this.def.error,r)}$dataError(){(0,ys.reportError)(this,this.def.$dataError||ys.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ys.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,xa.checkDataTypes)(c,r,s.opts.strictNumbers,xa.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 dA(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=Sa;function M_(t,e,r,n){let o=new Sa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,vs.funcKeywordCode)(o,r):"macro"in r?(0,vs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,vs.funcKeywordCode)(o,r)}var kA=/^\/(?:[^~]|~0|~1)*$/,PA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function N_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!kA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=PA.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=N_});var $a=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 bs=E(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var sd=gs(),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 Pa=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(),TA=$a(),rn=Jt(),wt=gs(),j_=oe(),EA=_s(),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=L_.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:TA.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,EA.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 RA(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=CA.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]=IA.call(this,s)}pt.resolveRef=RA;function IA(t){return(0,wt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ud.call(this,t)}function L_(t){for(let e of this._compilations)if(AA(e,t))return e}pt.getCompilingSchema=L_;function AA(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function CA(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ka.call(this,t,e)}function ka(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=ka.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=ka;var DA=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,j_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!DA.has(a)&&u&&(e=(0,wt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,j_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,wt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ka.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 F_=E((L4,zA)=>{zA.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((F4,V_)=>{"use strict";var OA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),U_=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 MA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Z_(t){return t.length=0,!0}function NA(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 jA(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=NA;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=Z_}else{o.push(u);continue}}return o.length&&(a===Z_?r.zone=o.join(""):i?n.push(o.join("")):n.push(ld(o))),r.address=n.join(""),r}function q_(t){if(LA(t,":")<2)return{host:t,isIPV6:!1};let e=jA(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 LA(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function FA(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 ZA(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 UA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!U_(r)){let n=q_(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}V_.exports={nonSimpleDomain:MA,recomposeAuthority:UA,normalizeComponentEncoding:ZA,removeDotSegments:FA,isIPv4:U_,isUUID:OA,normalizeIPv6:q_,stringArrayToHexStripped:ld}});var G_=E((Z4,K_)=>{"use strict";var{isUUID:qA}=dd(),VA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,BA=["http","https","ws","wss","urn","urn:uuid"];function WA(t){return BA.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 B_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function W_(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 HA(t){return t.secure=pd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function KA(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 GA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(VA);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 JA(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 YA(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!qA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function QA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var H_={scheme:"http",domainHost:!0,parse:B_,serialize:W_},XA={scheme:"https",domainHost:H_.domainHost,parse:B_,serialize:W_},Ta={scheme:"ws",domainHost:!0,parse:HA,serialize:KA},eC={scheme:"wss",domainHost:Ta.domainHost,parse:Ta.parse,serialize:Ta.serialize},tC={scheme:"urn",parse:GA,serialize:JA,skipNormalize:!0},rC={scheme:"urn:uuid",parse:YA,serialize:QA,skipNormalize:!0},Ea={http:H_,https:XA,ws:Ta,wss:eC,urn:tC,"urn:uuid":rC};Object.setPrototypeOf(Ea,null);function fd(t){return t&&(Ea[t]||Ea[t.toLowerCase()])||void 0}K_.exports={wsIsSecure:pd,SCHEMES:Ea,isValidSchemeName:WA,getSchemeHandler:fd}});var Q_=E((U4,Ia)=>{"use strict";var{normalizeIPv6:nC,removeDotSegments:ws,recomposeAuthority:oC,normalizeComponentEncoding:Ra,isIPv4:sC,nonSimpleDomain:iC}=dd(),{SCHEMES:aC,getSchemeHandler:J_}=G_();function cC(t,e){return typeof t=="string"?t=zt(Qt(t,e),e):typeof t=="object"&&(t=Qt(zt(t,e),e)),t}function uC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Y_(Qt(t,n),Qt(e,n),n,!0);return n.skipEscape=!0,zt(o,n)}function Y_(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=ws(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=ws(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ws(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=ws(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 lC(t,e,r){return typeof t=="string"?(t=unescape(t),t=zt(Ra(Qt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=zt(Ra(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=zt(Ra(Qt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=zt(Ra(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=J_(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=oC(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=ws(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 dC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\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(dC);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(sC(n.host)===!1){let c=nC(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=J_(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&iC(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:aC,normalize:cC,resolve:uC,resolveComponent:Y_,equal:lC,serialize:zt,parse:Qt};Ia.exports=md;Ia.exports.default=md;Ia.exports.fastUri=md});var eb=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var X_=Q_();X_.code='require("ajv/dist/runtime/uri").default';hd.default=X_});var cb=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 pC=_s();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return pC.KeywordCxt}});var Gn=H();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Gn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Gn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Gn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Gn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Gn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Gn.CodeGen}});var fC=$a(),sb=bs(),mC=Vl(),xs=Pa(),hC=H(),Ss=gs(),Aa=hs(),yd=oe(),tb=F_(),gC=eb(),ib=(t,e)=>new RegExp(t,e);ib.code="new RegExp";var yC=["removeAdditional","useDefaults","coerceTypes"],vC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_C={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."},bC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},rb=200;function wC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,y,_,x,v,P,S,N,L,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,Fs=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:ib,Zs=(o=t.uriResolver)!==null&&o!==void 0?o:gC.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:Fs}:{optimize:wr,regExp:Fs},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:rb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:rb,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(v=t.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(N=t.validateSchema)!==null&&N!==void 0?N:!0,validateFormats:(L=t.validateFormats)!==null&&L!==void 0?L:!0,unicodeRegExp:(Z=t.unicodeRegExp)!==null&&Z!==void 0?Z:!0,int32range:(De=t.int32range)!==null&&De!==void 0?De:!0,uriResolver:Zs}}var $s=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...wC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new hC.ValueScope({scope:{},prefixes:vC,es5:r,lines:n}),this.logger=TC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,mC.getRules)(),nb.call(this,_C,e,"NOT SUPPORTED"),nb.call(this,bC,e,"DEPRECATED","warn"),this._metaOpts=kC.call(this),e.formats&&SC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&$C.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),xC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=tb;n==="id"&&(o={...tb},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 sb.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,Ss.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=ob.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new xs.SchemaEnv({schema:{},schemaId:n});if(r=xs.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=ob.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,Ss.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(RC.call(this,n,r),!r)return(0,yd.eachItem)(n,s=>gd.call(this,s)),this;AC.call(this,r);let o={...r,type:(0,Aa.getJSONTypes)(r.type),schemaType:(0,Aa.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]=ab(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,Ss.normalizeId)(i||n);let u=Ss.getSchemaRefs.call(this,e,n);return c=new xs.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):xs.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{xs.compileSchema.call(this,e)}finally{this.opts=r}}};$s.ValidationError=fC.default;$s.MissingRefError=sb.default;Ae.default=$s;function nb(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 ob(t){return t=(0,Ss.normalizeId)(t),this.schemas[t]||this.refs[t]}function xC(){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 SC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function $C(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 kC(){let t={...this.opts};for(let e of yC)delete t[e];return t}var PC={log(){},warn(){},error(){}};function TC(t){if(t===!1)return PC;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 EC=/^[a-z_$][a-z0-9_$:-]*$/i;function RC(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(!EC.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,Aa.getJSONTypes)(e.type),schemaType:(0,Aa.getJSONTypes)(e.schemaType)}};e.before?IC.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 IC(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 AC(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=ab(e)),t.validateSchema=this.compile(e,!0))}var CC={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ab(t){return{anyOf:[t,CC]}}});var ub=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var DC={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vd.default=DC});var fb=E(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.callRef=nn.getValidate=void 0;var zC=bs(),lb=dt(),et=H(),Jn=Jt(),db=Pa(),Ca=oe(),OC={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=db.resolveRef.call(c,u,o,r);if(l===void 0)throw new zC.default(n.opts.uriResolver,o,r);if(l instanceof db.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Da(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Da(t,(0,et._)`${m}.validate`,u,u.$async)}function p(m){let g=pb(t,m);Da(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 pb(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=pb;function Da(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Jn.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,lb.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,lb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,et._)`${m}.errors`;o.assign(Jn.default.vErrors,(0,et._)`${Jn.default.vErrors} === null ? ${g} : ${Jn.default.vErrors}.concat(${g})`),o.assign(Jn.default.errors,(0,et._)`${Jn.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=Ca.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,et._)`${m}.evaluated.props`);s.props=Ca.mergeEvaluated.props(o,_,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ca.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,et._)`${m}.evaluated.items`);s.items=Ca.mergeEvaluated.items(o,_,s.items,et.Name)}}}nn.callRef=Da;nn.default=OC});var mb=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var MC=ub(),NC=fb(),jC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",MC.default,NC.default];_d.default=jC});var hb=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var za=H(),_r=za.operators,Oa={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}},LC={message:({keyword:t,schemaCode:e})=>(0,za.str)`must be ${Oa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,za._)`{comparison: ${Oa[t].okStr}, limit: ${e}}`},FC={keyword:Object.keys(Oa),type:"number",schemaType:"number",$data:!0,error:LC,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,za._)`${r} ${Oa[e].fail} ${n} || isNaN(${r})`)}};bd.default=FC});var gb=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var ks=H(),ZC={message:({schemaCode:t})=>(0,ks.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ks._)`{multipleOf: ${t}}`},UC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:ZC,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ks._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ks._)`${i} !== parseInt(${i})`;t.fail$data((0,ks._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wd.default=UC});var vb=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});function yb(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=yb;yb.code='require("ajv/dist/runtime/ucs2length").default'});var _b=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var on=H(),qC=oe(),VC=vb(),BC={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}}`},WC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:BC,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,qC.useFunc)(t.gen,VC.default)}(${r})`;t.fail$data((0,on._)`${i} ${s} ${n}`)}};Sd.default=WC});var bb=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var HC=dt(),Ma=H(),KC={message:({schemaCode:t})=>(0,Ma.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ma._)`{pattern: ${t}}`},GC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KC,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,HC.usePattern)(t,n);t.fail$data((0,Ma._)`!${a}.test(${e})`)}};$d.default=GC});var wb=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Ps=H(),JC={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ps.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ps._)`{limit: ${t}}`},YC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:JC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ps.operators.GT:Ps.operators.LT;t.fail$data((0,Ps._)`Object.keys(${r}).length ${o} ${n}`)}};kd.default=YC});var xb=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Ts=dt(),Es=H(),QC=oe(),XC={message:({params:{missingProperty:t}})=>(0,Es.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Es._)`{missingProperty: ${t}}`},eD={keyword:"required",type:"object",schemaType:"array",$data:!0,error:XC,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,QC.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Es.nil,d);else for(let f of r)(0,Ts.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,Ts.checkMissingProp)(t,r,f)),(0,Ts.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ts.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ts.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Es.not)(m),()=>{t.error(),e.break()})},Es.nil)}}};Pd.default=eD});var Sb=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Rs=H(),tD={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Rs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Rs._)`{limit: ${t}}`},rD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:tD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Rs.operators.GT:Rs.operators.LT;t.fail$data((0,Rs._)`${r}.length ${o} ${n}`)}};Td.default=rD});var Na=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var $b=Ql();$b.code='require("ajv/dist/runtime/equal").default';Ed.default=$b});var kb=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var Rd=hs(),Ce=H(),nD=oe(),oD=Na(),sD={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}}`},iD={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:sD,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),x=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 ${x}[${y}] == "number"`,()=>{e.assign(g,(0,Ce._)`${x}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ce._)`${x}[${y}] = ${m}`)})}function f(m,g){let y=(0,nD.useFunc)(e,oD.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=iD});var Pb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Ad=H(),aD=oe(),cD=Na(),uD={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ad._)`{allowedValue: ${t}}`},lD={keyword:"const",$data:!0,error:uD,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,aD.useFunc)(e,cD.default)}(${r}, ${o})`):t.fail((0,Ad._)`${s} !== ${r}`)}};Cd.default=lD});var Tb=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Is=H(),dD=oe(),pD=Na(),fD={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Is._)`{allowedValues: ${t}}`},mD={keyword:"enum",schemaType:"array",$data:!0,error:fD,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,dD.useFunc)(e,pD.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,Is.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,Is._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Is._)`${u()}(${r}, ${f}[${m}])`:(0,Is._)`${r} === ${g}`}}};Dd.default=mD});var Eb=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var hD=hb(),gD=gb(),yD=_b(),vD=bb(),_D=wb(),bD=xb(),wD=Sb(),xD=kb(),SD=Pb(),$D=Tb(),kD=[hD.default,gD.default,yD.default,vD.default,_D.default,bD.default,wD.default,xD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},SD.default,$D.default];zd.default=kD});var Md=E(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.validateAdditionalItems=void 0;var sn=H(),Od=oe(),PD={message:({params:{len:t}})=>(0,sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sn._)`{limit: ${t}}`},TD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:PD,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}Rb(t,n)}};function Rb(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())})}}As.validateAdditionalItems=Rb;As.default=TD});var Nd=E(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.validateTuple=void 0;var Ib=H(),ja=oe(),ED=dt(),RD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Ab(t,"additionalItems",e);r.items=!0,!(0,ja.alwaysValidSchema)(r,e)&&t.ok((0,ED.validateArray)(t))}};function Ab(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,Ib._)`${s}.length`);r.forEach((d,p)=>{(0,ja.alwaysValidSchema)(a,d)||(n.if((0,Ib._)`${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)}}}Cs.validateTuple=Ab;Cs.default=RD});var Cb=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var ID=Nd(),AD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,ID.validateTuple)(t,"items")};jd.default=AD});var zb=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Db=H(),CD=oe(),DD=dt(),zD=Md(),OD={message:({params:{len:t}})=>(0,Db.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Db._)`{limit: ${t}}`},MD={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:OD,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,CD.alwaysValidSchema)(n,e)&&(o?(0,zD.validateAdditionalItems)(t,o):t.ok((0,DD.validateArray)(t)))}};Ld.default=MD});var Ob=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var ft=H(),La=oe(),ND={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}}`},jD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ND,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,La.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,La.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,La.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:La.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=jD});var jb=E(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var Zd=H(),LD=oe(),Ds=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},
3
+ var LS=Object.create;var Oc=Object.defineProperty;var FS=Object.getOwnPropertyDescriptor;var ZS=Object.getOwnPropertyNames;var US=Object.getPrototypeOf,qS=Object.prototype.hasOwnProperty;var Er=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ve=(t,e)=>{for(var r in e)Oc(t,r,{get:e[r],enumerable:!0})},VS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ZS(e))!qS.call(t,o)&&o!==r&&Oc(t,o,{get:()=>e[o],enumerable:!(n=FS(e,o))||n.enumerable});return t};var uf=(t,e,r)=>(r=t!=null?LS(US(t)):{},VS(e||!t||!t.__esModule?Oc(r,"default",{value:t,enumerable:!0}):r,t));var lf,vo,df,pf,ff,mf,hf,_o,gf,Hs,yf,vf,_f,bf,wf,xf,Ks,Mc,Nc,Jj,Sf,gn,jc,Lc,$f,kf,Js,Rr,Fc,Pf,Tf,yn,qt=Er(()=>{"use strict";lf="4.10.3",vo="http://localhost:11434",df="llama3",pf=".agestra/.jobs",ff=".agestra/traces",mf=".agestra/worktrees",hf=".agestra/sessions",_o=".agestra/workspace",gf="individual",Hs="debates",yf="synthesis",vf="issue",_f=".agestra/workers",bf=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),wf=2,xf=6e4,Ks=20,Mc=5e4,Nc=10,Jj=Object.freeze([3,5,10]),Sf=Object.freeze(["agree","disagree","abstain","revise"]),gn="votes",jc=2,Lc=2,$f=1440*60*1e3,kf=3600*1e3,Js=Object.freeze(["ko","zh","ja","en"]),Rr="ko",Fc="en",Pf="[REDACTED]",Tf=["","--- 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
+ `),yn=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 BS}from"child_process";function vn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return BS("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 At(t,e=3e3){let r=t.pid;if(r)vn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e).unref?.()}var bo=Er(()=>{"use strict"});import{execFileSync as WS,spawn as HS}from"child_process";import{existsSync as KS}from"fs";function GS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:JS.has(t.toLowerCase())}function YS(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 XS(t){let e=t.toLowerCase();if(_n.has(e))return _n.get(e)??null;try{let n=WS("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:5e3}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return _n.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return _n.set(e,a),a}let i=`${n[0]}.ps1`;if(KS(i)){let a={type:"powershell",path:i};return _n.set(e,a),a}}catch{}return _n.set(e,null),null}function Vt(t,e){if(!GS(t))return{command:t,args:e};let r=XS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>YS(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function Me(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c,signal:u}=t;return new Promise((l,d)=>{if(u?.aborted){d(new ct(u.reason));return}let p=Vt(e,r),f=HS(p.command,p.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),m="",g="",v=0,_=0,S=!1,y=null,x=!1,$=null,M=()=>{$&&u&&u.removeEventListener("abort",$)},O=!1,Y=()=>{!O&&v+_>a&&(S=!0,O=!0,At(f))},Pe=()=>{x||(At(f),x=!0,M(),d(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`)))},K=setTimeout(Pe,n);u&&($=()=>{x||(x=!0,clearTimeout(K),At(f),M(),d(new ct(u.reason)))},u.addEventListener("abort",$));let ot=()=>{O||(clearTimeout(K),K=setTimeout(Pe,n))};if(f.stdout.on("data",Re=>{v+=Re.length,v<=a&&(m+=Re.toString()),Y(),ot()}),f.stderr.on("data",Re=>{_+=Re.length;let Pr=Re.toString();if(_<=a&&(g+=Pr),Y(),!O&&c){let Tr=c(Pr);Tr&&(y=Tr,O=!0,At(f))}ot()}),i&&f.stdin){f.stdin.on("error",()=>{});try{f.stdin.write(i),f.stdin.end()}catch{}}f.on("close",Re=>{if(clearTimeout(K),!x){if(y){x=!0,M(),d(y);return}x=!0,M(),l({stdout:m,stderr:g,exitCode:Re??1,truncated:S})}}),f.on("error",Re=>{clearTimeout(K),!x&&(x=!0,M(),d(new Error(`CLI spawn error: ${Re.message}`)))})})}var ct,JS,_n,bn=Er(()=>{"use strict";bo();ct=class extends Error{constructor(e){let r=e instanceof Error?`: ${e.message}`:typeof e=="string"&&e?`: ${e}`:"";super(`CLI aborted${r}`),this.name="CliAbortedError"}},JS=new Set(["codex","gemini","npm","npx"]),_n=new Map});import{writeFileSync as wk,mkdirSync as ko,openSync as Bc,writeSync as Wc,fsyncSync as Wf,closeSync as Hc,renameSync as xk,unlinkSync as Bf,appendFileSync as Sk,copyFileSync as $k}from"fs";import{dirname as Po,join as kk}from"path";import{randomUUID as Pk}from"crypto";function oe(t,e){let r=Po(t);ko(r,{recursive:!0});let n=kk(r,`.tmp-${Pk().slice(0,8)}`);try{wk(n,e,"utf-8");try{xk(n,t)}catch(o){if(o.code!=="EXDEV")throw o;$k(n,t),Bf(n)}}catch(o){try{Bf(n)}catch{}throw o}}function je(t,e){oe(t,JSON.stringify(e,null,2))}function ai(t,e){let r=Po(t);ko(r,{recursive:!0});let n=Bc(t,"a");try{Wc(n,e),Wf(n)}finally{Hc(n)}}var ii,ci=Er(()=>{"use strict";ii=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)ai(e,r);else{let s=Po(e);ko(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=Po(e);ko(n,{recursive:!0});let o=Bc(e,"a");try{Wc(o,r.join("")),Wf(o)}finally{Hc(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=Po(e);ko(n,{recursive:!0});let o=Bc(e,"a");try{Wc(o,r.join(""))}finally{Hc(o)}this.buffer.delete(e)}}});import{openSync as Tk,writeSync as Ek,closeSync as Rk,unlinkSync as Hf,statSync as Ik,mkdirSync as Ak}from"fs";import{dirname as Ck}from"path";function Mk(t){if(t<=0)return;let e=new SharedArrayBuffer(4),r=new Int32Array(e);Atomics.wait(r,0,0,t)}function Hr(t,e,r={}){let n=r.staleMs??Dk,o=r.acquireTimeoutMs??zk,s=r.pollMs??Ok;Ak(Ck(t),{recursive:!0});let i=Date.now(),a=null;for(;a===null;)try{a=Tk(t,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=!1;try{let p=Ik(t);l=Date.now()-p.mtimeMs>n}catch{continue}if(l){try{Hf(t)}catch{}continue}let d=Date.now()-i;if(d>=o)throw new Kc(t,d);Mk(s)}try{try{Ek(a,`${process.pid}@${Date.now()}
5
+ `)}catch{}return e()}finally{try{Rk(a)}catch{}try{Hf(t)}catch{}}}var Dk,zk,Ok,Kc,Jc=Er(()=>{"use strict";Dk=3e4,zk=5e3,Ok=10,Kc=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as Kf,realpathSync as Nk}from"fs";import{basename as jk,dirname as Lk,isAbsolute as Yc,join as Fk,normalize as Gf,resolve as Xc,relative as Zk}from"path";function Uk(t){return t===""||!t.startsWith("..")&&!Yc(t)}function Gc(t){let e=[],r=Xc(t);for(;!Kf(r);){let o=Lk(r);if(o===r)break;e.unshift(jk(r)),r=o}let n=Kf(r)?Nk(r):r;return e.reduce((o,s)=>Fk(o,s),n)}function Yf(t,e){let r=Gc(e),n=Gc(t),o=Zk(r,n);return Uk(o)}function Qc(t,e){let r=Xc(e,t);return Yf(r,e)}function pt(t,e){let r=Xc(e,t);if(!Yf(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Le(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 pt(t,e)}function Gt(t,e){if(Yc(t)){let r=Gf(t);if(!Qc(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return pt(t,e)}function eu(t,e){return Yc(t)?Gc(Gf(t)):pt(t,e)}function dr(t){return qk.test(t)}function ui(t,e){if(!t||typeof t!="string")throw new st(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new st(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new st(t,"command must not contain path separators");if(!Jf.has(t))throw new st(t,`command is not in the allowlist (${[...Jf].join(", ")})`);for(let r of e){if(typeof r!="string")throw new st(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new st(t,`arg contains null byte: ${JSON.stringify(r)}`);if(Vk.has(r))throw new st(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var qk,Jf,Vk,st,To=Er(()=>{"use strict";qk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Jf=new Set(["gemini","codex","npx","node","npm","tsc"]),Vk=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),st=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 em={};Ve(em,{CLI_PROVIDERS:()=>Xf,resolveCliConfig:()=>Qf});import{readFileSync as tu}from"fs";import{join as it}from"path";import{spawn as Bk}from"child_process";function Qf(t){let e=Wk[t.provider]??t.provider;return Xf[e]??null}function Kr(t,e){let r=it(t,"status.json"),n=`${r}.lock`;Hr(n,()=>{let o=JSON.parse(tu(r,"utf-8"));je(r,{...o,...e})})}async function Hk(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(tu(it(t,"job.json"),"utf-8"))}catch{try{je(it(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Qf(e);r||(Kr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Kr(t,{state:"running",startedAt:new Date().toISOString()});let s=tu(it(t,"prompt.txt"),"utf-8"),i=o(s);try{ui(n,i)}catch(c){let u=c instanceof st?c.message:`Argv rejected: ${c.message}`;Kr(t,{state:"error",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),u);return}let a;if(e.cwd)try{a=pt(e.cwd,process.cwd())}catch(c){Kr(t,{state:"error",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Vt(n,i),l=Bk(u.command,u.args,{cwd:a,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",v=>{f+=v.length,f<=10485760&&(d+=v.toString())}),l.stderr.on("data",v=>{m+=v.length,m<=10485760&&(p+=v.toString())});let g=setTimeout(()=>{At(l),oe(it(t,"output.txt"),d),oe(it(t,"error.txt"),p),Kr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",v=>{clearTimeout(g),oe(it(t,"output.txt"),d),oe(it(t,"error.txt"),p);let _=d.trim().length>0;Kr(t,{state:v===0||_?"completed":"error",exitCode:v??1,completedAt:new Date().toISOString()}),c()}),l.on("error",v=>{clearTimeout(g);let _=v.code==="ENOENT"?"missing_cli":"error";oe(it(t,"error.txt"),v.message),Kr(t,{state:_,completedAt:new Date().toISOString()}),c()})})}var Wk,Xf,Kk,tm=Er(()=>{"use strict";ci();Jc();bo();To();bn();Wk={"gemini-cli":"gemini","codex-cli":"codex"},Xf={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--skip-git-repo-check","--full-auto","--ephemeral",t]}};Kk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");Kk&&Hk().catch(()=>process.exit(1))});var ms=E(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var ps=class{};se._CodeOrName=ps;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var nn=class extends ps{constructor(e){if(super(),!se.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}}};se.Name=nn;var gt=class extends ps{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 nn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};se._Code=gt;se.nil=new gt("");function t_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ml(r,e[n]),r.push(t[++n]);return new gt(r)}se._=t_;var Ol=new gt("+");function r_(t,...e){let r=[fs(t[0])],n=0;for(;n<e.length;)r.push(Ol),Ml(r,e[n]),r.push(Ol,fs(t[++n]));return WR(r),new gt(r)}se.str=r_;function Ml(t,e){e instanceof gt?t.push(...e._items):e instanceof nn?t.push(e):t.push(JR(e))}se.addCodeArg=Ml;function WR(t){let e=1;for(;e<t.length-1;){if(t[e]===Ol){let r=HR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function HR(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof nn||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 nn))return`"${t}${e.slice(1)}`}function KR(t,e){return e.emptyStr()?t:t.emptyStr()?e:r_`${t}${e}`}se.strConcat=KR;function JR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:fs(Array.isArray(t)?t.join(","):t)}function GR(t){return new gt(fs(t))}se.stringify=GR;function fs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}se.safeStringify=fs;function YR(t){return typeof t=="string"&&se.IDENTIFIER.test(t)?new gt(`.${t}`):t_`[${t}]`}se.getProperty=YR;function XR(t){if(typeof t=="string"&&se.IDENTIFIER.test(t))return new gt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}se.getEsmExportName=XR;function QR(t){return new gt(t.toString())}se.regexpCode=QR});var Ll=E(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.ValueScope=tt.ValueScopeName=tt.Scope=tt.varKinds=tt.UsedValueState=void 0;var et=ms(),Nl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ha;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ha||(tt.UsedValueState=ha={}));tt.varKinds={const:new et.Name("const"),let:new et.Name("let"),var:new et.Name("var")};var ga=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof et.Name?e:this.name(e)}name(e){return new et.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}}};tt.Scope=ga;var ya=class extends et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,et._)`.${new et.Name(r)}[${n}]`}};tt.ValueScopeName=ya;var eI=(0,et._)`\n`,jl=class extends ga{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?eI:et.nil}}get(){return this._scope}name(e){return new ya(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,et._)`${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=et.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,ha.Started);let l=r(u);if(l){let d=this.opts.es5?tt.varKinds.var:tt.varKinds.const;s=(0,et._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,et._)`${s}${l}${this.opts._n}`;else throw new Nl(u);c.set(u,ha.Completed)})}return s}};tt.ValueScope=jl});var W=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 re=ms(),$t=Ll(),vr=ms();Object.defineProperty(H,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(H,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(H,"strConcat",{enumerable:!0,get:function(){return vr.strConcat}});Object.defineProperty(H,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(H,"getProperty",{enumerable:!0,get:function(){return vr.getProperty}});Object.defineProperty(H,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(H,"regexpCode",{enumerable:!0,get:function(){return vr.regexpCode}});Object.defineProperty(H,"Name",{enumerable:!0,get:function(){return vr.Name}});var wa=Ll();Object.defineProperty(H,"Scope",{enumerable:!0,get:function(){return wa.Scope}});Object.defineProperty(H,"ValueScope",{enumerable:!0,get:function(){return wa.ValueScope}});Object.defineProperty(H,"ValueScopeName",{enumerable:!0,get:function(){return wa.ValueScopeName}});Object.defineProperty(H,"varKinds",{enumerable:!0,get:function(){return wa.varKinds}});H.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var er=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Fl=class extends er{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=Hn(this.rhs,e,r)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},va=class extends er{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 re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Hn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return ba(e,this.rhs)}},Zl=class extends va{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ul=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ql=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Vl=class extends er{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Bl=class extends er{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=Hn(this.code,e,r),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},hs=class extends er{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)||(tI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>an(e,r.names),{})}},tr=class extends hs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Wl=class extends hs{},Wn=class extends tr{};Wn.kind="else";var on=class t extends tr{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 Wn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(n_(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=Hn(this.condition,e,r),this}get names(){let e=super.names;return ba(e,this.condition),this.else&&an(e,this.else.names),e}};on.kind="if";var sn=class extends tr{};sn.kind="for";var Hl=class extends sn{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=Hn(this.iteration,e,r),this}get names(){return an(super.names,this.iteration.names)}},Kl=class extends sn{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=ba(super.names,this.from);return ba(e,this.to)}},_a=class extends sn{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=Hn(this.iterable,e,r),this}get names(){return an(super.names,this.iterable.names)}},gs=class extends tr{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)}};gs.kind="func";var ys=class extends hs{render(e){return"return "+super.render(e)}};ys.kind="return";var Jl=class extends tr{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&&an(e,this.catch.names),this.finally&&an(e,this.finally.names),e}},vs=class extends tr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};vs.kind="catch";var _s=class extends tr{render(e){return"finally"+super.render(e)}};_s.kind="finally";var Gl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
6
+ `:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new Wl]}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 Fl(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 va(e,r,n))}add(e,r){return this._leafNode(new Zl(e,H.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Bl(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,re.addCodeArg)(r,o));return r.push("}"),new re._Code(r)}if(e,r,n){if(this._blockNode(new on(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 on(e))}else(){return this._elseNode(new Wn)}endIf(){return this._endBlockNode(on,Wn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Hl(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 Kl(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 re.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,re._)`${i}.length`,a=>{this.var(s,(0,re._)`${i}[${a}]`),n(s)})}return this._for(new _a("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,re._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new _a("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(sn)}label(e){return this._leafNode(new Ul(e))}break(e){return this._leafNode(new ql(e))}return(e){let r=new ys;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ys)}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 vs(s),r(s)}return n&&(this._currNode=o.finally=new _s,this.code(n)),this._endBlockNode(vs,_s)}throw(e){return this._leafNode(new Vl(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=re.nil,n,o){return this._blockNode(new gs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(gs)}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 on))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=Gl;function an(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ba(t,e){return e instanceof re._CodeOrName?an(t,e.names):t}function Hn(t,e,r){if(t instanceof re.Name)return n(t);if(!o(t))return t;return new re._Code(t._items.reduce((s,i)=>(i instanceof re.Name&&(i=n(i)),i instanceof re._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 re._Code&&s._items.some(i=>i instanceof re.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function tI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function n_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,re._)`!${Yl(t)}`}H.not=n_;var rI=o_(H.operators.AND);function nI(...t){return t.reduce(rI)}H.and=nI;var oI=o_(H.operators.OR);function sI(...t){return t.reduce(oI)}H.or=sI;function o_(t){return(e,r)=>e===re.nil?r:r===re.nil?e:(0,re._)`${Yl(e)} ${t} ${Yl(r)}`}function Yl(t){return t instanceof re.Name?t:(0,re._)`(${t})`}});var ie=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=W(),iI=ms();function aI(t){let e={};for(let r of t)e[r]=!0;return e}J.toHash=aI;function cI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(a_(t,e),!c_(e,t.self.RULES.all))}J.alwaysValidSchema=cI;function a_(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]||d_(t,`unknown keyword: "${s}"`)}J.checkUnknownRules=a_;function c_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}J.schemaHasRules=c_;function uI(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=uI;function lI({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=lI;function dI(t){return u_(decodeURIComponent(t))}J.unescapeFragment=dI;function pI(t){return encodeURIComponent(Ql(t))}J.escapeFragment=pI;function Ql(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=Ql;function u_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=u_;function fI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}J.eachItem=fI;function s_({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:s_({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} || {}`),ed(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:l_}),items:s_({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 l_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&ed(t,r,e),r}J.evaluatedPropsToName=l_;function ed(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}J.setEvaluated=ed;var i_={};function mI(t,e){return t.scopeValue("func",{ref:e,code:i_[e.code]||(i_[e.code]=new iI._Code(e.code))})}J.useFunc=mI;var Xl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Xl||(J.Type=Xl={}));function hI(t,e,r){if(t instanceof le.Name){let n=e===Xl.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():"/"+Ql(t)}J.getErrorPath=hI;function d_(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=d_});var rr=E(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var Ze=W(),gI={data:new Ze.Name("data"),valCxt:new Ze.Name("valCxt"),instancePath:new Ze.Name("instancePath"),parentData:new Ze.Name("parentData"),parentDataProperty:new Ze.Name("parentDataProperty"),rootData:new Ze.Name("rootData"),dynamicAnchors:new Ze.Name("dynamicAnchors"),vErrors:new Ze.Name("vErrors"),errors:new Ze.Name("errors"),this:new Ze.Name("this"),self:new Ze.Name("self"),scope:new Ze.Name("scope"),json:new Ze.Name("json"),jsonPos:new Ze.Name("jsonPos"),jsonLen:new Ze.Name("jsonLen"),jsonPart:new Ze.Name("jsonPart")};td.default=gI});var bs=E(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.extendErrors=Ue.resetErrorsCount=Ue.reportExtraError=Ue.reportError=Ue.keyword$DataError=Ue.keywordError=void 0;var ne=W(),xa=ie(),Je=rr();Ue.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function yI(t,e=Ue.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=m_(t,e,r);n??(i||a)?p_(s,c):f_(o,(0,ne._)`[${c}]`)}Ue.reportError=yI;function vI(t,e=Ue.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=m_(t,e,r);p_(o,a),s||i||f_(n,Je.default.vErrors)}Ue.reportExtraError=vI;function _I(t,e){t.assign(Je.default.errors,e),t.if((0,ne._)`${Je.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Je.default.vErrors}.length`,e),()=>t.assign(Je.default.vErrors,null)))}Ue.resetErrorsCount=_I;function bI({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,Je.default.errors,a=>{t.const(i,(0,ne._)`${Je.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Je.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ue.extendErrors=bI;function p_(t,e){let r=t.const("err",e);t.if((0,ne._)`${Je.default.vErrors} === null`,()=>t.assign(Je.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Je.default.vErrors}.push(${r})`),t.code((0,ne._)`${Je.default.errors}++`)}function f_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var cn={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function m_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:wI(t,e,r)}function wI(t,e,r={}){let{gen:n,it:o}=t,s=[xI(o,r),SI(t,r)];return $I(t,e,s),n.object(...s)}function xI({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,xa.getErrorPath)(e,xa.Type.Str)}`:t;return[Je.default.instancePath,(0,ne.strConcat)(Je.default.instancePath,r)]}function SI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,xa.getErrorPath)(r,xa.Type.Str)}`),[cn.schemaPath,o]}function $I(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([cn.keyword,o],[cn.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([cn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([cn.schema,i],[cn.parentSchema,(0,ne._)`${l}${d}`],[Je.default.data,s]),u&&n.push([cn.propertyName,u])}});var g_=E(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.boolOrEmptySchema=Kn.topBoolOrEmptySchema=void 0;var kI=bs(),PI=W(),TI=rr(),EI={message:"boolean schema is false"};function RI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?h_(t,!1):typeof r=="object"&&r.$async===!0?e.return(TI.default.data):(e.assign((0,PI._)`${n}.errors`,null),e.return(!0))}Kn.topBoolOrEmptySchema=RI;function II(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),h_(t)):r.var(e,!0)}Kn.boolOrEmptySchema=II;function h_(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,kI.reportError)(o,EI,void 0,e)}});var rd=E(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.getRules=Jn.isJSONType=void 0;var AI=["string","number","integer","boolean","null","object","array"],CI=new Set(AI);function DI(t){return typeof t=="string"&&CI.has(t)}Jn.isJSONType=DI;function zI(){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:{}}}Jn.getRules=zI});var nd=E(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.shouldUseRule=_r.shouldUseGroup=_r.schemaHasRulesForType=void 0;function OI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&y_(t,n)}_r.schemaHasRulesForType=OI;function y_(t,e){return e.rules.some(r=>v_(t,r))}_r.shouldUseGroup=y_;function v_(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))}_r.shouldUseRule=v_});var ws=E(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.reportTypeError=qe.checkDataTypes=qe.checkDataType=qe.coerceAndCheckDataType=qe.getJSONTypes=qe.getSchemaTypes=qe.DataType=void 0;var MI=rd(),NI=nd(),jI=bs(),U=W(),__=ie(),Gn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gn||(qe.DataType=Gn={}));function LI(t){let e=b_(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}qe.getSchemaTypes=LI;function b_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(MI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}qe.getJSONTypes=b_;function FI(t,e){let{gen:r,data:n,opts:o}=t,s=ZI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,NI.schemaHasRulesForType)(t,e[0]));if(i){let a=sd(e,n,o.strictNumbers,Gn.Wrong);r.if(a,()=>{s.length?UI(t,e,s):id(t)})}return i}qe.coerceAndCheckDataType=FI;var w_=new Set(["string","number","integer","boolean","null"]);function ZI(t,e){return e?t.filter(r=>w_.has(r)||e==="array"&&r==="array"):[]}function UI(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,U._)`typeof ${o}`),a=n.let("coerced",(0,U._)`undefined`);s.coerceTypes==="array"&&n.if((0,U._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,U._)`${o}[0]`).assign(i,(0,U._)`typeof ${o}`).if(sd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,U._)`${a} !== undefined`);for(let u of r)(w_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),id(t),n.endIf(),n.if((0,U._)`${a} !== undefined`,()=>{n.assign(o,a),qI(t,a)});function c(u){switch(u){case"string":n.elseIf((0,U._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,U._)`"" + ${o}`).elseIf((0,U._)`${o} === null`).assign(a,(0,U._)`""`);return;case"number":n.elseIf((0,U._)`${i} == "boolean" || ${o} === null
7
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,U._)`+${o}`);return;case"integer":n.elseIf((0,U._)`${i} === "boolean" || ${o} === null
8
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,U._)`+${o}`);return;case"boolean":n.elseIf((0,U._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,U._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,U._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,U._)`${i} === "string" || ${i} === "number"
9
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,U._)`[${o}]`)}}}function qI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,U._)`${e} !== undefined`,()=>t.assign((0,U._)`${e}[${r}]`,n))}function od(t,e,r,n=Gn.Correct){let o=n===Gn.Correct?U.operators.EQ:U.operators.NEQ,s;switch(t){case"null":return(0,U._)`${e} ${o} null`;case"array":s=(0,U._)`Array.isArray(${e})`;break;case"object":s=(0,U._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,U._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,U._)`typeof ${e} ${o} ${t}`}return n===Gn.Correct?s:(0,U.not)(s);function i(a=U.nil){return(0,U.and)((0,U._)`typeof ${e} == "number"`,a,r?(0,U._)`isFinite(${e})`:U.nil)}}qe.checkDataType=od;function sd(t,e,r,n){if(t.length===1)return od(t[0],e,r,n);let o,s=(0,__.toHash)(t);if(s.array&&s.object){let i=(0,U._)`typeof ${e} != "object"`;o=s.null?i:(0,U._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=U.nil;s.number&&delete s.integer;for(let i in s)o=(0,U.and)(o,od(i,e,r,n));return o}qe.checkDataTypes=sd;var VI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,U._)`{type: ${t}}`:(0,U._)`{type: ${e}}`};function id(t){let e=BI(t);(0,jI.reportError)(e,VI)}qe.reportTypeError=id;function BI(t){let{gen:e,data:r,schema:n}=t,o=(0,__.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var S_=E(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.assignDefaults=void 0;var Yn=W(),WI=ie();function HI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)x_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>x_(t,s,o.default))}Sa.assignDefaults=HI;function x_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Yn._)`${s}${(0,Yn.getProperty)(e)}`;if(o){(0,WI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Yn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Yn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Yn._)`${a} = ${(0,Yn.stringify)(r)}`)}});var yt=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=W(),ad=ie(),br=rr(),KI=ie();function JI(t,e){let{gen:r,data:n,it:o}=t;r.if(ud(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=JI;function GI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(ud(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=GI;function YI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=YI;function $_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=$_;function cd(t,e,r){return(0,ge._)`${$_(t)}.call(${e}, ${r})`}ue.isOwnProperty=cd;function XI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${cd(t,e,r)}`:o}ue.propertyInData=XI;function ud(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(cd(t,e,r))):o}ue.noPropertyInData=ud;function k_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=k_;function QI(t,e){return k_(e).filter(r=>!(0,ad.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=QI;function eA({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=[[br.default.instancePath,(0,ge.strConcat)(br.default.instancePath,s)],[br.default.parentData,i.parentData],[br.default.parentDataProperty,i.parentDataProperty],[br.default.rootData,br.default.rootData]];i.opts.dynamicRef&&d.push([br.default.dynamicAnchors,br.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=eA;var tA=(0,ge._)`new RegExp`;function rA({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"?tA:(0,KI.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=rA;function nA(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:ad.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=nA;function oA(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,ad.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=oA});var E_=E(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.validateKeywordUsage=Nt.validSchemaType=Nt.funcKeywordCode=Nt.macroKeywordCode=void 0;var Ge=W(),un=rr(),sA=yt(),iA=bs();function aA(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=T_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ge.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Nt.macroKeywordCode=aA;function cA(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;lA(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=T_(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&&P_(t),v(()=>t.error());else{let _=e.async?f():m();e.modifying&&P_(t),v(()=>uA(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,Ge._)`await `),S=>n.assign(d,!1).if((0,Ge._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Ge._)`${S}.errors`),()=>n.throw(S))),_}function m(){let _=(0,Ge._)`${l}.errors`;return n.assign(_,null),g(Ge.nil),_}function g(_=e.async?(0,Ge._)`await `:Ge.nil){let S=c.opts.passContext?un.default.this:un.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ge._)`${_}${(0,sA.callValidateCode)(t,l,S,y)}`,e.modifying)}function v(_){var S;n.if((0,Ge.not)((S=e.valid)!==null&&S!==void 0?S:d),_)}}Nt.funcKeywordCode=cA;function P_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ge._)`${n.parentData}[${n.parentDataProperty}]`))}function uA(t,e){let{gen:r}=t;r.if((0,Ge._)`Array.isArray(${e})`,()=>{r.assign(un.default.vErrors,(0,Ge._)`${un.default.vErrors} === null ? ${e} : ${un.default.vErrors}.concat(${e})`).assign(un.default.errors,(0,Ge._)`${un.default.vErrors}.length`),(0,iA.extendErrors)(t)},()=>t.error())}function lA({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function T_(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,Ge.stringify)(r)})}function dA(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")}Nt.validSchemaType=dA;function pA({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)}}Nt.validateKeywordUsage=pA});var I_=E(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;var jt=W(),R_=ie();function fA(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,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}${(0,jt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,R_.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')}wr.getSubschema=fA;function mA(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,jt._)`${e.data}${(0,jt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,jt.str)`${u}${(0,R_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,jt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof jt.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]}}wr.extendSubschemaData=mA;function hA(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}wr.extendSubschemaMode=hA});var ld=E((lB,A_)=>{"use strict";A_.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 D_=E((dB,C_)=>{"use strict";var xr=C_.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(){};$a(e,n,o,t,"",t)};xr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};xr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};xr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};xr.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 $a(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 xr.arrayKeywords)for(var p=0;p<d.length;p++)$a(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in xr.propsKeywords){if(d&&typeof d=="object")for(var f in d)$a(t,e,r,d[f],o+"/"+l+"/"+gA(f),s,o,l,n,f)}else(l in xr.keywords||t.allKeys&&!(l in xr.skipKeywords))&&$a(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function gA(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var xs=E(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getSchemaRefs=rt.resolveUrl=rt.normalizeId=rt._getFullPath=rt.getFullPath=rt.inlineRef=void 0;var yA=ie(),vA=ld(),_A=D_(),bA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wA(t,e=!0){return typeof t=="boolean"?!0:e===!0?!dd(t):e?z_(t)<=e:!1}rt.inlineRef=wA;var xA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function dd(t){for(let e in t){if(xA.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(dd)||typeof r=="object"&&dd(r))return!0}return!1}function z_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!bA.has(r)&&(typeof t[r]=="object"&&(0,yA.eachItem)(t[r],n=>e+=z_(n)),e===1/0))return 1/0}return e}function O_(t,e="",r){r!==!1&&(e=Xn(e));let n=t.parse(e);return M_(t,n)}rt.getFullPath=O_;function M_(t,e){return t.serialize(e).split("#")[0]+"#"}rt._getFullPath=M_;var SA=/#\/?$/;function Xn(t){return t?t.replace(SA,""):""}rt.normalizeId=Xn;function $A(t,e,r){return r=Xn(r),t.resolve(e,r)}rt.resolveUrl=$A;var kA=/^[a-z_][-a-z0-9._]*$/i;function PA(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xn(t[r]||e),s={"":o},i=O_(n,o,!1),a={},c=new Set;return _A(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,v=s[m];typeof d[r]=="string"&&(v=_.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[p]=v;function _(y){let x=this.opts.uriResolver.resolve;if(y=Xn(v?x(v,y):y),c.has(y))throw l(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,y):y!==Xn(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function S(y){if(typeof y=="string"){if(!kA.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,p,f){if(p!==void 0&&!vA(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rt.getSchemaRefs=PA});var ks=E(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.getData=Sr.KeywordCxt=Sr.validateFunctionCode=void 0;var Z_=g_(),N_=ws(),fd=nd(),ka=ws(),TA=S_(),$s=E_(),pd=I_(),D=W(),F=rr(),EA=xs(),nr=ie(),Ss=bs();function RA(t){if(V_(t)&&(B_(t),q_(t))){CA(t);return}U_(t,()=>(0,Z_.topBoolOrEmptySchema)(t))}Sr.validateFunctionCode=RA;function U_({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"; ${j_(r,o)}`),AA(t,o),t.code(s)}):t.func(e,(0,D._)`${F.default.data}, ${IA(o)}`,n.$async,()=>t.code(j_(r,o)).code(s))}function IA(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 AA(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 CA(t){let{schema:e,opts:r,gen:n}=t;U_(t,()=>{r.$comment&&e.$comment&&H_(t),NA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&DA(t),W_(t),FA(t)})}function DA(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 j_(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 zA(t,e){if(V_(t)&&(B_(t),q_(t))){OA(t,e);return}(0,Z_.boolOrEmptySchema)(t,e)}function q_({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 V_(t){return typeof t.schema!="boolean"}function OA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&H_(t),jA(t),LA(t);let s=n.const("_errs",F.default.errors);W_(t,s),n.var(e,(0,D._)`${s} === ${F.default.errors}`)}function B_(t){(0,nr.checkUnknownRules)(t),MA(t)}function W_(t,e){if(t.opts.jtd)return L_(t,[],!1,e);let r=(0,N_.getSchemaTypes)(t.schema),n=(0,N_.coerceAndCheckDataType)(t,r);L_(t,r,!n,e)}function MA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,nr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function NA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,nr.checkStrictMode)(t,"default is ignored in the schema root")}function jA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,EA.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 H_({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 FA(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&&ZA(t),e.return((0,D._)`${F.default.errors} === 0`))}function ZA({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 L_(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,nr.schemaHasRulesButRef)(s,l))){o.block(()=>J_(t,"$ref",l.all.$ref.definition));return}c.jtd||UA(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,fd.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ka.checkDataType)(p.type,i,c.strictNumbers)),F_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,ka.reportTypeError)(t)),o.endIf()):F_(t,p),a||o.if((0,D._)`${F.default.errors} === ${n||0}`))}}function F_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,TA.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,fd.shouldUseRule)(n,s)&&J_(t,s.keyword,s.definition,e.type)})}function UA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(qA(t,e),t.opts.allowUnionTypes||VA(t,e),BA(t,t.dataTypes))}function qA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{K_(t.dataTypes,r)||md(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),HA(t,e)}}function VA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&md(t,"use allowUnionTypes to allow union type keyword")}function BA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,fd.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>WA(e,i))&&md(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function WA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function K_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function HA(t,e){let r=[];for(let n of t.dataTypes)K_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function md(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,nr.checkStrictMode)(t,e,t.opts.strictTypes)}var Pa=class{constructor(e,r,n){if((0,$s.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,nr.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",G_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,$s.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?Ss.reportExtraError:Ss.reportError)(this,this.def.error,r)}$dataError(){(0,Ss.reportError)(this,this.def.$dataError||Ss.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ss.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,ka.checkDataTypes)(c,r,s.opts.strictNumbers,ka.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,pd.getSubschema)(this.it,e);(0,pd.extendSubschemaData)(n,this.it,e),(0,pd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return zA(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=nr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=nr.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}};Sr.KeywordCxt=Pa;function J_(t,e,r,n){let o=new Pa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,$s.funcKeywordCode)(o,r):"macro"in r?(0,$s.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,$s.funcKeywordCode)(o,r)}var KA=/^\/(?:[^~]|~0|~1)*$/,JA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function G_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!KA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=JA.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,nr.unescapeJsonPointer)(u))}`,i=(0,D._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Sr.getData=G_});var Ta=E(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var hd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};gd.default=hd});var Ps=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var yd=xs(),vd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,yd.resolveUrl)(e,r,n),this.missingSchema=(0,yd.normalizeId)((0,yd.getFullPath)(e,this.missingRef))}};_d.default=vd});var Ra=E(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.resolveSchema=vt.getCompilingSchema=vt.resolveRef=vt.compileSchema=vt.SchemaEnv=void 0;var kt=W(),GA=Ta(),ln=rr(),Pt=xs(),Y_=ie(),YA=ks(),Qn=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,Pt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};vt.SchemaEnv=Qn;function wd(t){let e=X_.call(this,t);if(e)return e;let r=(0,Pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:GA.default,code:(0,kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ln.default.data,parentData:ln.default.parentData,parentDataProperty:ln.default.parentDataProperty,dataNames:[ln.default.data],dataPathArr:[kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,YA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(ln.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${ln.default.self}`,`${ln.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 kt.Name?void 0:m,items:g instanceof kt.Name?void 0:g,dynamicProps:m instanceof kt.Name,dynamicItems:g instanceof kt.Name},f.source&&(f.source.evaluated=(0,kt.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)}}vt.compileSchema=wd;function XA(t,e,r){var n;r=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=tC.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 Qn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=QA.call(this,s)}vt.resolveRef=XA;function QA(t){return(0,Pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:wd.call(this,t)}function X_(t){for(let e of this._compilations)if(eC(e,t))return e}vt.getCompilingSchema=X_;function eC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function tC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ea.call(this,t,e)}function Ea(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pt._getFullPath)(this.opts.uriResolver,r),o=(0,Pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return bd.call(this,r,t);let s=(0,Pt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ea.call(this,t,i);return typeof a?.schema!="object"?void 0:bd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||wd.call(this,i),s===(0,Pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pt.resolveUrl)(this.opts.uriResolver,o,u)),new Qn({schema:a,schemaId:c,root:t,baseId:o})}return bd.call(this,r,i)}}vt.resolveSchema=Ea;var rC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function bd(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,Y_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!rC.has(a)&&u&&(e=(0,Pt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Y_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ea.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Qn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Q_=E((yB,nC)=>{nC.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 Sd=E((vB,nb)=>{"use strict";var oC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),tb=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 xd(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 sC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function eb(t){return t.length=0,!0}function iC(t,e,r){if(t.length){let n=xd(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function aC(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=iC;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=eb}else{o.push(u);continue}}return o.length&&(a===eb?r.zone=o.join(""):i?n.push(o.join("")):n.push(xd(o))),r.address=n.join(""),r}function rb(t){if(cC(t,":")<2)return{host:t,isIPV6:!1};let e=aC(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 cC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function uC(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 lC(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 dC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!tb(r)){let n=rb(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}nb.exports={nonSimpleDomain:sC,recomposeAuthority:dC,normalizeComponentEncoding:lC,removeDotSegments:uC,isIPv4:tb,isUUID:oC,normalizeIPv6:rb,stringArrayToHexStripped:xd}});var cb=E((_B,ab)=>{"use strict";var{isUUID:pC}=Sd(),fC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,mC=["http","https","ws","wss","urn","urn:uuid"];function hC(t){return mC.indexOf(t)!==-1}function $d(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 ob(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function sb(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 gC(t){return t.secure=$d(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function yC(t){if((t.port===($d(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 vC(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(fC);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=kd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function _C(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=kd(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 bC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function wC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var ib={scheme:"http",domainHost:!0,parse:ob,serialize:sb},xC={scheme:"https",domainHost:ib.domainHost,parse:ob,serialize:sb},Ia={scheme:"ws",domainHost:!0,parse:gC,serialize:yC},SC={scheme:"wss",domainHost:Ia.domainHost,parse:Ia.parse,serialize:Ia.serialize},$C={scheme:"urn",parse:vC,serialize:_C,skipNormalize:!0},kC={scheme:"urn:uuid",parse:bC,serialize:wC,skipNormalize:!0},Aa={http:ib,https:xC,ws:Ia,wss:SC,urn:$C,"urn:uuid":kC};Object.setPrototypeOf(Aa,null);function kd(t){return t&&(Aa[t]||Aa[t.toLowerCase()])||void 0}ab.exports={wsIsSecure:$d,SCHEMES:Aa,isValidSchemeName:hC,getSchemeHandler:kd}});var db=E((bB,Da)=>{"use strict";var{normalizeIPv6:PC,removeDotSegments:Ts,recomposeAuthority:TC,normalizeComponentEncoding:Ca,isIPv4:EC,nonSimpleDomain:RC}=Sd(),{SCHEMES:IC,getSchemeHandler:ub}=cb();function AC(t,e){return typeof t=="string"?t=Lt(or(t,e),e):typeof t=="object"&&(t=or(Lt(t,e),e)),t}function CC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=lb(or(t,n),or(e,n),n,!0);return n.skipEscape=!0,Lt(o,n)}function lb(t,e,r,n){let o={};return n||(t=or(Lt(t,r),r),e=or(Lt(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=Ts(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=Ts(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ts(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=Ts(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 DC(t,e,r){return typeof t=="string"?(t=unescape(t),t=Lt(Ca(or(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Lt(Ca(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Lt(Ca(or(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Lt(Ca(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Lt(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=ub(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=TC(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=Ts(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 zC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function or(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(zC);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(EC(n.host)===!1){let c=PC(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=ub(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&RC(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 Pd={SCHEMES:IC,normalize:AC,resolve:CC,resolveComponent:lb,equal:DC,serialize:Lt,parse:or};Da.exports=Pd;Da.exports.default=Pd;Da.exports.fastUri=Pd});var fb=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var pb=db();pb.code='require("ajv/dist/runtime/uri").default';Td.default=pb});var wb=E(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.CodeGen=ze.Name=ze.nil=ze.stringify=ze.str=ze._=ze.KeywordCxt=void 0;var OC=ks();Object.defineProperty(ze,"KeywordCxt",{enumerable:!0,get:function(){return OC.KeywordCxt}});var eo=W();Object.defineProperty(ze,"_",{enumerable:!0,get:function(){return eo._}});Object.defineProperty(ze,"str",{enumerable:!0,get:function(){return eo.str}});Object.defineProperty(ze,"stringify",{enumerable:!0,get:function(){return eo.stringify}});Object.defineProperty(ze,"nil",{enumerable:!0,get:function(){return eo.nil}});Object.defineProperty(ze,"Name",{enumerable:!0,get:function(){return eo.Name}});Object.defineProperty(ze,"CodeGen",{enumerable:!0,get:function(){return eo.CodeGen}});var MC=Ta(),vb=Ps(),NC=rd(),Es=Ra(),jC=W(),Rs=xs(),za=ws(),Rd=ie(),mb=Q_(),LC=fb(),_b=(t,e)=>new RegExp(t,e);_b.code="new RegExp";var FC=["removeAdditional","useDefaults","coerceTypes"],ZC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),UC={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."},qC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},hb=200;function VC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,v,_,S,y,x,$,M,O,Y,Pe;let K=t.strict,ot=(e=t.code)===null||e===void 0?void 0:e.optimize,Re=ot===!0||ot===void 0?1:ot||0,Pr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:_b,Tr=(o=t.uriResolver)!==null&&o!==void 0?o:LC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:K)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:K)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:K)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:K)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:K)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Re,regExp:Pr}:{optimize:Re,regExp:Pr},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:hb,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:hb,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(M=t.validateSchema)!==null&&M!==void 0?M:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(Y=t.unicodeRegExp)!==null&&Y!==void 0?Y:!0,int32range:(Pe=t.int32range)!==null&&Pe!==void 0?Pe:!0,uriResolver:Tr}}var Is=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...VC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new jC.ValueScope({scope:{},prefixes:ZC,es5:r,lines:n}),this.logger=GC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,NC.getRules)(),gb.call(this,UC,e,"NOT SUPPORTED"),gb.call(this,qC,e,"DEPRECATED","warn"),this._metaOpts=KC.call(this),e.formats&&WC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&HC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),BC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=mb;n==="id"&&(o={...mb},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 vb.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,Rs.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=yb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Es.SchemaEnv({schema:{},schemaId:n});if(r=Es.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=yb.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,Rs.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(XC.call(this,n,r),!r)return(0,Rd.eachItem)(n,s=>Ed.call(this,s)),this;eD.call(this,r);let o={...r,type:(0,za.getJSONTypes)(r.type),schemaType:(0,za.getJSONTypes)(r.schemaType)};return(0,Rd.eachItem)(n,o.type.length===0?s=>Ed.call(this,s,o):s=>o.type.forEach(i=>Ed.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]=bb(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,Rs.normalizeId)(i||n);let u=Rs.getSchemaRefs.call(this,e,n);return c=new Es.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):Es.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{Es.compileSchema.call(this,e)}finally{this.opts=r}}};Is.ValidationError=MC.default;Is.MissingRefError=vb.default;ze.default=Is;function gb(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 yb(t){return t=(0,Rs.normalizeId)(t),this.schemas[t]||this.refs[t]}function BC(){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 WC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function HC(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 KC(){let t={...this.opts};for(let e of FC)delete t[e];return t}var JC={log(){},warn(){},error(){}};function GC(t){if(t===!1)return JC;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 YC=/^[a-z_$][a-z0-9_$:-]*$/i;function XC(t,e){let{RULES:r}=this;if((0,Rd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!YC.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 Ed(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,za.getJSONTypes)(e.type),schemaType:(0,za.getJSONTypes)(e.schemaType)}};e.before?QC.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 QC(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 eD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=bb(e)),t.validateSchema=this.compile(e,!0))}var tD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function bb(t){return{anyOf:[t,tD]}}});var xb=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var rD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Id.default=rD});var Pb=E(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.callRef=dn.getValidate=void 0;var nD=Ps(),Sb=yt(),nt=W(),to=rr(),$b=Ra(),Oa=ie(),oD={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=$b.resolveRef.call(c,u,o,r);if(l===void 0)throw new nD.default(n.opts.uriResolver,o,r);if(l instanceof $b.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Ma(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Ma(t,(0,nt._)`${m}.validate`,u,u.$async)}function p(m){let g=kb(t,m);Ma(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,nt.stringify)(m)}:{ref:m}),v=e.name("valid"),_=t.subschema({schema:m,dataTypes:[],schemaPath:nt.nil,topSchemaRef:g,errSchemaPath:r},v);t.mergeEvaluated(_),t.ok(v)}}};function kb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,nt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}dn.getValidate=kb;function Ma(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?to.default.this:nt.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,nt._)`await ${(0,Sb.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,nt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,Sb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,nt._)`${m}.errors`;o.assign(to.default.vErrors,(0,nt._)`${to.default.vErrors} === null ? ${g} : ${to.default.vErrors}.concat(${g})`),o.assign(to.default.errors,(0,nt._)`${to.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let v=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(s.props=Oa.mergeEvaluated.props(o,v.props,s.props));else{let _=o.var("props",(0,nt._)`${m}.evaluated.props`);s.props=Oa.mergeEvaluated.props(o,_,s.props,nt.Name)}if(s.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(s.items=Oa.mergeEvaluated.items(o,v.items,s.items));else{let _=o.var("items",(0,nt._)`${m}.evaluated.items`);s.items=Oa.mergeEvaluated.items(o,_,s.items,nt.Name)}}}dn.callRef=Ma;dn.default=oD});var Tb=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var sD=xb(),iD=Pb(),aD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sD.default,iD.default];Ad.default=aD});var Eb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Na=W(),$r=Na.operators,ja={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}},cD={message:({keyword:t,schemaCode:e})=>(0,Na.str)`must be ${ja[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Na._)`{comparison: ${ja[t].okStr}, limit: ${e}}`},uD={keyword:Object.keys(ja),type:"number",schemaType:"number",$data:!0,error:cD,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Na._)`${r} ${ja[e].fail} ${n} || isNaN(${r})`)}};Cd.default=uD});var Rb=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var As=W(),lD={message:({schemaCode:t})=>(0,As.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,As._)`{multipleOf: ${t}}`},dD={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lD,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,As._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,As._)`${i} !== parseInt(${i})`;t.fail$data((0,As._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Dd.default=dD});var Ab=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});function Ib(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}zd.default=Ib;Ib.code='require("ajv/dist/runtime/ucs2length").default'});var Cb=E(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var pn=W(),pD=ie(),fD=Ab(),mD={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,pn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,pn._)`{limit: ${t}}`},hD={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:mD,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?pn.operators.GT:pn.operators.LT,i=o.opts.unicode===!1?(0,pn._)`${r}.length`:(0,pn._)`${(0,pD.useFunc)(t.gen,fD.default)}(${r})`;t.fail$data((0,pn._)`${i} ${s} ${n}`)}};Od.default=hD});var Db=E(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var gD=yt(),La=W(),yD={message:({schemaCode:t})=>(0,La.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,La._)`{pattern: ${t}}`},vD={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yD,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,La._)`(new RegExp(${o}, ${i}))`:(0,gD.usePattern)(t,n);t.fail$data((0,La._)`!${a}.test(${e})`)}};Md.default=vD});var zb=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Cs=W(),_D={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Cs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Cs._)`{limit: ${t}}`},bD={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_D,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Cs.operators.GT:Cs.operators.LT;t.fail$data((0,Cs._)`Object.keys(${r}).length ${o} ${n}`)}};Nd.default=bD});var Ob=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var Ds=yt(),zs=W(),wD=ie(),xD={message:({params:{missingProperty:t}})=>(0,zs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,zs._)`{missingProperty: ${t}}`},SD={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xD,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 v=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${v}" (strictRequired)`;(0,wD.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(zs.nil,d);else for(let f of r)(0,Ds.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,Ds.checkMissingProp)(t,r,f)),(0,Ds.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ds.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ds.propertyInData)(e,o,f,a.ownProperties)),e.if((0,zs.not)(m),()=>{t.error(),e.break()})},zs.nil)}}};jd.default=SD});var Mb=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Os=W(),$D={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Os.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Os._)`{limit: ${t}}`},kD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$D,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Os.operators.GT:Os.operators.LT;t.fail$data((0,Os._)`${r}.length ${o} ${n}`)}};Ld.default=kD});var Fa=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Nb=ld();Nb.code='require("ajv/dist/runtime/equal").default';Fd.default=Nb});var jb=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Zd=ws(),Oe=W(),PD=ie(),TD=Fa(),ED={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},RD={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ED,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,Zd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Oe._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Oe._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Oe._)`${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 v=e.name("item"),_=(0,Zd.checkDataTypes)(u,v,a.opts.strictNumbers,Zd.DataType.Wrong),S=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${m}--;`,()=>{e.let(v,(0,Oe._)`${r}[${m}]`),e.if(_,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${v} == "string"`,(0,Oe._)`${v} += "_"`),e.if((0,Oe._)`typeof ${S}[${v}] == "number"`,()=>{e.assign(g,(0,Oe._)`${S}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${S}[${v}] = ${m}`)})}function f(m,g){let v=(0,PD.useFunc)(e,TD.default),_=e.name("outer");e.label(_).for((0,Oe._)`;${m}--;`,()=>e.for((0,Oe._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Oe._)`${v}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Ud.default=RD});var Lb=E(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var qd=W(),ID=ie(),AD=Fa(),CD={message:"must be equal to constant",params:({schemaCode:t})=>(0,qd._)`{allowedValue: ${t}}`},DD={keyword:"const",$data:!0,error:CD,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,qd._)`!${(0,ID.useFunc)(e,AD.default)}(${r}, ${o})`):t.fail((0,qd._)`${s} !== ${r}`)}};Vd.default=DD});var Fb=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var Ms=W(),zD=ie(),OD=Fa(),MD={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ms._)`{allowedValues: ${t}}`},ND={keyword:"enum",schemaType:"array",$data:!0,error:MD,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,zD.useFunc)(e,OD.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,Ms.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,Ms._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Ms._)`${u()}(${r}, ${f}[${m}])`:(0,Ms._)`${r} === ${g}`}}};Bd.default=ND});var Zb=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var jD=Eb(),LD=Rb(),FD=Cb(),ZD=Db(),UD=zb(),qD=Ob(),VD=Mb(),BD=jb(),WD=Lb(),HD=Fb(),KD=[jD.default,LD.default,FD.default,ZD.default,UD.default,qD.default,VD.default,BD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WD.default,HD.default];Wd.default=KD});var Kd=E(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.validateAdditionalItems=void 0;var fn=W(),Hd=ie(),JD={message:({params:{len:t}})=>(0,fn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,fn._)`{limit: ${t}}`},GD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Hd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ub(t,n)}};function Ub(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,fn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,fn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Hd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,fn._)`${a} <= ${e.length}`);r.if((0,fn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Hd.Type.Num},u),i.allErrors||r.if((0,fn.not)(u),()=>r.break())})}}Ns.validateAdditionalItems=Ub;Ns.default=GD});var Jd=E(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.validateTuple=void 0;var qb=W(),Za=ie(),YD=yt(),XD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Vb(t,"additionalItems",e);r.items=!0,!(0,Za.alwaysValidSchema)(r,e)&&t.ok((0,YD.validateArray)(t))}};function Vb(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=Za.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,qb._)`${s}.length`);r.forEach((d,p)=>{(0,Za.alwaysValidSchema)(a,d)||(n.if((0,qb._)`${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 v=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Za.checkStrictMode)(a,v,p.strictTuples)}}}js.validateTuple=Vb;js.default=XD});var Bb=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var QD=Jd(),ez={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,QD.validateTuple)(t,"items")};Gd.default=ez});var Hb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var Wb=W(),tz=ie(),rz=yt(),nz=Kd(),oz={message:({params:{len:t}})=>(0,Wb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wb._)`{limit: ${t}}`},sz={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:oz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,tz.alwaysValidSchema)(n,e)&&(o?(0,nz.validateAdditionalItems)(t,o):t.ok((0,rz.validateArray)(t)))}};Yd.default=sz});var Kb=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var _t=W(),Ua=ie(),iz={message:({params:{min:t,max:e}})=>e===void 0?(0,_t.str)`must contain at least ${t} valid item(s)`:(0,_t.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_t._)`{minContains: ${t}}`:(0,_t._)`{minContains: ${t}, maxContains: ${e}}`},az={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iz,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,_t._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ua.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ua.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ua.alwaysValidSchema)(s,r)){let g=(0,_t._)`${l} >= ${i}`;a!==void 0&&(g=(0,_t._)`${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,_t._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),v=e.let("count",0);f(g,()=>e.if(g,()=>m(v)))}function f(g,v){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Ua.Type.Num,compositeRule:!0},g),v()})}function m(g){e.code((0,_t._)`${g}++`),a===void 0?e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,_t._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Xd.default=az});var Yb=E(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateSchemaDeps=Ft.validatePropertyDeps=Ft.error=void 0;var Qd=W(),cz=ie(),Ls=yt();Ft.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Qd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Qd._)`{property: ${t},
9
10
  missingProperty: ${n},
10
11
  depsCount: ${e},
11
- deps: ${r}}`};var FD={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=ZD(t);Mb(t,e),Nb(t,r)}};function ZD({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 Mb(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,Ds.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,Ds.checkReportMissingProp)(t,u)}):(r.if((0,Zd._)`${c} && (${(0,Ds.checkMissingProp)(t,a,s)})`),(0,Ds.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=Mb;function Nb(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,LD.alwaysValidSchema)(s,e[a])||(r.if((0,Ds.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=Nb;Ot.default=FD});var Fb=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Lb=H(),UD=oe(),qD={message:"property name must be valid",params:({params:t})=>(0,Lb._)`{propertyName: ${t.propertyName}}`},VD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:qD,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,UD.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,Lb.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ud.default=VD});var Vd=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var Fa=dt(),xt=H(),BD=Jt(),Za=oe(),WD={message:"must NOT have additional properties",params:({params:t})=>(0,xt._)`{additionalProperty: ${t.additionalProperty}}`},HD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:WD,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,Za.alwaysValidSchema)(i,r))return;let u=(0,Fa.allSchemaProperties)(n.properties),l=(0,Fa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,xt._)`${s} === ${BD.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 x=(0,Za.schemaRefOrVal)(i,n.properties,"properties");_=(0,Fa.isOwnProperty)(e,x,y)}else u.length?_=(0,xt.or)(...u.map(x=>(0,xt._)`${y} === ${x}`)):_=xt.nil;return l.length&&(_=(0,xt.or)(_,...l.map(x=>(0,xt._)`${(0,Fa.usePattern)(t,x)}.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,Za.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,_,x){let v={keyword:"additionalProperties",dataProp:y,dataPropType:Za.Type.Str};x===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(v,_)}}};qd.default=HD});var qb=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var KD=_s(),Zb=dt(),Bd=oe(),Ub=Vd(),GD={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&&Ub.default.code(new KD.KeywordCxt(s,Ub.default,"additionalProperties"));let i=(0,Zb.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,Zb.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=GD});var Hb=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Vb=dt(),Ua=H(),Bb=oe(),Wb=oe(),JD={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,Vb.allSchemaProperties)(r),c=a.filter(g=>(0,Bb.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 Ua.Name)&&(s.props=(0,Wb.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,Bb.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,Ua._)`${(0,Vb.usePattern)(t,g)}.test(${y})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Wb.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ua._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Ua.not)(l),()=>e.break())})})}}};Hd.default=JD});var Kb=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var YD=oe(),QD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,YD.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=QD});var Gb=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var XD=dt(),ez={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:XD.validateUnion,error:{message:"must match a schema in anyOf"}};Gd.default=ez});var Jb=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var qa=H(),tz=oe(),rz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,qa._)`{passingSchemas: ${t.passing}}`},nz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:rz,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,tz.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,qa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,qa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,qa.Name)})})}}};Jd.default=nz});var Yb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var oz=oe(),sz={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,oz.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Yd.default=sz});var ew=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var Va=H(),Xb=oe(),iz={message:({params:t})=>(0,Va.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Va._)`{failingKeyword: ${t.ifClause}}`},az={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:iz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Xb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Qb(n,"then"),s=Qb(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,Va.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,Va._)`${l}`):t.setParams({ifClause:l})}}}};function Qb(t,e){let r=t.schema[e];return r!==void 0&&!(0,Xb.alwaysValidSchema)(t,r)}Qd.default=az});var tw=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var cz=oe(),uz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,cz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Xd.default=uz});var rw=E(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var lz=Md(),dz=Cb(),pz=Nd(),fz=zb(),mz=Ob(),hz=jb(),gz=Fb(),yz=Vd(),vz=qb(),_z=Hb(),bz=Kb(),wz=Gb(),xz=Jb(),Sz=Yb(),$z=ew(),kz=tw();function Pz(t=!1){let e=[bz.default,wz.default,xz.default,Sz.default,$z.default,kz.default,gz.default,yz.default,hz.default,vz.default,_z.default];return t?e.push(dz.default,fz.default):e.push(lz.default,pz.default),e.push(mz.default),e}ep.default=Pz});var nw=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ke=H(),Tz={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},Ez={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Tz,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)(x(),v()));function x(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function v(){let P=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,S=(0,ke._)`(typeof ${_} == "function" ? ${P} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${y} === ${e} && !${S}`}}function f(){let m=d.formats[s];if(!m){x();return}if(m===!0)return;let[g,y,_]=v(m);g===e&&t.pass(P());function x(){if(c.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(S){let N=S instanceof RegExp?(0,ke.regexpCode)(S):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,L=r.scopeValue("formats",{key:s,ref:S,code:N});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,ke._)`${L}.validate`]:["string",S,L]}function P(){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=Ez});var ow=E(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var Rz=nw(),Iz=[Rz.default];rp.default=Iz});var sw=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 aw=E(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var Az=mb(),Cz=Eb(),Dz=rw(),zz=ow(),iw=sw(),Oz=[Az.default,Cz.default,(0,Dz.default)(),zz.default,iw.metadataVocabulary,iw.contentVocabulary];np.default=Oz});var uw=E(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.DiscrError=void 0;var cw;(function(t){t.Tag="tag",t.Mapping="mapping"})(cw||(Ba.DiscrError=cw={}))});var dw=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var Qn=H(),op=uw(),lw=Pa(),Mz=bs(),Nz=oe(),jz={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}}`},Lz={keyword:"discriminator",type:"object",schemaType:"object",error:jz,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 P=0;P<i.length;P++){let S=i[P];if(S?.$ref&&!(0,Nz.schemaHasRulesButRef)(S,s.self.RULES)){let L=S.$ref;if(S=lw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,L),S instanceof lw.SchemaEnv&&(S=S.schema),S===void 0)throw new Mz.default(s.opts.uriResolver,s.baseId,L)}let N=(f=S?.properties)===null||f===void 0?void 0:f[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||_(S)),x(N,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:P}){return Array.isArray(P)&&P.includes(a)}function x(P,S){if(P.const)v(P.const,S);else if(P.enum)for(let N of P.enum)v(N,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(P,S){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=S}}}};sp.default=Lz});var pw=E((IB,Fz)=>{Fz.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 Zz=cb(),Uz=aw(),qz=dw(),fw=pw(),Vz=["/properties"],Wa="http://json-schema.org/draft-07/schema",Xn=class extends Zz.default{_addVocabularies(){super._addVocabularies(),Uz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(qz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(fw,Vz):fw;this.addMetaSchema(e,Wa,!1),this.refs["http://json-schema.org/schema"]=Wa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wa)?Wa:void 0)}};ye.Ajv=Xn;ip.exports=ye=Xn;ip.exports.Ajv=Xn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Xn;var Bz=_s();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return Bz.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 Wz=$a();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return Wz.default}});var Hz=bs();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return Hz.default}})});var ww=E(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.formatNames=Nt.fastFormats=Nt.fullFormats=void 0;function Mt(t,e){return{validate:t,compare:e}}Nt.fullFormats={date:Mt(yw,dp),time:Mt(up(!0),pp),"date-time":Mt(mw(!0),_w),"iso-time":Mt(up(),vw),"iso-date-time":Mt(mw(),bw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Xz,"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:iO,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:eO,int32:{type:"number",validate:nO},int64:{type:"number",validate:oO},float:{type:"number",validate:gw},double:{type:"number",validate:gw},password:!0,binary:!0};Nt.fastFormats={...Nt.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,_w),"iso-time":Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vw),"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,bw),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};Nt.formatNames=Object.keys(Nt.fullFormats);function Kz(t){return t%4===0&&(t%100!==0||t%400===0)}var Gz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Jz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function yw(t){let e=Gz.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&&Kz(r)?29:Jz[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 vw(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 mw(t){let e=up(t);return function(n){let o=n.split(lp);return o.length===2&&yw(o[0])&&e(o[1])}}function _w(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function bw(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 Yz=/\/|:/,Qz=/^(?:[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 Xz(t){return Yz.test(t)&&Qz.test(t)}var hw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function eO(t){return hw.lastIndex=0,hw.test(t)}var tO=-(2**31),rO=2**31-1;function nO(t){return Number.isInteger(t)&&t<=rO&&t>=tO}function oO(t){return Number.isInteger(t)}function gw(){return!0}var sO=/[^\\]\\Z/;function iO(t){if(sO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var xw=E(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.formatLimitDefinition=void 0;var aO=ap(),St=H(),br=St.operators,Ha={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}},cO={message:({keyword:t,schemaCode:e})=>(0,St.str)`should be ${Ha[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,St._)`{comparison: ${Ha[t].okStr}, limit: ${e}}`};to.formatLimitDefinition={keyword:Object.keys(Ha),type:"string",schemaType:"string",$data:!0,error:cO,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 aO.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}) ${Ha[o].fail} 0`}},dependencies:["format"]};var uO=t=>(t.addKeyword(to.formatLimitDefinition),t);to.default=uO});var Pw=E((zs,kw)=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var ro=ww(),lO=xw(),fp=H(),Sw=new fp.Name("fullFormats"),dO=new fp.Name("fastFormats"),mp=(t,e={keywords:!0})=>{if(Array.isArray(e))return $w(t,e,ro.fullFormats,Sw),t;let[r,n]=e.mode==="fast"?[ro.fastFormats,dO]:[ro.fullFormats,Sw],o=e.formats||ro.formatNames;return $w(t,o,r,n),e.keywords&&(0,lO.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 $w(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])}kw.exports=zs=mp;Object.defineProperty(zs,"__esModule",{value:!0});zs.default=mp});import{readFileSync as mj}from"fs";import{join as Gp}from"path";import{fileURLToPath as hj}from"url";var cn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Us=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 gf={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"}},FS={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 Ws(t,e,r,n=t){let o=gf[n]??gf[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=FS[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 Hs={low:0,medium:.5,high:.7},ZS={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 yf(t,e){return e?.[t]??ZS[t]??"low"}function Ks(t,e,r=Hs){return t>=r[e]}var Gs=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 Us(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 Ws(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??yf(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 Ks(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:()=>f$,DIRTY:()=>$r,EMPTY_PATH:()=>BS,INVALID:()=>O,NEVER:()=>Y$,OK:()=>Oe,ParseStatus:()=>Te,Schema:()=>B,ZodAny:()=>or,ZodArray:()=>qt,ZodBigInt:()=>Pr,ZodBoolean:()=>Tr,ZodBranded:()=>yo,ZodCatch:()=>jr,ZodDate:()=>Er,ZodDefault:()=>Nr,ZodDiscriminatedUnion:()=>Qs,ZodEffects:()=>it,ZodEnum:()=>Or,ZodError:()=>Ke,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>ei,ZodIntersection:()=>Cr,ZodIssueCode:()=>$,ZodLazy:()=>Dr,ZodLiteral:()=>zr,ZodMap:()=>bn,ZodNaN:()=>xn,ZodNativeEnum:()=>Mr,ZodNever:()=>mt,ZodNull:()=>Ir,ZodNullable:()=>Et,ZodNumber:()=>kr,ZodObject:()=>Ge,ZodOptional:()=>ot,ZodParsedType:()=>R,ZodPipeline:()=>vo,ZodPromise:()=>sr,ZodReadonly:()=>Lr,ZodRecord:()=>Xs,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:()=>x$,array:()=>P$,bigint:()=>y$,boolean:()=>Ef,coerce:()=>J$,custom:()=>kf,date:()=>v$,datetimeRegex:()=>Sf,defaultErrorMap:()=>Ft,discriminatedUnion:()=>I$,effect:()=>U$,enum:()=>L$,function:()=>M$,getErrorMap:()=>hn,getParsedType:()=>Pt,instanceof:()=>h$,intersection:()=>A$,isAborted:()=>Js,isAsync:()=>gn,isDirty:()=>Ys,isValid:()=>rr,late:()=>m$,lazy:()=>N$,literal:()=>j$,makeIssue:()=>go,map:()=>z$,nan:()=>g$,nativeEnum:()=>F$,never:()=>$$,null:()=>w$,nullable:()=>V$,number:()=>Tf,object:()=>T$,objectUtil:()=>Nc,oboolean:()=>G$,onumber:()=>K$,optional:()=>q$,ostring:()=>H$,pipeline:()=>W$,preprocess:()=>B$,promise:()=>Z$,quotelessJson:()=>US,record:()=>D$,set:()=>O$,setErrorMap:()=>VS,strictObject:()=>E$,string:()=>Pf,symbol:()=>_$,transformer:()=>U$,tuple:()=>C$,undefined:()=>b$,union:()=>R$,unknown:()=>S$,util:()=>J,void:()=>k$});var J;(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})(J||(J={}));var Nc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Nc||(Nc={}));var R=J.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 $=J.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"]),US=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,J.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 qS=(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,J.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${J.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}"`:J.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,J.assertNever(t)}return{message:r}},Ft=qS;var vf=Ft;function VS(t){vf=t}function hn(){return vf}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}},BS=[];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 O;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 O;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}}},O=Object.freeze({status:"aborted"}),$r=t=>({status:"dirty",value:t}),Oe=t=>({status:"valid",value:t}),Js=t=>t.status==="aborted",Ys=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}},_f=(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 _f(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 _f(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:k.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:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Nr({...U(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new yo({typeName:k.ZodBranded,type:this,...U(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new jr({...U(this._def),innerType:this,catchValue:r,typeName:k.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}},WS=/^c[^\s-]{8,}$/i,HS=/^[0-9a-z]+$/,KS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GS=/^[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,JS=/^[a-z0-9_-]{21}$/i,YS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QS=/^[-+]?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)?)??$/,XS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,e$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",jc,t$=/^(?:(?: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])$/,r$=/^(?:(?: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])$/,n$=/^(([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]))$/,o$=/^(([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])$/,s$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,i$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wf="((\\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])))",a$=new RegExp(`^${wf}$`);function xf(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 c$(t){return new RegExp(`^${xf(t)}$`)}function Sf(t){let e=`${wf}T${xf(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 u$(t,e){return!!((e==="v4"||!e)&&t$.test(t)||(e==="v6"||!e)&&n$.test(t))}function l$(t,e){if(!YS.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 d$(t,e){return!!((e==="v4"||!e)&&r$.test(t)||(e==="v6"||!e)&&o$.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}),O}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")XS.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")jc||(jc=new RegExp(e$,"u")),jc.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")GS.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")JS.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")WS.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")HS.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")KS.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"?Sf(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?a$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?c$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?QS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?u$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?l$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?d$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?s$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?i$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):J.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:k.ZodString,coerce:t?.coerce??!1,...U(t)});function p$(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}),O}let n,o=new Te;for(let s of this._def.checks)s.kind==="int"?J.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"?p$(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()):J.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"&&J.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:k.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()):J.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}),O}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:k.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}),O}return Oe(e.data)}};Tr.create=t=>new Tr({typeName:k.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}),O}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_date}),O}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()):J.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:k.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}),O}return Oe(e.data)}};vn.create=t=>new vn({typeName:k.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}),O}return Oe(e.data)}};Rr.create=t=>new Rr({typeName:k.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}),O}return Oe(e.data)}};Ir.create=t=>new Ir({typeName:k.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:k.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:k.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}),O}};mt.create=t=>new mt({typeName:k.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}),O}return Oe(e.data)}};_n.create=t=>new _n({typeName:k.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}),O;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:k.ZodArray,...U(e)});function yn(t){if(t instanceof Ge){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ot.create(yn(n))}return new Ge({...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 Ge=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=J.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}),O}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:k.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 J.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 J.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 J.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 J.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 $f(J.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:k.ZodObject,...U(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:k.ZodObject,...U(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:k.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}),O}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}),O}}get options(){return this._def.options}};Ar.create=(t,e)=>new Ar({options:t,typeName:k.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?J.objectValues(t.enum):t instanceof Nr?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 jr?Zt(t._def.innerType):[],Qs=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}),O;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]}),O)}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:k.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=J.objectKeys(e),s=J.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 O;let a=Lc(s.value,i.value);return a.valid?((Ys(s)||Ys(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:$.invalid_intersection_types}),O)};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:k.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}),O;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"}),O;!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:k.ZodTuple,rest:null,...U(e)})};var Xs=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}),O;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:k.ZodRecord,...U(n)}):new t({keyType:nr.create(),valueType:e,typeName:k.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}),O;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 O;(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 O;(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:k.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}),O;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 O;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:k.ZodSet,...U(e)});var ei=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}),O;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:k.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:k.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}),O}return{status:"valid",value:e.data}}get value(){return this._def.value}};zr.create=(t,e)=>new zr({value:t,typeName:k.ZodLiteral,...U(e)});function $f(t,e){return new Or({values:t,typeName:k.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:J.joinValues(n),received:r.parsedType,code:$.invalid_type}),O}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}),O}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=$f;var Mr=class extends B{_parse(e){let r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=J.objectValues(r);return T(n,{expected:J.joinValues(o),received:n.parsedType,code:$.invalid_type}),O}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=J.objectValues(r);return T(n,{received:n.data,code:$.invalid_enum_value,options:o}),O}return Oe(e.data)}get enum(){return this._def.values}};Mr.create=(t,e)=>new Mr({values:t,typeName:k.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}),O;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:k.ZodPromise,...U(e)});var it=class extends B{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.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 O;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?O:c.status==="dirty"?$r(c.value):r.value==="dirty"?$r(c.value):c});{if(r.value==="aborted")return O;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?O: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"?O:(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"?O:(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 O;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})):O);J.assertNever(o)}};it.create=(t,e,r)=>new it({schema:t,typeName:k.ZodEffects,effect:e,...U(r)});it.createWithPreprocess=(t,e,r)=>new it({schema:e,effect:{type:"preprocess",transform:t},typeName:k.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:k.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:k.ZodNullable,...U(e)});var Nr=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}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...U(e)});var jr=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}};jr.create=(t,e)=>new jr({innerType:t,typeName:k.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}),O}return{status:"valid",value:e.data}}};xn.create=t=>new xn({typeName:k.ZodNaN,...U(t)});var f$=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"?O: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"?O: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:k.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:k.ZodReadonly,...U(e)});function bf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function kf(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=bf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=bf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):or.create()}var m$={object:Ge.lazycreate},k;(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"})(k||(k={}));var h$=(t,e={message:`Input not instance of ${t.name}`})=>kf(r=>r instanceof t,e),Pf=nr.create,Tf=kr.create,g$=xn.create,y$=Pr.create,Ef=Tr.create,v$=Er.create,_$=vn.create,b$=Rr.create,w$=Ir.create,x$=or.create,S$=Ut.create,$$=mt.create,k$=_n.create,P$=qt.create,T$=Ge.create,E$=Ge.strictCreate,R$=Ar.create,I$=Qs.create,A$=Cr.create,C$=Tt.create,D$=Xs.create,z$=bn.create,O$=wn.create,M$=ei.create,N$=Dr.create,j$=zr.create,L$=Or.create,F$=Mr.create,Z$=sr.create,U$=it.create,q$=ot.create,V$=Et.create,B$=it.createWithPreprocess,W$=vo.create,H$=()=>Pf().optional(),K$=()=>Tf().optional(),G$=()=>Ef().optional(),J$={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 Y$=O;jt();var Q$=h.enum(["read-only","workspace-write","full-auto"]),X$=Q$.default("read-only"),ek=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:X$,config:h.record(h.unknown()).default({})}),tk=h.enum(["default-only","auto"]).default("default-only"),rk=h.object({selectionPolicy:tk,locale:h.string().optional(),providers:h.array(ek).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 ti(t){return t==="workspace-write"||t==="full-auto"}function nk(t){return Bs.includes(t)}function ok(t){if(t!==void 0)return nk(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${xr}`),xr)}function Rf(t){let e=rk.parse(t);return{selectionPolicy:e.selectionPolicy,locale:ok(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{mkdirSync as sk}from"fs";import{homedir as ik}from"os";import{dirname as ak,join as If}from"path";var Af="providers.config.json";function _o(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=process.env.CLAUDE_PLUGIN_ROOT;return e&&e.length>0?If(e,Af):If(ik(),".agestra",Af)}function Cf(t){sk(ak(t),{recursive:!0})}oi();xo();ho();mn();jt();import{mkdirSync as qf,readFileSync as Rt,readdirSync as Wc,existsSync as ir,unlinkSync as Ak,rmdirSync as Ck}from"fs";import{join as ce}from"path";import{spawn as Vf}from"child_process";import{randomUUID as Dk}from"crypto";function Zr(t,e){let r=ce(t,"status.json"),n=JSON.parse(Rt(r,"utf-8"));Ue(r,{...n,...e})}var ai=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;constructor(e=process.cwd(),r){this.jobsDir=ce(e,Xp),qf(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7}submit(e){let r=`${e.provider}-${Date.now()}-${Dk().slice(0,6)}`,n=ce(this.jobsDir,r);qf(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(!si(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(!si(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(!si(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)Ak(ce(f,g));Ck(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=Vf(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(()=>(Uf(),Zf)).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=Vf(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{}})}};oi();jt();import{mkdirSync as zk,readdirSync as Bf,readFileSync as Ok,unlinkSync as Mk}from"fs";import{join as So}from"path";function Wf(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 Nk(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function jk(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var ci=class{tracesDir;writer;constructor(e,r){this.tracesDir=So(e,ef),zk(this.tracesDir,{recursive:!0}),this.writer=new ri(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Wf(new Date(r.timestamp)),o=So(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=Ok(i,"utf-8").split(`
13
- `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);jk(u)?o.push(u):Nk(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=Wf(o),a=So(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=Bf(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&&(Mk(So(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=Bf(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=>So(this.tracesDir,n))}};var Lk=/[;|&`$(){}!><\n\r\\]/,ui=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),Fk=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 Hf(t){if(Lk.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(!ui.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...ui].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(Fk.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}jt();var Kf=[{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"}],Gf=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function Jf(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 Kf){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!Gf.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 Kf){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>Gf.some(a=>a.test(i))?i:mf)}e[r]=n}return e.join(`
17
- `)}jt();import{execFileSync as Zk}from"child_process";import{existsSync as Yf,rmSync as Uk,mkdirSync as qk}from"fs";import{join as Qf}from"path";var li=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=Qf(e,tf)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=Qf(this.worktreeBaseDir,r);qk(this.worktreeBaseDir,{recursive:!0}),Yf(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&&(Yf(e)&&Uk(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return Zk("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var Vk=["npm","node","git","tsc"];function Xf(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:[...Vk]},timeout_minutes:t.timeoutMinutes??10}}function em(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 di=10,Kc=2e4;import{spawn as Jk}from"child_process";import{writeFileSync as Jc,mkdirSync as Yk,readFileSync as om,existsSync as sm}from"fs";import{isAbsolute as im,join as $o,resolve as am}from"path";import{randomBytes as Qk}from"crypto";import{execFileSync as Xk}from"child_process";jt();mn();ho();xo();xo();import{readFileSync as tm}from"fs";var Gc=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 Bk(t,e,r){let n=rm(t,e,r);return{command:"codex",args:["exec","--skip-git-repo-check","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function Wk(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",rm(t,e,r)]}}function rm(t,e,r){let n=tm(t,"utf-8"),o=Hk(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 nm(){let t=new Gc;return t.register("codex",Bk),t.register("gemini",Wk),t}function Hk(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,di))try{let s=tm(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>di&&(n.push(`...[${r.length-di} additional read-only files omitted]`),n.push("")),n.join(`
21
- `)}var ko=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=$o(e,af),this.worktreeManager=new li(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??nm()}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=Jf(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=Qk(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=$o(this.workersBaseDir,c);Yk(u,{recursive:!0});let l=Xf({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=em(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=$o(u,"task-manifest.json");Jc(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=$o(u,"stdout.log"),g=$o(u,"stderr.log"),y=f?.path??r,_=this.cliBuilderRegistry.build(e.provider,p,y,n),x=Lt(_.command,_.args),v=Jk(x.command,x.args,{cwd:y,env:t.buildWorkerEnv(),detached:!0,stdio:[_.stdin?"pipe":"ignore","pipe","pipe"]}),P=[],S=[];v.stdout?.on("data",Z=>P.push(Z)),v.stderr?.on("data",Z=>S.push(Z)),_.stdin!==void 0&&v.stdin?.end(_.stdin),v.unref();let N={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},L={info:N,process:v,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,L),e.timeoutMinutes){let Z=e.timeoutMinutes*6e4;setTimeout(()=>{if(L.info.state===$e.RUNNING){L.info.state=$e.TIMEOUT,L.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let Y=L.process?.pid;Y&&pn(Y)}},Z).unref()}return v.on("close",Z=>{L.info.exitCode=Z;try{Jc(m,Buffer.concat(P).toString("utf-8")),Jc(g,Buffer.concat(S).toString("utf-8"))}catch{}L.info.state===$e.CANCELLING?L.info.state=$e.CANCELLED:Z===0?L.info.state=$e.COLLECTING:(L.info.state=$e.FAILED,L.info.error=`Process exited with code ${Z}`)}),N}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{sm(r.outputPath)&&(o=om(r.outputPath,"utf-8").split(`
12
+ deps: ${r}}`};var uz={keyword:"dependencies",type:"object",schemaType:"object",error:Ft.error,code(t){let[e,r]=lz(t);Jb(t,e),Gb(t,r)}};function lz({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 Jb(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,Ls.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,Ls.checkReportMissingProp)(t,u)}):(r.if((0,Qd._)`${c} && (${(0,Ls.checkMissingProp)(t,a,s)})`),(0,Ls.reportMissingProp)(t,s),r.else())}}Ft.validatePropertyDeps=Jb;function Gb(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,cz.alwaysValidSchema)(s,e[a])||(r.if((0,Ls.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))}Ft.validateSchemaDeps=Gb;Ft.default=uz});var Qb=E(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var Xb=W(),dz=ie(),pz={message:"property name must be valid",params:({params:t})=>(0,Xb._)`{propertyName: ${t.propertyName}}`},fz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:pz,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,dz.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,Xb.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};ep.default=fz});var rp=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var qa=yt(),Tt=W(),mz=rr(),Va=ie(),hz={message:"must NOT have additional properties",params:({params:t})=>(0,Tt._)`{additionalProperty: ${t.additionalProperty}}`},gz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hz,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,qa.allSchemaProperties)(n.properties),l=(0,qa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Tt._)`${s} === ${mz.default.errors}`);function d(){e.forIn("key",o,v=>{!u.length&&!l.length?m(v):e.if(p(v),()=>m(v))})}function p(v){let _;if(u.length>8){let S=(0,Va.schemaRefOrVal)(i,n.properties,"properties");_=(0,qa.isOwnProperty)(e,S,v)}else u.length?_=(0,Tt.or)(...u.map(S=>(0,Tt._)`${v} === ${S}`)):_=Tt.nil;return l.length&&(_=(0,Tt.or)(_,...l.map(S=>(0,Tt._)`${(0,qa.usePattern)(t,S)}.test(${v})`))),(0,Tt.not)(_)}function f(v){e.code((0,Tt._)`delete ${o}[${v}]`)}function m(v){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Va.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(v,_,!1),e.if((0,Tt.not)(_),()=>{t.reset(),f(v)})):(g(v,_),a||e.if((0,Tt.not)(_),()=>e.break()))}}function g(v,_,S){let y={keyword:"additionalProperties",dataProp:v,dataPropType:Va.Type.Str};S===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};tp.default=gz});var rw=E(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var yz=ks(),ew=yt(),np=ie(),tw=rp(),vz={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&&tw.default.code(new yz.KeywordCxt(s,tw.default,"additionalProperties"));let i=(0,ew.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=np.mergeEvaluated.props(e,(0,np.toHash)(i),s.props));let a=i.filter(d=>!(0,np.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,ew.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)}}};op.default=vz});var iw=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var nw=yt(),Ba=W(),ow=ie(),sw=ie(),_z={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,nw.allSchemaProperties)(r),c=a.filter(g=>(0,ow.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 Ba.Name)&&(s.props=(0,sw.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 v in u)new RegExp(g).test(v)&&(0,ow.checkStrictMode)(s,`property ${v} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,v=>{e.if((0,Ba._)`${(0,nw.usePattern)(t,g)}.test(${v})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:v,dataPropType:sw.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ba._)`${d}[${v}]`,!0):!_&&!s.allErrors&&e.if((0,Ba.not)(l),()=>e.break())})})}}};sp.default=_z});var aw=E(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var bz=ie(),wz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,bz.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"}};ip.default=wz});var cw=E(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var xz=yt(),Sz={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xz.validateUnion,error:{message:"must match a schema in anyOf"}};ap.default=Sz});var uw=E(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var Wa=W(),$z=ie(),kz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Wa._)`{passingSchemas: ${t.passing}}`},Pz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kz,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,$z.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Wa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Wa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Wa.Name)})})}}};cp.default=Pz});var lw=E(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});var Tz=ie(),Ez={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,Tz.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};up.default=Ez});var fw=E(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});var Ha=W(),pw=ie(),Rz={message:({params:t})=>(0,Ha.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ha._)`{failingKeyword: ${t.ifClause}}`},Iz={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Rz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,pw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=dw(n,"then"),s=dw(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,Ha.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,Ha._)`${l}`):t.setParams({ifClause:l})}}}};function dw(t,e){let r=t.schema[e];return r!==void 0&&!(0,pw.alwaysValidSchema)(t,r)}lp.default=Iz});var mw=E(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});var Az=ie(),Cz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Az.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};dp.default=Cz});var hw=E(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var Dz=Kd(),zz=Bb(),Oz=Jd(),Mz=Hb(),Nz=Kb(),jz=Yb(),Lz=Qb(),Fz=rp(),Zz=rw(),Uz=iw(),qz=aw(),Vz=cw(),Bz=uw(),Wz=lw(),Hz=fw(),Kz=mw();function Jz(t=!1){let e=[qz.default,Vz.default,Bz.default,Wz.default,Hz.default,Kz.default,Lz.default,Fz.default,jz.default,Zz.default,Uz.default];return t?e.push(zz.default,Mz.default):e.push(Dz.default,Oz.default),e.push(Nz.default),e}pp.default=Jz});var gw=E(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var ke=W(),Gz={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},Yz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Gz,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}]`),v=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(v,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(v,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(S(),y()));function S(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function y(){let x=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${v} === ${e} && !${$}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[g,v,_]=y(m);g===e&&t.pass(x());function S(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function y($){let M=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:$,code:M});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${O}.validate`]:["string",$,O]}function x(){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 v=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};fp.default=Yz});var yw=E(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var Xz=gw(),Qz=[Xz.default];mp.default=Qz});var vw=E(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.contentVocabulary=ro.metadataVocabulary=void 0;ro.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ro.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var bw=E(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var eO=Tb(),tO=Zb(),rO=hw(),nO=yw(),_w=vw(),oO=[eO.default,tO.default,(0,rO.default)(),nO.default,_w.metadataVocabulary,_w.contentVocabulary];hp.default=oO});var xw=E(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.DiscrError=void 0;var ww;(function(t){t.Tag="tag",t.Mapping="mapping"})(ww||(Ka.DiscrError=ww={}))});var $w=E(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var no=W(),gp=xw(),Sw=Ra(),sO=Ps(),iO=ie(),aO={message:({params:{discrError:t,tagName:e}})=>t===gp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,no._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},cO={keyword:"discriminator",type:"object",schemaType:"object",error:aO,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,no._)`${r}${(0,no.getProperty)(a)}`);e.if((0,no._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:gp.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,no._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:gp.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,no.Name),m}function p(){var f;let m={},g=_(o),v=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,iO.schemaHasRulesButRef)($,s.self.RULES)){let O=$.$ref;if($=Sw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),$ instanceof Sw.SchemaEnv&&($=$.schema),$===void 0)throw new sO.default(s.opts.uriResolver,s.baseId,O)}let M=(f=$?.properties)===null||f===void 0?void 0:f[a];if(typeof M!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(g||_($)),S(M,x)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function S(x,$){if(x.const)y(x.const,$);else if(x.enum)for(let M of x.enum)y(M,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,$){if(typeof x!="string"||x in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[x]=$}}}};yp.default=cO});var kw=E((c2,uO)=>{uO.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 _p=E((ye,vp)=>{"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 lO=wb(),dO=bw(),pO=$w(),Pw=kw(),fO=["/properties"],Ja="http://json-schema.org/draft-07/schema",oo=class extends lO.default{_addVocabularies(){super._addVocabularies(),dO.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(pO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Pw,fO):Pw;this.addMetaSchema(e,Ja,!1),this.refs["http://json-schema.org/schema"]=Ja}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ja)?Ja:void 0)}};ye.Ajv=oo;vp.exports=ye=oo;vp.exports.Ajv=oo;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=oo;var mO=ks();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return mO.KeywordCxt}});var so=W();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return so._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return so.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return so.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return so.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return so.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return so.CodeGen}});var hO=Ta();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return hO.default}});var gO=Ps();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return gO.default}})});var zw=E(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.formatNames=Ut.fastFormats=Ut.fullFormats=void 0;function Zt(t,e){return{validate:t,compare:e}}Ut.fullFormats={date:Zt(Iw,Sp),time:Zt(wp(!0),$p),"date-time":Zt(Tw(!0),Cw),"iso-time":Zt(wp(),Aw),"iso-date-time":Zt(Tw(),Dw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:xO,"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:RO,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:SO,int32:{type:"number",validate:PO},int64:{type:"number",validate:TO},float:{type:"number",validate:Rw},double:{type:"number",validate:Rw},password:!0,binary:!0};Ut.fastFormats={...Ut.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Sp),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,$p),"date-time":Zt(/^\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,Cw),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Aw),"iso-date-time":Zt(/^\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,Dw),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};Ut.formatNames=Object.keys(Ut.fullFormats);function yO(t){return t%4===0&&(t%100!==0||t%400===0)}var vO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_O=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Iw(t){let e=vO.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&&yO(r)?29:_O[n])}function Sp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var bp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function wp(t){return function(r){let n=bp.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 $p(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 Aw(t,e){if(!(t&&e))return;let r=bp.exec(t),n=bp.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 xp=/t|\s/i;function Tw(t){let e=wp(t);return function(n){let o=n.split(xp);return o.length===2&&Iw(o[0])&&e(o[1])}}function Cw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Dw(t,e){if(!(t&&e))return;let[r,n]=t.split(xp),[o,s]=e.split(xp),i=Sp(r,o);if(i!==void 0)return i||$p(n,s)}var bO=/\/|:/,wO=/^(?:[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 xO(t){return bO.test(t)&&wO.test(t)}var Ew=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function SO(t){return Ew.lastIndex=0,Ew.test(t)}var $O=-(2**31),kO=2**31-1;function PO(t){return Number.isInteger(t)&&t<=kO&&t>=$O}function TO(t){return Number.isInteger(t)}function Rw(){return!0}var EO=/[^\\]\\Z/;function RO(t){if(EO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ow=E(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.formatLimitDefinition=void 0;var IO=_p(),Et=W(),kr=Et.operators,Ga={formatMaximum:{okStr:"<=",ok:kr.LTE,fail:kr.GT},formatMinimum:{okStr:">=",ok:kr.GTE,fail:kr.LT},formatExclusiveMaximum:{okStr:"<",ok:kr.LT,fail:kr.GTE},formatExclusiveMinimum:{okStr:">",ok:kr.GT,fail:kr.LTE}},AO={message:({keyword:t,schemaCode:e})=>(0,Et.str)`should be ${Ga[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Et._)`{comparison: ${Ga[t].okStr}, limit: ${e}}`};io.formatLimitDefinition={keyword:Object.keys(Ga),type:"string",schemaType:"string",$data:!0,error:AO,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 IO.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,Et._)`${p}[${c.schemaCode}]`);t.fail$data((0,Et.or)((0,Et._)`typeof ${f} != "object"`,(0,Et._)`${f} instanceof RegExp`,(0,Et._)`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,Et._)`${i.code.formats}${(0,Et.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,Et._)`${p}.compare(${r}, ${n}) ${Ga[o].fail} 0`}},dependencies:["format"]};var CO=t=>(t.addKeyword(io.formatLimitDefinition),t);io.default=CO});var Lw=E((Fs,jw)=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var ao=zw(),DO=Ow(),kp=W(),Mw=new kp.Name("fullFormats"),zO=new kp.Name("fastFormats"),Pp=(t,e={keywords:!0})=>{if(Array.isArray(e))return Nw(t,e,ao.fullFormats,Mw),t;let[r,n]=e.mode==="fast"?[ao.fastFormats,zO]:[ao.fullFormats,Mw],o=e.formats||ao.formatNames;return Nw(t,o,r,n),e.keywords&&(0,DO.default)(t),t};Pp.get=(t,e="full")=>{let n=(e==="fast"?ao.fastFormats:ao.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Nw(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,kp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}jw.exports=Fs=Pp;Object.defineProperty(Fs,"__esModule",{value:!0});Fs.default=Pp});import{readFileSync as Fj}from"fs";import{join as cf}from"path";import{fileURLToPath as Zj}from"url";var mn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Ws=class extends mn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},de=class extends mn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var hn=class extends mn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},Be=class extends mn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var Ef={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"}},QS={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 Zc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Gs(t,e,r,n=t){let o=Ef[n]??Ef[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Zc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function ir(t,e){let r=QS[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 Ys={low:0,medium:.5,high:.7},e$={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 Rf(t,e){return e?.[t]??e$[t]??"low"}function Xs(t,e,r=Ys){return t>=r[e]}var Qs=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.resolveClaudeAlias()}resolveClaudeAlias(){let e,r;for(let n of this.providers.values())n.type==="claude-host"?e=e??n:n.type==="claude-cli"&&(r=r??n);return e??r}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new Ws(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 Gs(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??ir(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??Rf(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 Xs(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={};Ve(h,{BRAND:()=>P$,DIRTY:()=>Ar,EMPTY_PATH:()=>o$,INVALID:()=>N,NEVER:()=>lk,OK:()=>Ne,ParseStatus:()=>Ie,Schema:()=>V,ZodAny:()=>ur,ZodArray:()=>Kt,ZodBigInt:()=>Dr,ZodBoolean:()=>zr,ZodBranded:()=>xo,ZodCatch:()=>Br,ZodDate:()=>Or,ZodDefault:()=>Vr,ZodDiscriminatedUnion:()=>ri,ZodEffects:()=>dt,ZodEnum:()=>Ur,ZodError:()=>Ye,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>oi,ZodIntersection:()=>Lr,ZodIssueCode:()=>k,ZodLazy:()=>Fr,ZodLiteral:()=>Zr,ZodMap:()=>Pn,ZodNaN:()=>En,ZodNativeEnum:()=>qr,ZodNever:()=>bt,ZodNull:()=>Nr,ZodNullable:()=>zt,ZodNumber:()=>Cr,ZodObject:()=>Xe,ZodOptional:()=>ut,ZodParsedType:()=>R,ZodPipeline:()=>So,ZodPromise:()=>lr,ZodReadonly:()=>Wr,ZodRecord:()=>ni,ZodSchema:()=>V,ZodSet:()=>Tn,ZodString:()=>cr,ZodSymbol:()=>$n,ZodTransformer:()=>dt,ZodTuple:()=>Dt,ZodType:()=>V,ZodUndefined:()=>Mr,ZodUnion:()=>jr,ZodUnknown:()=>Ht,ZodVoid:()=>kn,addIssueToContext:()=>T,any:()=>O$,array:()=>L$,bigint:()=>I$,boolean:()=>Ff,coerce:()=>uk,custom:()=>Nf,date:()=>A$,datetimeRegex:()=>Of,defaultErrorMap:()=>Bt,discriminatedUnion:()=>q$,effect:()=>tk,enum:()=>X$,function:()=>J$,getErrorMap:()=>wn,getParsedType:()=>Ct,instanceof:()=>E$,intersection:()=>V$,isAborted:()=>ei,isAsync:()=>xn,isDirty:()=>ti,isValid:()=>ar,late:()=>T$,lazy:()=>G$,literal:()=>Y$,makeIssue:()=>wo,map:()=>H$,nan:()=>R$,nativeEnum:()=>Q$,never:()=>N$,null:()=>z$,nullable:()=>nk,number:()=>Lf,object:()=>F$,objectUtil:()=>Uc,oboolean:()=>ck,onumber:()=>ak,optional:()=>rk,ostring:()=>ik,pipeline:()=>sk,preprocess:()=>ok,promise:()=>ek,quotelessJson:()=>t$,record:()=>W$,set:()=>K$,setErrorMap:()=>n$,strictObject:()=>Z$,string:()=>jf,symbol:()=>C$,transformer:()=>tk,tuple:()=>B$,undefined:()=>D$,union:()=>U$,unknown:()=>M$,util:()=>G,void:()=>j$});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 Uc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Uc||(Uc={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ct=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=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"]),t$=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ye=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()}};Ye.create=t=>new Ye(t);var r$=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,G.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${G.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${G.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${G.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.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 k.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 k.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 k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,G.assertNever(t)}return{message:r}},Bt=r$;var If=Bt;function n$(t){If=t}function wn(){return If}var wo=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}},o$=[];function T(t,e){let r=wn(),n=wo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Bt?void 0:Bt].filter(o=>!!o)});t.common.issues.push(n)}var Ie=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 N;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 N;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}}},N=Object.freeze({status:"aborted"}),Ar=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),ei=t=>t.status==="aborted",ti=t=>t.status==="dirty",ar=t=>t.status==="valid",xn=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 lt=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}},Af=(t,e)=>{if(ar(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 Ye(t.common.issues);return this._error=r,this._error}}};function Z(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 Ct(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(xn(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:Ct(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Af(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ar(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=>ar(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:Ct(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(xn(o)?o:Promise.resolve(o));return Af(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:k.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 dt({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 ut.create(this,this._def)}nullable(){return zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return lr.create(this,this._def)}or(e){return jr.create([this,e],this._def)}and(e){return Lr.create(this,e,this._def)}transform(e){return new dt({...Z(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Vr({...Z(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new xo({typeName:P.ZodBranded,type:this,...Z(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Br({...Z(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 So.create(this,e)}readonly(){return Wr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},s$=/^c[^\s-]{8,}$/i,i$=/^[0-9a-z]+$/,a$=/^[0-9A-HJKMNP-TV-Z]{26}$/i,c$=/^[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,u$=/^[a-z0-9_-]{21}$/i,l$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,d$=/^[-+]?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)?)??$/,p$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,f$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qc,m$=/^(?:(?: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])$/,h$=/^(?:(?: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])$/,g$=/^(([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]))$/,y$=/^(([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])$/,v$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Df="((\\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])))",b$=new RegExp(`^${Df}$`);function zf(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 w$(t){return new RegExp(`^${zf(t)}$`)}function Of(t){let e=`${Df}T${zf(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 x$(t,e){return!!((e==="v4"||!e)&&m$.test(t)||(e==="v6"||!e)&&g$.test(t))}function S$(t,e){if(!l$.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 $$(t,e){return!!((e==="v4"||!e)&&h$.test(t)||(e==="v6"||!e)&&y$.test(t))}var cr=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:k.invalid_type,expected:R.string,received:s.parsedType}),N}let n=new Ie,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:k.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:k.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:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")p$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")qc||(qc=new RegExp(f$,"u")),qc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")c$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")u$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")s$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")i$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")a$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:k.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:k.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:k.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:k.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:k.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:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Of(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?b$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?w$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?d$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?x$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?S$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?$$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?v$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?_$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:k.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:k.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}};cr.create=t=>new cr({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...Z(t)});function k$(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 Cr=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:k.invalid_type,expected:R.number,received:s.parsedType}),N}let n,o=new Ie;for(let s of this._def.checks)s.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.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:k.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:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?k$(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.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:k.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)}};Cr.create=t=>new Cr({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...Z(t)});var Dr=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 Ie;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:k.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:k.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:k.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:k.invalid_type,expected:R.bigint,received:r.parsedType}),N}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}};Dr.create=t=>new Dr({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...Z(t)});var zr=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:k.invalid_type,expected:R.boolean,received:n.parsedType}),N}return Ne(e.data)}};zr.create=t=>new zr({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...Z(t)});var Or=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:k.invalid_type,expected:R.date,received:s.parsedType}),N}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),N}let n=new Ie,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.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:k.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}};Or.create=t=>new Or({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...Z(t)});var $n=class extends V{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.symbol,received:n.parsedType}),N}return Ne(e.data)}};$n.create=t=>new $n({typeName:P.ZodSymbol,...Z(t)});var Mr=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.undefined,received:n.parsedType}),N}return Ne(e.data)}};Mr.create=t=>new Mr({typeName:P.ZodUndefined,...Z(t)});var Nr=class extends V{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.null,received:n.parsedType}),N}return Ne(e.data)}};Nr.create=t=>new Nr({typeName:P.ZodNull,...Z(t)});var ur=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};ur.create=t=>new ur({typeName:P.ZodAny,...Z(t)});var Ht=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};Ht.create=t=>new Ht({typeName:P.ZodUnknown,...Z(t)});var bt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.never,received:r.parsedType}),N}};bt.create=t=>new bt({typeName:P.ZodNever,...Z(t)});var kn=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.void,received:n.parsedType}),N}return Ne(e.data)}};kn.create=t=>new kn({typeName:P.ZodVoid,...Z(t)});var Kt=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:k.invalid_type,expected:R.array,received:r.parsedType}),N;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?k.too_big:k.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:k.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:k.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 lt(r,i,r.path,a)))).then(i=>Ie.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new lt(r,i,r.path,a)));return Ie.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)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...Z(e)});function Sn(t){if(t instanceof Xe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ut.create(Sn(n))}return new Xe({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:Sn(t.element)}):t instanceof ut?ut.create(Sn(t.unwrap())):t instanceof zt?zt.create(Sn(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>Sn(e))):t}var Xe=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=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:k.invalid_type,expected:R.object,received:u.parsedType}),N}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof bt&&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 lt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof bt){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:k.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 lt(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=>Ie.mergeObjectSync(n,u)):Ie.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 Sn(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 ut;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Mf(G.objectKeys(this.shape))}};Xe.create=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:P.ZodObject,...Z(e)});Xe.strictCreate=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:P.ZodObject,...Z(e)});Xe.lazycreate=(t,e)=>new Xe({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:P.ZodObject,...Z(e)});var jr=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 Ye(a.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:i}),N}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 Ye(c));return T(r,{code:k.invalid_union,unionErrors:a}),N}}get options(){return this._def.options}};jr.create=(t,e)=>new jr({options:t,typeName:P.ZodUnion,...Z(e)});var Wt=t=>t instanceof Fr?Wt(t.schema):t instanceof dt?Wt(t.innerType()):t instanceof Zr?[t.value]:t instanceof Ur?t.options:t instanceof qr?G.objectValues(t.enum):t instanceof Vr?Wt(t._def.innerType):t instanceof Mr?[void 0]:t instanceof Nr?[null]:t instanceof ut?[void 0,...Wt(t.unwrap())]:t instanceof zt?[null,...Wt(t.unwrap())]:t instanceof xo||t instanceof Wr?Wt(t.unwrap()):t instanceof Br?Wt(t._def.innerType):[],ri=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:k.invalid_type,expected:R.object,received:r.parsedType}),N;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:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),N)}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=Wt(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,...Z(n)})}};function Vc(t,e){let r=Ct(t),n=Ct(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=Vc(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=Vc(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 Lr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ei(s)||ei(i))return N;let a=Vc(s.value,i.value);return a.valid?((ti(s)||ti(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:k.invalid_intersection_types}),N)};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}))}};Lr.create=(t,e,r)=>new Lr({left:t,right:e,typeName:P.ZodIntersection,...Z(r)});var Dt=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),N;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),N;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:k.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 lt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ie.mergeArray(r,i)):Ie.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:P.ZodTuple,rest:null,...Z(e)})};var ni=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:k.invalid_type,expected:R.object,received:n.parsedType}),N;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new lt(n,a,n.path,a)),value:i._parse(new lt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ie.mergeObjectAsync(r,o):Ie.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:P.ZodRecord,...Z(n)}):new t({keyType:cr.create(),valueType:e,typeName:P.ZodRecord,...Z(r)})}},Pn=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:k.invalid_type,expected:R.map,received:n.parsedType}),N;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new lt(n,a,n.path,[u,"key"])),value:s._parse(new lt(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 N;(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 N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Pn.create=(t,e,r)=>new Pn({valueType:e,keyType:t,typeName:P.ZodMap,...Z(r)});var Tn=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:k.invalid_type,expected:R.set,received:n.parsedType}),N;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:k.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:k.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 N;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 lt(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)}};Tn.create=(t,e)=>new Tn({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...Z(e)});var oi=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:k.invalid_type,expected:R.function,received:r.parsedType}),N;function n(a,c){return wo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Bt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return wo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Bt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof lr){let a=this;return Ne(async function(...c){let u=new Ye([]),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 Ne(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ye([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ye([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:Dt.create(e).rest(Ht.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||Dt.create([]).rest(Ht.create()),returns:r||Ht.create(),typeName:P.ZodFunction,...Z(n)})}},Fr=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})}};Fr.create=(t,e)=>new Fr({getter:t,typeName:P.ZodLazy,...Z(e)});var Zr=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),N}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zr.create=(t,e)=>new Zr({value:t,typeName:P.ZodLiteral,...Z(e)});function Mf(t,e){return new Ur({values:t,typeName:P.ZodEnum,...Z(e)})}var Ur=class t extends V{_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:k.invalid_type}),N}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:k.invalid_enum_value,options:n}),N}return Ne(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})}};Ur.create=Mf;var qr=class extends V{_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:k.invalid_type}),N}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:k.invalid_enum_value,options:o}),N}return Ne(e.data)}get enum(){return this._def.values}};qr.create=(t,e)=>new qr({values:t,typeName:P.ZodNativeEnum,...Z(e)});var lr=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:k.invalid_type,expected:R.promise,received:r.parsedType}),N;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Ne(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};lr.create=(t,e)=>new lr({type:t,typeName:P.ZodPromise,...Z(e)});var dt=class extends V{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 N;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?N:c.status==="dirty"?Ar(c.value):r.value==="dirty"?Ar(c.value):c});{if(r.value==="aborted")return N;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?N:a.status==="dirty"?Ar(a.value):r.value==="dirty"?Ar(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"?N:(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"?N:(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(!ar(i))return N;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=>ar(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):N);G.assertNever(o)}};dt.create=(t,e,r)=>new dt({schema:t,typeName:P.ZodEffects,effect:e,...Z(r)});dt.createWithPreprocess=(t,e,r)=>new dt({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...Z(r)});var ut=class extends V{_parse(e){return this._getType(e)===R.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ut.create=(t,e)=>new ut({innerType:t,typeName:P.ZodOptional,...Z(e)});var zt=class extends V{_parse(e){return this._getType(e)===R.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:P.ZodNullable,...Z(e)});var Vr=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}};Vr.create=(t,e)=>new Vr({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Br=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 xn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Br.create=(t,e)=>new Br({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var En=class extends V{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.nan,received:n.parsedType}),N}return{status:"valid",value:e.data}}};En.create=t=>new En({typeName:P.ZodNaN,...Z(t)});var P$=Symbol("zod_brand"),xo=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"?N:s.status==="dirty"?(r.dirty(),Ar(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"?N: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})}},Wr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(ar(o)&&(o.value=Object.freeze(o.value)),o);return xn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Wr.create=(t,e)=>new Wr({innerType:t,typeName:P.ZodReadonly,...Z(e)});function Cf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Nf(t,e={},r){return t?ur.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Cf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Cf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ur.create()}var T$={object:Xe.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 E$=(t,e={message:`Input not instance of ${t.name}`})=>Nf(r=>r instanceof t,e),jf=cr.create,Lf=Cr.create,R$=En.create,I$=Dr.create,Ff=zr.create,A$=Or.create,C$=$n.create,D$=Mr.create,z$=Nr.create,O$=ur.create,M$=Ht.create,N$=bt.create,j$=kn.create,L$=Kt.create,F$=Xe.create,Z$=Xe.strictCreate,U$=jr.create,q$=ri.create,V$=Lr.create,B$=Dt.create,W$=ni.create,H$=Pn.create,K$=Tn.create,J$=oi.create,G$=Fr.create,Y$=Zr.create,X$=Ur.create,Q$=qr.create,ek=lr.create,tk=dt.create,rk=ut.create,nk=zt.create,ok=dt.createWithPreprocess,sk=So.create,ik=()=>jf().optional(),ak=()=>Lf().optional(),ck=()=>Ff().optional(),uk={string:(t=>cr.create({...t,coerce:!0})),number:(t=>Cr.create({...t,coerce:!0})),boolean:(t=>zr.create({...t,coerce:!0})),bigint:(t=>Dr.create({...t,coerce:!0})),date:(t=>Or.create({...t,coerce:!0}))};var lk=N;qt();var dk=h.enum(["read-only","workspace-write","full-auto"]),pk=dk.default("read-only"),fk=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:pk,config:h.record(h.unknown()).default({})}),mk=h.enum(["default-only","auto"]).default("default-only"),hk=h.object({selectionPolicy:mk,locale:h.string().optional(),providers:h.array(fk).min(1,"At least one provider required")});function Jt(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":return"workspace-write";default:return"read-only"}}function si(t){return t==="workspace-write"||t==="full-auto"}function gk(t){return Js.includes(t)}function yk(t){if(t!==void 0)return gk(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${Rr}`),Rr)}function Zf(t){let e=hk.parse(t);return{selectionPolicy:e.selectionPolicy,locale:yk(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{mkdirSync as vk}from"fs";import{homedir as _k}from"os";import{dirname as bk,join as Uf}from"path";var qf="providers.config.json";function $o(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=process.env.CLAUDE_PLUGIN_ROOT;return e&&e.length>0?Uf(e,qf):Uf(_k(),".agestra",qf)}function Vf(t){vk(bk(t),{recursive:!0})}ci();Jc();To();bo();bn();qt();import{mkdirSync as rm,readFileSync as Te,readdirSync as Eo,existsSync as We,unlinkSync as Qk,rmdirSync as e0}from"fs";import{join as X}from"path";import{spawn as nm}from"child_process";import{randomUUID as t0}from"crypto";var r0=5e3,ru=["completed","error","timed_out","cancelled","missing_cli"];function Yt(t,e){let r=X(t,"status.json"),n=`${r}.lock`;Hr(n,()=>{let o=JSON.parse(Te(r,"utf-8"));je(r,{...o,...e})})}var li=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;completionHandler;saveInFlight=new Map;deferredSaveTimers=new Map;constructor(e=process.cwd(),r){this.jobsDir=X(e,pf),rm(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7,this.completionHandler=r?.completionHandler,this.submitCount=this.countExistingJobs()}countExistingJobs(){if(!We(this.jobsDir))return 0;try{return Eo(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){let e=0,r;try{r=Eo(this.jobsDir)}catch{return 0}for(let n of r){if(!dr(n))continue;let o=X(this.jobsDir,n,"status.json");if(!We(o))continue;let s;try{s=JSON.parse(Te(o,"utf-8"))}catch{continue}if(s.state!=="running"||s.pid!==void 0&&this.isPidAlive(s.pid))continue;let i=`${o}.lock`;try{let a=Hr(i,()=>{let c=JSON.parse(Te(o,"utf-8"));if(c.state!=="running"||c.pid!==void 0&&this.isPidAlive(c.pid))return null;let u={...c,state:"error",completedAt:new Date().toISOString()};return je(o,u),u});if(!a)continue;oe(X(this.jobsDir,n,"error.txt"),"orphaned (worker process died before completion)"),this.statusCache.set(n,a),e++}catch{}}return e}resolveCreatedAtMs(e){let r=X(this.jobsDir,e,"job.json");try{let o=JSON.parse(Te(r,"utf-8")),s=new Date(o.createdAt).getTime();if(Number.isFinite(s))return s}catch{}let n=e.split("-");for(let o=n.length-2;o>=0;o--)if(/^\d+$/.test(n[o])){let s=Number(n[o]);if(Number.isFinite(s)&&s>0)return s}return null}isPidAlive(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}submit(e){let r=`${e.provider}-${Date.now()}-${t0().slice(0,6)}`,n=X(this.jobsDir,r);rm(n,{recursive:!0});let o=e.timeout??3e5,s={id:r,provider:e.provider,prompt:e.prompt,timeout:o,createdAt:new Date().toISOString(),cwd:process.cwd(),saveAsDocument:e.saveAsDocument},i={id:r,state:"queued",provider:e.provider};if(je(X(n,"job.json"),s),je(X(n,"status.json"),i),oe(X(n,"prompt.txt"),e.prompt),this.statusCache.set(r,i),this.spawnWorker(n),e.saveAsDocument&&this.completionHandler){let a=setTimeout(()=>{this.deferredSaveTimers.delete(r),this.maybeTriggerCompletionSave(r).catch(()=>{})},o+r0);a.unref?.(),this.deferredSaveTimers.set(r,a)}return this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!dr(e))return null;let r=this.statusCache.get(e);if(r&&ru.includes(r.state)&&((r.savedDocumentId?!0:r.saveError!==void 0)||!this.completionHandler))return r;let n=X(this.jobsDir,e,"status.json");if(!We(n))return null;let o=JSON.parse(Te(n,"utf-8"));if(o.state==="queued"){let s=this.resolveCreatedAtMs(e);if(s!==null&&Date.now()-s>6e4){let a=`${n}.lock`;try{let c=Hr(a,()=>{let u=JSON.parse(Te(n,"utf-8"));if(u.state!=="queued")return null;let l={...u,state:"error",completedAt:new Date().toISOString()};return je(n,l),l});if(c)return oe(X(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,c),c}catch{}}}return this.statusCache.set(e,o),ru.includes(o.state)&&!o.savedDocumentId&&!o.saveError&&this.completionHandler&&this.maybeTriggerCompletionSave(e).catch(()=>{}),o}getResult(e){if(!dr(e))return null;let r=this.getStatus(e);if(!r)return null;let n=X(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError},s=X(n,"output.txt");We(s)&&(o.output=Te(s,"utf-8"));let i=X(n,"error.txt");return We(i)&&(o.error=Te(i,"utf-8")),o}async getResultAwaited(e){return dr(e)?(await this.maybeTriggerCompletionSave(e),this.getResult(e)):null}async maybeTriggerCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e);if(!We(X(r,"status.json")))return;let n=this.saveInFlight.get(e);if(n)return n;let o=this.runCompletionSave(e).finally(()=>{this.saveInFlight.delete(e)});return this.saveInFlight.set(e,o),o}async runCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e),n=X(r,"status.json"),o=X(r,"job.json");if(!We(n)||!We(o))return;let s=JSON.parse(Te(n,"utf-8"));if(!ru.includes(s.state)||s.savedDocumentId||s.saveError)return;let i=JSON.parse(Te(o,"utf-8"));if(!i.saveAsDocument)return;let a={id:e,state:s.state,exitCode:s.exitCode},c=X(r,"output.txt");We(c)&&(a.output=Te(c,"utf-8"));let u=X(r,"error.txt");We(u)&&(a.error=Te(u,"utf-8"));try{let l=await this.completionHandler({jobId:e,descriptor:i,result:a,saveAsDocument:i.saveAsDocument});if(l){let d={savedDocumentId:l.documentId};Yt(r,d),this.statusCache.set(e,{...s,...d})}else{let d={saveError:"skipped"};Yt(r,d),this.statusCache.set(e,{...s,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{Yt(r,p),this.statusCache.set(e,{...s,...p})}catch{}}}listJobs(){if(!We(this.jobsDir))return[];let e;try{e=Eo(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory())}catch{return[]}let r=[];for(let n of e)try{let o=X(this.jobsDir,n.name,"status.json");We(o)&&r.push(JSON.parse(Te(o,"utf-8")))}catch{}return r}cancel(e){if(!dr(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&vn(r.pid);let n=X(this.jobsDir,e),o=X(n,"status.json"),s=`${o}.lock`;try{let i=Hr(s,()=>{let a=JSON.parse(Te(o,"utf-8"));if(a.state!=="queued"&&a.state!=="running")return null;let c={...a,state:"cancelled",completedAt:new Date().toISOString()};return je(o,c),c});i&&this.statusCache.set(e,i)}catch{}return this.clearDeferredSaveTimer(e),!0}clearDeferredSaveTimer(e){let r=this.deferredSaveTimers.get(e);r&&(clearTimeout(r),this.deferredSaveTimers.delete(e))}shutdown(){for(let e of this.deferredSaveTimers.values())clearTimeout(e);this.deferredSaveTimers.clear()}cleanup(){if(!We(this.jobsDir))return 0;let e;try{e=Eo(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory())}catch{return 0}let r=[];for(let u of e)try{let l=X(this.jobsDir,u.name,"status.json"),d=X(this.jobsDir,u.name,"job.json");if(!We(l))continue;let p=JSON.parse(Te(l,"utf-8")),f=null;try{f=JSON.parse(Te(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}catch{}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=X(this.jobsDir,u.name);try{let m=Eo(f);for(let g of m)Qk(X(f,g));e0(f),this.statusCache.delete(u.name),this.clearDeferredSaveTimer(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(We(r)){let n=nm(process.execPath,[r,e],{detached:!0,stdio:"ignore"}),o=typeof n.pid=="number"&&n.pid>0;if(o)try{Yt(e,{pid:n.pid})}catch{}n.on("error",s=>{if(o)return;s.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(tm(),em)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Te(X(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){Yt(e,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Te(X(e,"prompt.txt"),"utf-8"),c=i(a);Yt(e,{state:"running",startedAt:new Date().toISOString()});let u=Vt(s,c),l=nm(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(!l.stdout||!l.stderr){try{l.kill()}catch{}oe(X(e,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),Yt(e,{state:"error",completedAt:new Date().toISOString()});return}let d="",p="",f=0,m=0,g=!1,v=!1;l.stdout.on("data",y=>{f+=y.length,f<=10485760?d+=y.toString():g||(g=!0,At(l))}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let _=(y,x)=>{if(!v){v=!0,clearTimeout(S);try{oe(X(e,"output.txt"),d),x!==void 0?oe(X(e,"error.txt"),x):oe(X(e,"error.txt"),p),Yt(e,y)}catch{}}},S=setTimeout(()=>{v||(At(l),_({state:"timed_out",completedAt:new Date().toISOString()}))},n.timeout);l.on("close",y=>{if(v)return;let x=d.trim().length>0;_({state:y===0||x?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()})}),l.on("error",y=>{if(v)return;let x=y.code==="ENOENT"?"missing_cli":"error";_({state:x,completedAt:new Date().toISOString()},y.message)})}).catch(()=>{try{Yt(e,{state:"error",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),"Failed to load job worker module")}catch{}})}};ci();qt();import{mkdirSync as n0,readdirSync as om,readFileSync as o0,unlinkSync as s0}from"fs";import{join as Ro}from"path";function sm(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 i0(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function a0(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var di=class{tracesDir;writer;constructor(e,r){this.tracesDir=Ro(e,ff),n0(this.tracesDir,{recursive:!0}),this.writer=new ii(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=sm(new Date(r.timestamp)),o=Ro(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
13
+ `,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=o0(i,"utf-8").split(`
14
+ `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);a0(u)?o.push(u):i0(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=sm(o),a=Ro(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(s)+`
15
+ `,"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=om(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&&(s0(Ro(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=om(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=>Ro(this.tracesDir,n))}};var c0=/[;|&`$(){}!><\n\r\\]/,pi=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),u0=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 im(t){if(c0.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(!pi.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...pi].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(u0.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}qt();var am=[{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"}],cm=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function um(t){let e=Array.isArray(t)?t:t.split(`
16
+ `),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of am){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!cm.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 nu(t){if(t.length===0)return t;let e=t.split(`
17
+ `);for(let r=0;r<e.length;r++){let n=e[r];for(let o of am){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>cm.some(a=>a.test(i))?i:Pf)}e[r]=n}return e.join(`
18
+ `)}qt();import{execFileSync as l0}from"child_process";import{existsSync as lm,rmSync as d0,mkdirSync as p0}from"fs";import{join as dm}from"path";var fi=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=dm(e,mf)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=dm(this.worktreeBaseDir,r);p0(this.worktreeBaseDir,{recursive:!0}),lm(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(`
19
+ `))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&&(lm(e)&&d0(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return l0("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var f0=["npm","node","git","tsc"];function pm(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:[...f0]},timeout_minutes:t.timeoutMinutes??10}}function fm(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 mi=10,ou=2e4;import{spawn as _0}from"child_process";import{writeFileSync as iu,mkdirSync as b0,readFileSync as ym,existsSync as vm}from"fs";import{isAbsolute as _m,join as Io,resolve as bm}from"path";import{randomBytes as w0}from"crypto";import{execFileSync as x0}from"child_process";qt();bn();bo();To();To();import{readFileSync as mm}from"fs";var su=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 m0(t,e,r){let n=hm(t,e,r);return{command:"codex",args:["exec","--skip-git-repo-check","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function h0(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",hm(t,e,r)]}}function hm(t,e,r){let n=mm(t,"utf-8"),o=g0(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(`
20
+ `)}function gm(){let t=new su;return t.register("codex",m0),t.register("gemini",h0),t}function g0(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!Qc(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,mi))try{let s=mm(o,"utf-8"),i=s.length>ou?`${s.slice(0,ou)}
21
+ ...[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>mi&&(n.push(`...[${r.length-mi} additional read-only files omitted]`),n.push("")),n.join(`
22
+ `)}var Ao=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=Io(e,_f),this.worktreeManager=new fi(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??gm()}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=um(s);if(!i.clean){let Y=i.findings.map(Pe=>Pe.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${Y}`)}let a=w0(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=Io(this.workersBaseDir,c);b0(u,{recursive:!0});let l=pm({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=fm(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=Io(u,"task-manifest.json");iu(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=Io(u,"stdout.log"),g=Io(u,"stderr.log"),v=f?.path??r,_=this.cliBuilderRegistry.build(e.provider,p,v,n),S=Vt(_.command,_.args),y=_0(S.command,S.args,{cwd:v,env:t.buildWorkerEnv(),detached:!0,stdio:[_.stdin?"pipe":"ignore","pipe","pipe"]}),x=[],$=[];y.stdout?.on("data",Y=>x.push(Y)),y.stderr?.on("data",Y=>$.push(Y)),_.stdin!==void 0&&y.stdin?.end(_.stdin),y.unref();let M={workerId:c,provider:e.provider,state:$e.RUNNING,pid:y.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},O={info:M,process:y,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,O),e.timeoutMinutes){let Y=e.timeoutMinutes*6e4,Pe=setTimeout(()=>{if(O.info.state===$e.RUNNING&&O.process===y){O.info.state=$e.TIMEOUT,O.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let K=y.pid;K&&vn(K)}},Y);Pe.unref(),O.timeoutTimer=Pe}return y.on("close",Y=>{O.timeoutTimer&&(clearTimeout(O.timeoutTimer),O.timeoutTimer=void 0),O.info.exitCode=Y;try{iu(m,Buffer.concat(x).toString("utf-8")),iu(g,Buffer.concat($).toString("utf-8"))}catch{}O.info.state===$e.CANCELLING?O.info.state=$e.CANCELLED:Y===0?O.info.state=$e.COLLECTING:(O.info.state=$e.FAILED,O.info.error=`Process exited with code ${Y}`)}),M}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{vm(r.outputPath)&&(o=ym(r.outputPath,"utf-8").split(`
22
23
  `).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:Hc(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{sm(r.outputPath)&&(n=om(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 Xk("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 cf){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(!ti(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=im(n)?n:am(r,n);return Bt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=im(n)?n:am(r,n);return ht(o,this.baseDir)})}};var fi=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();jt();import{spawn as e0}from"child_process";var t0=3e5,r0=3,n0=15e3,o0=3e3,s0=6e5,mi=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??t0,this.maxConsecutiveFailures=e.maxConsecutiveFailures??r0,this.startupTimeoutMs=e.startupTimeoutMs??n0}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??s0)}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>lf?(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{}},o0);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=e0(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 z(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 cm(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 um(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}
24
+ `))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:nu(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{vm(r.outputPath)&&(n=ym(r.outputPath,"utf-8"))}catch{}n=nu(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)vn(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(`
25
+ `).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(r){let n=r instanceof Error?r.message:String(r);return console.warn(`[CliWorkerManager] Worker ${e} failed to create isolated worktree: ${n} \u2014 falling back to shared base directory.`),null}}execGit(e,r){return x0("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(`
26
+ `).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of bf){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(!si(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return pt(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let o=_m(n)?n:bm(r,n);return Gt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=_m(n)?n:bm(r,n);return pt(o,this.baseDir)})}};var gi=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 Rn=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()}}};bn();qt();import{spawn as S0}from"child_process";var $0=3e5,k0=3,P0=15e3,T0=3e3,wm=10*1024*1024,E0=6e5,yi=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??$0,this.maxConsecutiveFailures=e.maxConsecutiveFailures??k0,this.startupTimeoutMs=e.startupTimeoutMs??P0}async request(e,r,n){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if(n?.aborted)throw new ct(n.reason);if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),n?.aborted)throw new ct(n.reason);if(this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??E0,n)}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>xf?(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{}},T0);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=Vt(this.command,e),n=S0(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0});this.process=n;let o=c=>this.handleStdout(c.toString()),s=c=>{process.stderr.write(`[codex-app-server] ${c.toString()}`)},i=(c,u)=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("error",a),this.handleProcessClose(c,u)},a=c=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("close",i),this.handleProcessError(c)};return n.stdout.on("data",o),n.stderr.on("data",s),n.on("close",i),n.on("error",a),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){if(this.stdoutBuffer+=e,this.stdoutBuffer.length>wm){if(process.stderr.write(`[codex-app-server] stdoutBuffer exceeded ${wm} bytes \u2014 dropping and restarting
27
+ `),this.stdoutBuffer="",this.state!=="shutdown"){this.state="error",this.consecutiveFailures++,this.lastFailureTime=Date.now();for(let[,o]of this.pendingRequests)clearTimeout(o.timer),o.reject(new Error("App server stdout buffer overflow"));this.pendingRequests.clear();try{this.process?.kill("SIGTERM")}catch{}}return}for(let o of this.pendingRequests.values())o.resetTimer();let r=()=>{this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null)},n;for(;(n=this.stdoutBuffer.indexOf(`
28
+ `))!==-1;){let o=this.stdoutBuffer.slice(0,n).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(n+1),!!o){if(this.state==="starting"&&(o.includes("ready")||o.includes("initialized"))){r();continue}try{let s=JSON.parse(o);if(this.state==="starting"&&r(),s.id&&this.pendingRequests.has(s.id)){let i=this.pendingRequests.get(s.id);this.pendingRequests.delete(s.id),clearTimeout(i.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),i.resolve(s)}}catch{this.state==="starting"&&r()}}}}sendRequest(e,r,n){return new Promise((o,s)=>{if(!this.process||!this.process.stdin){s(new Error("App server process not available"));return}let i=null,a=()=>{i&&n&&(n.removeEventListener("abort",i),i=null)},c=()=>{this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),s(new Error(`App server request timeout (${r}ms of inactivity)`))},u=setTimeout(c,r),l=()=>{clearTimeout(u),u=setTimeout(c,r)},d=f=>{a(),o(f)},p=f=>{a(),s(f)};this.pendingRequests.set(e.id,{resolve:d,reject:p,timer:u,resetTimer:l}),this.state="busy",this.clearIdleTimer(),n&&(i=()=>{let f=this.pendingRequests.get(e.id);f&&(this.pendingRequests.delete(e.id),clearTimeout(f.timer),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="ready",this.resetIdleTimer()),a(),s(new ct(n.reason)))},n.addEventListener("abort",i));try{this.process.stdin.write(JSON.stringify(e)+`
29
+ `)}catch(f){clearTimeout(u),this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",s(new Error(`Failed to write to app server: ${f.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 z(t){return t instanceof Error?t.message:String(t)}function In(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}bn();async function An(t,e){try{if((await Me({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await Me({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function xm(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await Me({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 Cn(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 de(r,`Rate limited: ${n}`);throw s.markUnavailable=!0,s}throw o.includes("auth")||o.includes("credential")||o.includes("login")||o.includes("api key")?new de(r,`Authentication issue: ${n}`):new Be(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 de(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 de(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Jr(t){let e=t.prompt;if(t.system&&(e=`${t.system}
28
30
 
29
31
  ${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
30
32
 
31
33
  ### File: ${r.path}
32
34
  \`\`\`
33
35
  ${r.content}
34
- \`\`\``);return e}function hi(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 i0(t){let e=t.prompt;if(t.files?.length)for(let r of t.files)r.content&&(e+=`
36
+ \`\`\``);return e}function vi(t,e){return!!t.files?.length||e.length>4e3}function au(t){let e=0;return t.replace(/^### File: .+$/gm,()=>(e+=1,`### File ${e}`))}function pr(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Dn(t,e,r){if(t instanceof de||t instanceof Be||t instanceof ct)throw t;let n=t?.message??"";throw n.startsWith("CLI timeout after ")?new hn(e,r):new Be(e,n)}function R0(t){let e=t.prompt;if(t.system&&(e=`${t.system}
37
+
38
+ ${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
35
39
 
36
40
  ### File: ${r.path}
37
41
  \`\`\`
38
42
  ${r.content}
39
- \`\`\``);return e}function a0(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=i0(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:a0(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 c0={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"]}]},gi=class extends cr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:c0,modelName:e.modelName??"claude-host"})}};var u0={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"]}]},yi=class extends cr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:u0,modelName:e.modelName??"codex-host"})}};var l0={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"]}]},vi=class extends cr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:l0,modelName:e.modelName??"gemini-host"})}};jt();var lm={"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 dm={"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 pm={"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 fm={"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 mm=Object.freeze({en:lm,ko:dm,ja:pm,zh:fm});function h0(t){return typeof t=="string"&&Bs.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 hm(t){return t===void 0?Qc(xr):h0(t)?Qc(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${xr}`),Qc(xr))}function g0(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 g0(t,mm[t],mm[Oc])}async function gm(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:y0(n.name||"")}))}function y0(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 gm(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 ${Qp})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var _0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function ym(t){return t.split(`
40
- `).filter(n=>{let o=n.trim();return o?!_0.some(s=>s.test(o)):!1}).join(`
41
- `).trim()}function vm(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(uf);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=hi(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=um(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=vm(u.stdout);if(l!==null){let p=b0(u.stdout);return{text:l,model:p,provider:this.id}}return{text:ym(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 b0(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 w0}from"crypto";function tu(t){let e=t.trim().split(`
43
+ \`\`\``);return e}function I0(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var fr=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 ir(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new de(this.id,`${this.displayName} host bridge is not available`);try{let r=R0(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:I0(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 de(this.id,n):new Be(this.id,n)}}};var A0={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"]}]},_i=class extends fr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:A0,modelName:e.modelName??"claude-host"})}};var C0={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"]}]},bi=class extends fr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:C0,modelName:e.modelName??"codex-host"})}};var D0={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"]}]},wi=class extends fr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:D0,modelName:e.modelName??"gemini-host"})}};qt();var $m={"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 km={"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 Pm={"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 Tm={"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 Em=Object.freeze({en:$m,ko:km,ja:Pm,zh:Tm});function j0(t){return typeof t=="string"&&Js.includes(t)}function cu(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 lu(t){return t===void 0?uu(Rr):j0(t)?uu(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${Rr}`),uu(Rr))}function L0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return cu(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 ${Fc}`)),cu(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),cu(o,s))}}}function uu(t){return L0(t,Em[t],Em[Fc])}async function Rm(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:F0(n.name||"")}))}function F0(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 Gr=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 Rm(this.host),this.available=this.models.length>0,this.available&&(this.unavailableUntil=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 de(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),i=()=>o.abort(e.signal.reason);e.signal&&(e.signal.aborted?o.abort(e.signal.reason):e.signal.addEventListener("abort",i));try{let a=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(a.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new de(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!a.ok)throw new Be(this.id,`HTTP ${a.status}: ${a.statusText}`);let c=await a.json();return{text:c.response||"",model:c.model||r,provider:this.id}}catch(a){throw a.name==="AbortError"?new hn(this.id,this.timeouts.generate):a instanceof Be||a instanceof de?a:new Be(this.id,a.message)}finally{clearTimeout(s),e.signal&&e.signal.removeEventListener("abort",i)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new de(this.id,`No models detected. Install a model first (ollama pull ${df})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var U0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function Im(t){return t.split(`
44
+ `).filter(n=>{let o=n.trim();return o?!U0.some(s=>s.test(o)):!1}).join(`
45
+ `).trim()}function Am(t){try{let e=JSON.parse(t.trim());if(e&&typeof e.response=="string")return e.response}catch{let e=t.split(`
46
+ `);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 du="gemini",pu="@google/gemini-cli",Yr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new Rn(wf);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(du,pu);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}=pr(this.cliPath,du,pu,["--version"]),n=await Me({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 de(this.id,"Gemini CLI not installed");let r=Jr(e),n=vi(e,r),s=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=pr(this.cliPath,du,pu,s),c=Sm(this.id);try{let u=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,onStderrChunk:p=>c.feed(p),signal:e.signal});if(u.exitCode!==0)try{Cn(u.exitCode,u.stderr,this.id)}catch(p){throw p.markUnavailable&&(this.available=!1),p}let l=Am(u.stdout);if(l!==null){let p=q0(u.stdout);return{text:l,model:p,provider:this.id}}return{text:Im(u.stdout),model:"gemini",provider:this.id}}catch(u){if(u instanceof de)throw u.markUnavailable&&(this.available=!1),u;Dn(u,this.id,this.timeout)}}};function q0(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 V0}from"crypto";function fu(t){let e=t.trim().split(`
43
47
  `),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 _i="codex",bi="@openai/codex";function x0(){return["-C",process.cwd()]}function S0(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(_i,bi);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new mi({command:this.cliPath==="npx"?"npx":_i,commandPrefix:this.cliPath==="npx"?[bi]:void 0,commandArgs:x0()}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=ar(this.cliPath,_i,bi,["--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:w0()},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"||hi(e,r),o=S0(r,n),{command:s,cliArgs:i}=ar(this.cliPath,_i,bi,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 _m(t){try{return JSON.parse(t.trim())}catch{return null}}function bm(t){let e=_m(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=_m(o);if(s)return s}return null}function wm(t){let e=bm(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function xm(t){let e=bm(t);return typeof e?.model=="string"?e.model:"claude"}var $0=1,ru="claude",nu="@anthropic-ai/claude-code",Wr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Sn($0);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 cm(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:wm(i.stdout)??i.stdout.trim(),model:xm(i.stdout),provider:this.id}}catch(i){Tn(i,this.id,this.timeout)}}};import{randomUUID as k0}from"crypto";var P0=7200*1e3,To=class{debates=new Map;create(e){this.purgeStaleDebates();let r=k0(),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}
48
+ `)||t.trim()}var xi="codex",Si="@openai/codex";function B0(t){return["-C",t]}function W0(t,e,r){return["exec","--skip-git-repo-check","-C",r,"--full-auto","--ephemeral","--json","--",e?"-":t]}var Xr=class{id;type="codex-cli";timeout;available=!1;cliPath=null;appServer=null;defaultCwd;constructor(e){this.id=e.id,this.timeout=e.timeout??6e5,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await An(xi,Si);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new yi({command:this.cliPath==="npx"?"npx":xi,commandPrefix:this.cliPath==="npx"?[Si]:void 0,commandArgs:B0(this.defaultCwd)}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=pr(this.cliPath,xi,Si,["--version"]),n=await Me({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 de(this.id,"Codex CLI not installed");if(this.appServer&&!this.appServer.shouldFallback())try{return await this.chatViaAppServer(e)}catch(r){if(!this.shouldFallbackFrom(r))throw r}return this.chatViaCli(e)}shouldFallbackFrom(e){return!(e instanceof ct||e instanceof de||e instanceof Be)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r={method:"exec",params:{prompt:au(Jr(e)),fullAuto:!0,ephemeral:!0},id:V0()},n=await this.appServer.request(r,this.timeout,e.signal);if(n.error)throw new Be(this.id,n.error.message);return{text:fu(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=au(Jr(e)),n=process.platform==="win32"||vi(e,r),o=e.workspaceBaseDir??this.defaultCwd,s=W0(r,n,o),{command:i,cliArgs:a}=pr(this.cliPath,xi,Si,s);try{let c=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,signal:e.signal});if(c.exitCode!==0)try{Cn(c.exitCode,c.stderr,this.id)}catch(l){throw l.markUnavailable&&(this.available=!1),l}return{text:fu(c.stdout),model:"codex",provider:this.id}}catch(c){Dn(c,this.id,this.timeout)}}};function Cm(t){try{return JSON.parse(t.trim())}catch{return null}}function Dm(t){let e=Cm(t);if(e)return e;let r=t.split(`
49
+ `);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=Cm(o);if(s)return s}return null}function zm(t){let e=Dm(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function Om(t){let e=Dm(t);return typeof e?.model=="string"?e.model:"claude"}var H0=1,mu="claude",hu="@anthropic-ai/claude-code",Qr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Rn(H0);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(mu,hu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return xm(this.cliPath,mu,hu,"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 de(this.id,"Claude CLI not installed");let r=Jr(e),n=["-p","--output-format","json"];e.model&&n.push("--model",e.model),n.push(r);let{command:o,cliArgs:s}=pr(this.cliPath,mu,hu,n);try{let i=await Me({command:o,args:s,timeout:this.timeout,signal:e.signal});if(i.exitCode!==0){let c=[i.stderr,i.stdout].filter(Boolean).join(`
50
+ `).trim();try{Cn(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:zm(i.stdout)??i.stdout.trim(),model:Om(i.stdout),provider:this.id}}catch(i){Dn(i,this.id,this.timeout)}}};import{randomUUID as K0}from"crypto";var J0=7200*1e3,Do=class{debates=new Map;create(e){this.purgeStaleDebates();let r=K0(),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
51
  `;if(n.goal&&(o+=`Goal: ${n.goal}
48
52
  `),n.turns.length>0){o+=`
49
53
  === Conversation History ===
50
54
 
51
- `;let i=n.turns.length;if(i>Vs){let u=i-Vs,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];o+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
55
+ `;let i=n.turns.length;if(i>Ks){let u=i-Ks,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];o+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
52
56
 
53
- `}let a=n.turns.slice(-Vs),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
57
+ `}let a=n.turns.slice(-Ks),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
54
58
  ${u.content}
55
59
 
56
- `;if(c.length+l.length>Ac){c+=`[... history truncated at ${Ac} characters]
60
+ `;if(c.length+l.length>Mc){c+=`[... history truncated at ${Mc} characters]
57
61
 
58
62
  `;break}c+=l}o+=c,o+=`===
59
63
 
@@ -89,31 +93,31 @@ Evaluation goal: ${n.goal}
89
93
 
90
94
  ${o.content}
91
95
 
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>P0&&this.debates.delete(r)}}};import{mkdirSync as T0,readFileSync as Sm,readdirSync as ou,existsSync as wi,renameSync as E0,rmdirSync as R0}from"fs";import{join as I0}from"path";import{randomUUID as A0}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 $m=new Set(["completed","completed_with_errors","failed"]);function km(t,e){return $m.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&$m.has(e)||t==="in_progress"&&e==="in_progress")}function Pm(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 Eo=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,T0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=I0(this.sessionDir,"sessions");if(!wi(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(wi(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{E0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{ou(e).length===0&&R0(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:A0(),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(wi(n))try{let o=Sm(n,"utf-8"),s=JSON.parse(o);return Pm(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(!km(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(!km(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(!wi(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=Sm(o,"utf-8"),i=JSON.parse(s);if(!Pm(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 Tm(t,e,r){try{let n=En(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var Ro=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?`
96
+ `;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>J0&&this.debates.delete(r)}}};import{mkdirSync as G0,readFileSync as Mm,readdirSync as gu,existsSync as $i,renameSync as Y0,rmdirSync as X0}from"fs";import{join as Q0}from"path";import{randomUUID as eP}from"crypto";function yu(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 Nm=new Set(["completed","completed_with_errors","failed"]);function jm(t,e){return Nm.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&Nm.has(e)||t==="in_progress"&&e==="in_progress")}function Lm(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 zo=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,G0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=Q0(this.sessionDir,"sessions");if(!$i(e))return;let r;try{r=gu(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=Le(o,e),i=Le(o,this.sessionDir)}catch(a){console.warn(`[SessionManager] skipped legacy file ${JSON.stringify(o)}: ${String(a)}`);continue}if($i(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{Y0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{gu(e).length===0&&X0(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:eP(),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=Le(`${e}.json`,this.sessionDir)}catch{return}if($i(n))try{let o=Mm(n,"utf-8"),s=JSON.parse(o);return Lm(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(!jm(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(!jm(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=Le(`${e.id}.json`,this.sessionDir);je(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!$i(this.sessionDir)){this.fullyLoaded=!0;return}let e=gu(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=Le(r,this.sessionDir),s=Mm(o,"utf-8"),i=JSON.parse(s);if(!Lm(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function zn(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 Fm(t,e,r){try{let n=zn(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var Oo=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
97
  Additional criteria: ${n}`:"",s=[`You are a cross-validator reviewing work from provider "${e.providerId}".`,`Task: ${e.task}`,`Content to review:
94
98
  ${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 Tm(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 Im,readdirSync as Am,statSync as Si}from"fs";import{join as Cm,relative as z0}from"path";var Em=50*1024,xi=500,Rm=100;function O0(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function M0(t,e){let r=[],n=o=>{let s=Si(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of Am(o)){let a=Cm(o,i),c=Si(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function N0(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 Dm={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=Im(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
99
+ `),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return Fm(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 qm,readdirSync as Vm,statSync as Pi}from"fs";import{join as Bm,relative as nP}from"path";var Zm=50*1024,ki=500,Um=100;function oP(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function sP(t,e){let r=[],n=o=>{let s=Pi(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of Vm(o)){let a=Bm(o,i),c=Pi(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function iP(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 Wm={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=Gt(String(t.path??""),e),n=qm(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
96
100
  `),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")>Em&&(n=$n(n,Em,`
98
- ... [truncated]`)),n}},j0={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)`}},zm={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>=xi)return;let u=Am(a);for(let l of u){if(o.length>=xi)break;let d=Cm(a,l),p=c?`${c}/${l}`:l;try{let f=Si(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=xi?`
99
- ... [truncated at ${xi} entries]`:"";return o.join(`
100
- `)+i}},Om={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?O0(String(t.glob)):null,s=Si(n).isDirectory(),i=M0(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=z0(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=Im(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>=Rm))return c.join(`
101
+ `)}return Buffer.byteLength(n,"utf-8")>Zm&&(n=In(n,Zm,`
102
+ ... [truncated]`)),n}},aP={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=pt(String(t.path??""),e),n=String(t.content??"");return oe(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},Hm={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=Gt(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=ki)return;let u=Vm(a);for(let l of u){if(o.length>=ki)break;let d=Bm(a,l),p=c?`${c}/${l}`:l;try{let f=Pi(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=ki?`
103
+ ... [truncated at ${ki} entries]`:"";return o.join(`
104
+ `)+i}},Km={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=Gt(String(t.path??"."),e),o=t.glob?oP(String(t.glob)):null,s=Pi(n).isDirectory(),i=sP(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=nP(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=qm(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>=Um))return c.join(`
101
105
  `)+`
102
- ... [truncated at ${Rm} matches]`}return c.join(`
103
- `)||"No matches found."}catch{return"No matches found."}}},L0={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...ui].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=Hf(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=N0(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?`
106
+ ... [truncated at ${Um} matches]`}return c.join(`
107
+ `)||"No matches found."}catch{return"No matches found."}}},cP={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...pi].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=im(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=iP(s,i);try{let c=await Me({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
104
108
  `:"")+`[stderr] ${c.stderr}`),c.exitCode!==0&&(u+=`
105
109
  [exit code: ${c.exitCode}]`),c.truncated&&(u+=`
106
- ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${z(c)}`}}};function iu(){return[Dm,j0,zm,Om,L0]}function $i(){return[Dm,zm,Om]}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 F0=15,Z0=30,U0=3e5,q0=2e3,V0=`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.
110
+ ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${z(c)}`}}};function vu(){return[Wm,aP,Hm,Km,cP]}function Ti(){return[Wm,Hm,Km]}function _u(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 uP=15,lP=30,dP=3e5,pP=2e3,fP=`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
111
 
108
112
  Guidelines:
109
113
  - Read files before modifying them to understand the existing code.
110
114
  - Use grep_search to find relevant code across the workspace.
111
115
  - Write complete file contents when using file_write (not just diffs).
112
- - Provide a clear summary of what you did when finished.`,ki=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??F0,Z0),this.timeoutMs=e.timeoutMs??U0,this.systemPrompt=e.systemPrompt??V0,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=z(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: ${z(y)}`}n.push({iteration:i,toolName:l,arguments:p,result:$n(g,q0,"... [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 Mm(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(Ws(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Mm(e);return o?{text:(await new ki({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 Io,readFileSync as H0,readdirSync as K0}from"fs";import{join as In}from"path";var Ao=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"}**
116
+ - Provide a clear summary of what you did when finished.`,Ei=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??uP,lP),this.timeoutMs=e.timeoutMs??dP,this.systemPrompt=e.systemPrompt??fP,this.tools=e.tools??vu(),this.toolDefs=_u(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=z(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 v=zn(d);p=v&&typeof v=="object"&&!Array.isArray(v)?v:{}}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(v){g=`Error: ${z(v)}`}n.push({iteration:i,toolName:l,arguments:p,result:In(g,pP,"... [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 Jm(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var On=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(Gs(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Jm(e);return o?{text:(await new Ei({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 Mo,readFileSync as gP,readdirSync as yP}from"fs";import{join as Mn}from"path";var No=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
117
  ${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=dn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(Io(In(this.baseDir,"tsconfig.json")))return dn.tsc;if(Io(In(this.baseDir,"vitest.config.ts"))||Io(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(!Io(e))return null;try{let r=K0(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(!Io(e))return null;try{return JSON.parse(H0(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{ii(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
- ${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 G0=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),J0=/[\w./\\]+\.[a-z]{1,4}/gi,Y0=/\b\d+\.?\d*\b/g,Q0=/`[^`\n]+`/g,X0=/https?:\/\/\S+/g,eP=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function Pi(t){return Math.max(0,Math.min(1,t))}function Wt(t,e){return t.match(e)?.length??0}function tP(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 rP(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return G0.has(e)?!0:e.replace(/\s+/g,"").length<5}function nP(t){let e=tP(t);if(e.length===0)return .1;let r=e.filter(rP).length,n=(e.length-r)/e.length;return Math.max(.1,Pi(n))}function oP(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 Pi(s/3)}function sP(t){let e=Wt(t,J0)+Wt(t,Y0)+Wt(t,Q0)+Wt(t,X0)+Wt(t,eP);return Pi(e/3)}function Nm(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function iP(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Nm(i.content))r.add(a);if(r.size===0)return 0;let n=Nm(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return Pi(o/s)}function Co(t,e,r){let n={substanceRatio:nP(t),structureScore:oP(t),specificityScore:sP(t),engagementScore:iP(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Ti,readFileSync as jm,readdirSync as cu,existsSync as zo,statSync as cP,unlinkSync as uP}from"fs";import{basename as Lm,join as Do,relative as Fm,sep as Zm}from"path";import{randomUUID as lP}from"crypto";var dP="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 pP(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(!zo(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 Um(t){return Zm==="/"?t:t.split(Zm).join("/")}var Oo=class{reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.reviewDir=Do(e,dP),this.individualDir=Do(e,nf),this.debateDir=Do(e,qs),this.synthesisDir=Do(e,of),Ti(this.reviewDir,{recursive:!0}),Ti(this.individualDir,{recursive:!0}),Ti(this.debateDir,{recursive:!0}),Ti(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(zo(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):lP().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}
118
+ `)}`;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=yn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(Mo(Mn(this.baseDir,"tsconfig.json")))return yn.tsc;if(Mo(Mn(this.baseDir,"vitest.config.ts"))||Mo(Mn(this.baseDir,"vitest.config.js")))return yn.vitest;let e=this.getPackageScripts();return e?.build?yn["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?yn["npm-test"]:null}detectDesignDoc(){let e=Mn(this.baseDir,"docs","plans");if(!Mo(e))return null;try{let r=yP(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return Mn("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=Mn(this.baseDir,"package.json");if(!Mo(e))return null;try{return JSON.parse(gP(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{ui(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof st?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await Me({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),o=n.exitCode===0?n.stdout:`${n.stdout}
119
+ ${n.stderr}`.trim(),s=In(o,1e4,`
120
+ ... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var vP=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),_P=/[\w./\\]+\.[a-z]{1,4}/gi,bP=/\b\d+\.?\d*\b/g,wP=/`[^`\n]+`/g,xP=/https?:\/\/\S+/g,SP=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function Ri(t){return Math.max(0,Math.min(1,t))}function Xt(t,e){return t.match(e)?.length??0}function $P(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 kP(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return vP.has(e)?!0:e.replace(/\s+/g,"").length<5}function PP(t){let e=$P(t);if(e.length===0)return .1;let r=e.filter(kP).length,n=(e.length-r)/e.length;return Math.max(.1,Ri(n))}function TP(t){let e=Xt(t,/^\s*#\s+/gm),r=Xt(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Xt(t,/^\s*```/gm)/2),o=Xt(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return Ri(s/3)}function EP(t){let e=Xt(t,_P)+Xt(t,bP)+Xt(t,wP)+Xt(t,xP)+Xt(t,SP);return Ri(e/3)}function Gm(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function RP(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Gm(i.content))r.add(a);if(r.size===0)return 0;let n=Gm(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return Ri(o/s)}function jo(t,e,r){let n={substanceRatio:PP(t),structureScore:TP(t),specificityScore:EP(t),engagementScore:RP(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Ii,readFileSync as Ym,readdirSync as bu,existsSync as Lo,statSync as AP,unlinkSync as CP}from"fs";import{basename as Xm,join as Fo,relative as Qm,sep as eh}from"path";import{randomUUID as DP}from"crypto";var zP="reviews";function Nn(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function OP(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function jn(){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 th(t){return eh==="/"?t:t.split(eh).join("/")}var Zo=class{reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.reviewDir=Fo(e,zP),this.individualDir=Fo(e,gf),this.debateDir=Fo(e,Hs),this.synthesisDir=Fo(e,yf),Ii(this.reviewDir,{recursive:!0}),Ii(this.individualDir,{recursive:!0}),Ii(this.debateDir,{recursive:!0}),Ii(this.synthesisDir,{recursive:!0})}get allDirs(){return[this.individualDir,this.debateDir,this.synthesisDir,this.reviewDir]}nextSequenceGlobal(e){let r=0,n=new RegExp(`_${e}_(\\d{3})\\.md$`);for(let o of this.allDirs){if(!Lo(o))continue;let s;try{s=bu(o)}catch{continue}for(let i of s){let a=i.match(n);if(a){let c=parseInt(a[1],10);c>r&&(r=c)}}}return String(r+1).padStart(3,"0")}resolveDocPath(e){let r;for(let n of this.allDirs)try{let o=Le(`${e}.md`,n);if(Lo(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=jn(),n=e.topic?Nn(e.topic):DP().slice(0,8),o=this.nextSequenceGlobal(r),s=e.provider?`${e.provider}_${n}_${r}_${o}`:`${n}_${r}_${o}`,i=Le(`${s}.md`,this.reviewDir),a=`# Review: ${e.topic??s}
117
121
 
118
122
  `;a+=`**Date:** ${new Date().toISOString().slice(0,10)}
119
123
  `,e.provider&&(a+=`**Provider:** ${e.provider}
@@ -128,7 +132,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
128
132
  `}return a+=`
129
133
  ---
130
134
 
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}
135
+ `,oe(i,a),{id:s,content:a,path:i}}async createDebateDocument(e){let r=jn(),n=Nn(e.topic),o=this.nextSequenceGlobal(r),s=`${n}_${r}_${o}`,i=Le(`${s}.md`,this.debateDir),a=`# Debate: ${e.topic}
132
136
 
133
137
  `;return a+=`**Date:** ${new Date().toISOString().slice(0,10)}
134
138
  `,a+=`**Participants:** ${e.providers.join(", ")}
@@ -136,7 +140,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
136
140
  `),a+=`
137
141
  ---
138
142
 
139
- `,se(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=Cn(),n=pP(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}
143
+ `,oe(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=jn(),n=OP(e.participantId),o=Nn(e.topic),s=this.nextSequenceGlobal(r),i=`${n}_${o}_${r}_${s}`,a=Le(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
140
144
 
141
145
  `;if(c+=`**Date:** ${new Date().toISOString().slice(0,10)}
142
146
  `,c+=`**Participant:** ${e.participantId}
@@ -151,7 +155,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
151
155
  `,c+=e.content,c+=`
152
156
 
153
157
  ---
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=`${sf}_${n}_${r}_${o}`,i=Me(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
158
+ `,oe(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=jn(),n=e.sessionId.slice(0,8),o=this.nextSequenceGlobal(r),s=`${vf}_${n}_${r}_${o}`,i=Le(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
155
159
 
156
160
  `;if(a+=`**Session:** ${e.sessionId}
157
161
  `,a+=`**Rejected at:** ${new Date().toISOString()}
@@ -170,7 +174,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
170
174
  `}a+=`
171
175
  `}return a+=`
172
176
  ---
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=Um(Fm(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>Um(Fm(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
177
+ `,oe(i,a),{id:s,content:a,path:i}}async createSynthesis(e){let r=jn(),n=Nn(e.topic),o=this.nextSequenceGlobal(r),s=`${n}_${r}_${o}`,i=Le(`${s}.md`,this.synthesisDir),a=th(Qm(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>th(Qm(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
174
178
 
175
179
  `;if(u+=`**Date:** ${new Date().toISOString().slice(0,10)}
176
180
  `,u+=`**Status:** ${e.status}
@@ -181,16 +185,16 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
181
185
  `;if(u+=`
182
186
  ## Sources
183
187
 
184
- `,u+=`- Debate transcript: [${Lm(e.debatePath)}](${a})
188
+ `,u+=`- Debate transcript: [${Xm(e.debatePath)}](${a})
185
189
  `,e.individualPaths.length>0){u+=`- Individual reviews:
186
- `;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${Lm(d)}](${c[l]})
190
+ `;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${Xm(d)}](${c[l]})
187
191
  `}}return u+=`
188
192
  ---
189
193
 
190
194
  `,u+=e.body,u+=`
191
195
 
192
196
  ---
193
- `,se(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Me(`${e}.md`,this.synthesisDir);if(!zo(n))throw new Error(`Synthesis document not found: ${e}`);ni(n,`
197
+ `,oe(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Le(`${e}.md`,this.synthesisDir);if(!Lo(n))throw new Error(`Synthesis document not found: ${e}`);ai(n,`
194
198
  ${r}
195
199
  `)}async addComment(e,r){let n=this.resolveDocPath(e),o=`
196
200
  ## Comment by ${r.author}
@@ -198,66 +202,78 @@ ${r}
198
202
  ${r.content}
199
203
 
200
204
  ---
201
- `;ni(n,o)}async read(e){let r=this.resolveDocPath(e),n=jm(r,"utf-8");return{id:e,content:n,path:r}}resolveKindDir(e){switch(e){case"individual":return this.individualDir;case"debate":return this.debateDir;case"synthesis":return this.synthesisDir;case"general":return this.reviewDir}}async createDocument(e){let r=e.kind??"general",n=this.resolveKindDir(r),o=Cn(),s=e.topic?An(e.topic):An(e.title),i=Dn(n,o),a=`${s}_${o}_${i}`,c=Me(`${a}.md`,n),u=`# ${e.title}
205
+ `;ai(n,o)}async read(e){let r=this.resolveDocPath(e),n=Ym(r,"utf-8");return{id:e,content:n,path:r}}resolveKindDir(e){switch(e){case"individual":return this.individualDir;case"debate":return this.debateDir;case"synthesis":return this.synthesisDir;case"general":return this.reviewDir}}async createDocument(e){let r=e.kind??"general",n=this.resolveKindDir(r),o=jn(),s=e.topic?Nn(e.topic):Nn(e.title),i=this.nextSequenceGlobal(o),a=`${s}_${o}_${i}`,c=Le(`${a}.md`,n),u=`# ${e.title}
202
206
 
203
207
  `;if(e.metadata){for(let[l,d]of Object.entries(e.metadata))u+=`**${l}:** ${d}
204
208
  `;u+=`
205
209
  `}return u+=e.content,u+=`
206
210
 
207
211
  ---
208
- `,se(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!zo(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=jm(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(!zo(a))continue;let c=cu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Do(a,u),d=cP(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{uP(c[u].path),i++}catch{}}}return{removed:i}}};var bZ=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.")}},Ei={};function at(t){return t&&Object.assign(Ei,t),Ei}var ie={};Ze(ie,{BIGINT_FORMAT_RANGES:()=>Vm,Class:()=>lu,NUMBER_FORMAT_RANGES:()=>vu,aborted:()=>Kr,allowsEval:()=>hu,assert:()=>yP,assertEqual:()=>fP,assertIs:()=>hP,assertNever:()=>gP,assertNotEqual:()=>mP,assignProp:()=>mu,cached:()=>No,captureStackTrace:()=>Ii,cleanEnum:()=>IP,cleanRegex:()=>Lo,clone:()=>It,createTransparentProxy:()=>SP,defineLazy:()=>de,esc:()=>Hr,escapeRegex:()=>ur,extend:()=>PP,finalizeIssue:()=>gt,floatSafeRemainder:()=>fu,getElementAtPath:()=>vP,getEnumValues:()=>du,getLengthableOrigin:()=>Fo,getParsedType:()=>xP,getSizableOrigin:()=>Bm,isObject:()=>zn,isPlainObject:()=>On,issue:()=>_u,joinValues:()=>Ri,jsonStringifyReplacer:()=>pu,merge:()=>TP,normalizeParams:()=>M,nullish:()=>jo,numKeys:()=>wP,omit:()=>kP,optionalKeys:()=>yu,partial:()=>EP,pick:()=>$P,prefixIssues:()=>At,primitiveTypes:()=>qm,promiseAllObject:()=>_P,propertyKeyTypes:()=>gu,randomString:()=>bP,required:()=>RP,stringifyPrimitive:()=>Ai,unwrapMessage:()=>Mo});function fP(t){return t}function mP(t){return t}function hP(t){}function gP(t){throw new Error}function yP(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 Ri(t,e="|"){return t.map(r=>Ai(r)).join(e)}function pu(t,e){return typeof e=="bigint"?e.toString():e}function No(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 Lo(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 vP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function _P(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 bP(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 Ii=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hu=No(()=>{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 wP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var xP=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"]),qm=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 M(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 SP(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 Ai(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]},Vm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $P(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 kP(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 PP(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 TP(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 EP(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 RP(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 Mo(t){return typeof t=="string"?t:t?.message}function gt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Mo(t.inst?._zod.def?.error?.(t))??Mo(e?.error?.(t))??Mo(r.customError?.(t))??Mo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Bm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Fo(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 IP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var lu=class{constructor(...e){}};var Wm=(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})},Ci=w("$ZodError",Wm),bu=w("$ZodError",Wm,{Parent:Error});function Hm(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 Km(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 Gm=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 Ii(a,o?.callee),a}return i.value};var Jm=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 Ii(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??Ci)(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Zo=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}},Di=xu(bu);var Ym=/^[cC][^\s-]{8,}$/,Qm=/^[0-9a-z]+$/,Xm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eh=/^[0-9a-vA-V]{20}$/,th=/^[A-Za-z0-9]{27}$/,rh=/^[a-zA-Z0-9_-]{21}$/,nh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var oh=/^([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 sh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var CP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ih(){return new RegExp(CP,"u")}var ah=/^(?:(?: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])$/,ch=/^(([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})$/,uh=/^((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])$/,lh=/^(([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])$/,dh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$u=/^[A-Za-z0-9_-]*$/,ph=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var fh=/^\+(?:[0-9]){6,14}[0-9]$/,mh="(?:(?:\\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])))",hh=new RegExp(`^${mh}$`);function gh(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 yh(t){return new RegExp(`^${gh(t)}$`)}function vh(t){let e=gh({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(`^${mh}T(?:${n})$`)}var _h=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var bh=/^\d+$/,wh=/^-?\d+(?:\.\d+)?/i,xh=/true|false/i,Sh=/null/i;var $h=/^[^A-Z]*$/,kh=/^[^a-z]*$/;var Ne=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ph={number:"number",bigint:"bigint",object:"date"},Pu=w("$ZodCheckLessThan",(t,e)=>{Ne.init(t,e);let r=Ph[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)=>{Ne.init(t,e);let r=Ph[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})}}),Th=w("$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):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})}}),Eh=w("$ZodCheckNumberFormat",(t,e)=>{Ne.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=bh)}),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 Rh=w("$ZodCheckMaxLength",(t,e)=>{var r;Ne.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=Fo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ih=w("$ZodCheckMinLength",(t,e)=>{var r;Ne.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=Fo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ah=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ne.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=Fo(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})}}),Uo=w("$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=()=>{})}),Ch=w("$ZodCheckRegex",(t,e)=>{Uo.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})}}),Dh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=$h),Uo.init(t,e)}),zh=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=kh),Uo.init(t,e)}),Oh=w("$ZodCheckIncludes",(t,e)=>{Ne.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})}}),Mh=w("$ZodCheckStartsWith",(t,e)=>{Ne.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})}}),Nh=w("$ZodCheckEndsWith",(t,e)=>{Ne.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 jh=w("$ZodCheckOverwrite",(t,e)=>{Ne.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var zi=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(`
212
+ `,oe(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!Lo(r))continue;let n=bu(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Le(o,r),a=Ym(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFilesPerDir??e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!Lo(a))continue;let c=bu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Fo(a,u),d=AP(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{CP(c[u].path),i++}catch{}}}return{removed:i}}};var XZ=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 Qt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ai={};function ft(t){return t&&Object.assign(Ai,t),Ai}var ae={};Ve(ae,{BIGINT_FORMAT_RANGES:()=>nh,Class:()=>xu,NUMBER_FORMAT_RANGES:()=>Iu,aborted:()=>tn,allowsEval:()=>Tu,assert:()=>FP,assertEqual:()=>MP,assertIs:()=>jP,assertNever:()=>LP,assertNotEqual:()=>NP,assignProp:()=>Pu,cached:()=>qo,captureStackTrace:()=>Di,cleanEnum:()=>QP,cleanRegex:()=>Bo,clone:()=>Ot,createTransparentProxy:()=>WP,defineLazy:()=>pe,esc:()=>en,escapeRegex:()=>mr,extend:()=>JP,finalizeIssue:()=>wt,floatSafeRemainder:()=>ku,getElementAtPath:()=>ZP,getEnumValues:()=>Su,getLengthableOrigin:()=>Wo,getParsedType:()=>BP,getSizableOrigin:()=>oh,isObject:()=>Ln,isPlainObject:()=>Fn,issue:()=>Au,joinValues:()=>Ci,jsonStringifyReplacer:()=>$u,merge:()=>GP,normalizeParams:()=>j,nullish:()=>Vo,numKeys:()=>VP,omit:()=>KP,optionalKeys:()=>Ru,partial:()=>YP,pick:()=>HP,prefixIssues:()=>Mt,primitiveTypes:()=>rh,promiseAllObject:()=>UP,propertyKeyTypes:()=>Eu,randomString:()=>qP,required:()=>XP,stringifyPrimitive:()=>zi,unwrapMessage:()=>Uo});function MP(t){return t}function NP(t){return t}function jP(t){}function LP(t){throw new Error}function FP(t){}function Su(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 Ci(t,e="|"){return t.map(r=>zi(r)).join(e)}function $u(t,e){return typeof e=="bigint"?e.toString():e}function qo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Vo(t){return t==null}function Bo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ku(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 pe(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 Pu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ZP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function UP(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 qP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function en(t){return JSON.stringify(t)}var Di=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Tu=qo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Fn(t){if(Ln(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function VP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var BP=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}`)}},Eu=new Set(["string","number","symbol"]),rh=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ot(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function j(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 WP(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 zi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ru(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Iu={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]},nh={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function HP(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function KP(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function JP(t,e){if(!Fn(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 Pu(this,"shape",n),n},checks:[]};return Ot(t,r)}function GP(t,e){return Ot(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Pu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function YP(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 Ot(e,{...e._zod.def,shape:o,checks:[]})}function XP(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 Ot(e,{...e._zod.def,shape:o,checks:[]})}function tn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Mt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Uo(t){return typeof t=="string"?t:t?.message}function wt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Uo(t.inst?._zod.def?.error?.(t))??Uo(e?.error?.(t))??Uo(r.customError?.(t))??Uo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function oh(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Wo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Au(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function QP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var xu=class{constructor(...e){}};var sh=(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,$u,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Oi=w("$ZodError",sh),Cu=w("$ZodError",sh,{Parent:Error});function ih(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 ah(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 ch=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 Qt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>wt(c,s,ft())));throw Di(a,o?.callee),a}return i.value};var uh=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=>wt(c,s,ft())));throw Di(a,o?.callee),a}return i.value};var Du=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 Qt;return s.issues.length?{success:!1,error:new(t??Oi)(s.issues.map(i=>wt(i,o,ft())))}:{success:!0,data:s.value}},Ho=Du(Cu),zu=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=>wt(i,o,ft())))}:{success:!0,data:s.value}},Mi=zu(Cu);var lh=/^[cC][^\s-]{8,}$/,dh=/^[0-9a-z]+$/,ph=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fh=/^[0-9a-vA-V]{20}$/,mh=/^[A-Za-z0-9]{27}$/,hh=/^[a-zA-Z0-9_-]{21}$/,gh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var yh=/^([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})$/,Ou=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 vh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var tT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _h(){return new RegExp(tT,"u")}var bh=/^(?:(?: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])$/,wh=/^(([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})$/,xh=/^((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])$/,Sh=/^(([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])$/,$h=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mu=/^[A-Za-z0-9_-]*$/,kh=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Ph=/^\+(?:[0-9]){6,14}[0-9]$/,Th="(?:(?:\\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])))",Eh=new RegExp(`^${Th}$`);function Rh(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 Ih(t){return new RegExp(`^${Rh(t)}$`)}function Ah(t){let e=Rh({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(`^${Th}T(?:${n})$`)}var Ch=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Dh=/^\d+$/,zh=/^-?\d+(?:\.\d+)?/i,Oh=/true|false/i,Mh=/null/i;var Nh=/^[^A-Z]*$/,jh=/^[^a-z]*$/;var Fe=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Lh={number:"number",bigint:"bigint",object:"date"},ju=w("$ZodCheckLessThan",(t,e)=>{Fe.init(t,e);let r=Lh[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})}}),Lu=w("$ZodCheckGreaterThan",(t,e)=>{Fe.init(t,e);let r=Lh[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})}}),Fh=w("$ZodCheckMultipleOf",(t,e)=>{Fe.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):ku(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})}}),Zh=w("$ZodCheckNumberFormat",(t,e)=>{Fe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Iu[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=Dh)}),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 Uh=w("$ZodCheckMaxLength",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Vo(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=Wo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qh=w("$ZodCheckMinLength",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Vo(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=Wo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Vh=w("$ZodCheckLengthEquals",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Vo(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=Wo(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})}}),Ko=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Fe.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=()=>{})}),Bh=w("$ZodCheckRegex",(t,e)=>{Ko.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})}}),Wh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Nh),Ko.init(t,e)}),Hh=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=jh),Ko.init(t,e)}),Kh=w("$ZodCheckIncludes",(t,e)=>{Fe.init(t,e);let r=mr(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})}}),Jh=w("$ZodCheckStartsWith",(t,e)=>{Fe.init(t,e);let r=new RegExp(`^${mr(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})}}),Gh=w("$ZodCheckEndsWith",(t,e)=>{Fe.init(t,e);let r=new RegExp(`.*${mr(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 Yh=w("$ZodCheckOverwrite",(t,e)=>{Fe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Ni=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(`
209
213
  `).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(`
210
- `))}};var Fh={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=Fh;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=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=w("$ZodString",(t,e)=>{pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??_h(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)=>{Uo.init(t,e),Mi.init(t,e)}),Jh=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=oh),he.init(t,e)}),Yh=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)}),Qh=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=sh),he.init(t,e)}),Xh=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:ph.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})}}}),eg=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ih()),he.init(t,e)}),tg=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=rh),he.init(t,e)}),rg=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ym),he.init(t,e)}),ng=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Qm),he.init(t,e)}),og=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Xm),he.init(t,e)}),sg=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=eh),he.init(t,e)}),ig=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=th),he.init(t,e)}),ag=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=vh(e)),he.init(t,e)}),cg=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=hh),he.init(t,e)}),ug=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=yh(e)),he.init(t,e)}),lg=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=nh),he.init(t,e)}),dg=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ah),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),pg=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ch),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})}}}),fg=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=uh),he.init(t,e)}),mg=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=lh),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 hg(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var gg=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=dh),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{hg(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function DP(t){if(!$u.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return hg(r)}var yg=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=>{DP(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),vg=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=fh),he.init(t,e)});function zP(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 _g=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{zP(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??wh,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}}),bg=w("$ZodNumber",(t,e)=>{Eh.init(t,e),Ru.init(t,e)}),wg=w("$ZodBoolean",(t,e)=>{pe.init(t,e),t._zod.pattern=xh,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 xg=w("$ZodNull",(t,e)=>{pe.init(t,e),t._zod.pattern=Sh,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 Sg=w("$ZodUnknown",(t,e)=>{pe.init(t,e),t._zod.parse=r=>r}),$g=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 Zh(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}var kg=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=>Zh(u,r,i))):Zh(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Oi(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}function Uh(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 Pg=w("$ZodObject",(t,e)=>{pe.init(t,e);let r=No(()=>{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 zi(["shape","payload","ctx"]),f=r.value,m=x=>{let v=Hr(x);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 x of f.keys)g[x]=`key_${y++}`;p.write("const newResult = {}");for(let x of f.keys)if(f.optionalKeys.has(x)){let v=g[x];p.write(`const ${v} = ${m(x)};`);let P=Hr(x);p.write(`
211
- if (${v}.issues.length) {
212
- if (input[${P}] === undefined) {
213
- if (${P} in input) {
214
- newResult[${P}] = undefined;
214
+ `))}};var Qh={major:4,minor:0,patch:0};var fe=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Qh;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=tn(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 Qt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=tn(s,d)))});else{if(s.issues.length===d)continue;c||(c=tn(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 Qt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Ho(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Mi(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Li=w("$ZodString",(t,e)=>{fe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ch(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)=>{Ko.init(t,e),Li.init(t,e)}),ug=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=yh),he.init(t,e)}),lg=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=Ou(n))}else e.pattern??(e.pattern=Ou());he.init(t,e)}),dg=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=vh),he.init(t,e)}),pg=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:kh.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})}}}),fg=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=_h()),he.init(t,e)}),mg=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=hh),he.init(t,e)}),hg=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=lh),he.init(t,e)}),gg=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=dh),he.init(t,e)}),yg=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ph),he.init(t,e)}),vg=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=fh),he.init(t,e)}),_g=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mh),he.init(t,e)}),bg=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ah(e)),he.init(t,e)}),wg=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Eh),he.init(t,e)}),xg=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ih(e)),he.init(t,e)}),Sg=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=gh),he.init(t,e)}),$g=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=bh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),kg=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=wh),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})}}}),Pg=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=xh),he.init(t,e)}),Tg=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Sh),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 Eg(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Rg=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=$h),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Eg(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function rT(t){if(!Mu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Eg(r)}var Ig=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Mu),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{rT(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Ag=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ph),he.init(t,e)});function nT(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 Cg=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{nT(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Zu=w("$ZodNumber",(t,e)=>{fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??zh,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}}),Dg=w("$ZodNumber",(t,e)=>{Zh.init(t,e),Zu.init(t,e)}),zg=w("$ZodBoolean",(t,e)=>{fe.init(t,e),t._zod.pattern=Oh,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 Og=w("$ZodNull",(t,e)=>{fe.init(t,e),t._zod.pattern=Mh,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 Mg=w("$ZodUnknown",(t,e)=>{fe.init(t,e),t._zod.parse=r=>r}),Ng=w("$ZodNever",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function eg(t,e,r){t.issues.length&&e.issues.push(...Mt(r,t.issues)),e.value[r]=t.value}var jg=w("$ZodArray",(t,e)=>{fe.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=>eg(u,r,i))):eg(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ji(t,e,r){t.issues.length&&e.issues.push(...Mt(r,t.issues)),e.value[r]=t.value}function tg(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(...Mt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var Lg=w("$ZodObject",(t,e)=>{fe.init(t,e);let r=qo(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof fe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Ru(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});pe(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 Ni(["shape","payload","ctx"]),f=r.value,m=S=>{let y=en(S);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),v=0;for(let S of f.keys)g[S]=`key_${v++}`;p.write("const newResult = {}");for(let S of f.keys)if(f.optionalKeys.has(S)){let y=g[S];p.write(`const ${y} = ${m(S)};`);let x=en(S);p.write(`
215
+ if (${y}.issues.length) {
216
+ if (input[${x}] === undefined) {
217
+ if (${x} in input) {
218
+ newResult[${x}] = undefined;
215
219
  }
216
220
  } else {
217
221
  payload.issues = payload.issues.concat(
218
- ${v}.issues.map((iss) => ({
222
+ ${y}.issues.map((iss) => ({
219
223
  ...iss,
220
- path: iss.path ? [${P}, ...iss.path] : [${P}],
224
+ path: iss.path ? [${x}, ...iss.path] : [${x}],
221
225
  }))
222
226
  );
223
227
  }
224
- } else if (${v}.value === undefined) {
225
- if (${P} in input) newResult[${P}] = undefined;
228
+ } else if (${y}.value === undefined) {
229
+ if (${x} in input) newResult[${x}] = undefined;
226
230
  } else {
227
- newResult[${P}] = ${v}.value;
231
+ newResult[${x}] = ${y}.value;
228
232
  }
229
- `)}else{let v=g[x];p.write(`const ${v} = ${m(x)};`),p.write(`
230
- if (${v}.issues.length) payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
233
+ `)}else{let y=g[S];p.write(`const ${y} = ${m(S)};`),p.write(`
234
+ if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
231
235
  ...iss,
232
- path: iss.path ? [${Hr(x)}, ...iss.path] : [${Hr(x)}]
233
- })));`),p.write(`newResult[${Hr(x)}] = ${v}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(x,v)=>_(d,x,v)},o,s=zn,i=!Ei.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 P of l.keys){let S=v[P],N=S._zod.run({value:f[P],issues:[]},p),L=S._zod.optin==="optional"&&S._zod.optout==="optional";N instanceof Promise?m.push(N.then(Z=>L?Uh(Z,d,P,f):Oi(Z,d,P))):L?Uh(N,d,P,f):Oi(N,d,P)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],y=l.keySet,_=u._zod,x=_.def.type;for(let v of Object.keys(f)){if(y.has(v))continue;if(x==="never"){g.push(v);continue}let P=_.run({value:f[v],issues:[]},p);P instanceof Promise?m.push(P.then(S=>Oi(S,d,v))):Oi(P,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 qh(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=>Lo(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=>qh(i,r,t,n)):qh(s,r,t,n)}}),Tg=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=No(()=>{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)}}),Eg=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])=>Vh(r,c,u)):Vh(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 Vh(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 Rg=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 Ig=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}}),Ag=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 Cg=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}}),Dg=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(`^(${Lo(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)}),zg=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(`^(${Lo(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)}),Og=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=>Bh(s,e)):Bh(o,e)}});function Bh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Mg=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))}),Ng=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=>Wh(s,t)):Wh(o,t)}});function Wh(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 jg=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 Lg=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=>Hh(s,e,n)):Hh(o,e,n)}});function Hh(t,e,r){return Kr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Fg=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(Kh):Kh(o)}});function Kh(t){return t.value=Object.freeze(t.value),t}var Zg=w("$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=>Gh(s,r,n,t));Gh(o,r,n,t)}});function Gh(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 OP=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},MP=()=>{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 ${OP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ai(n.values[0])}`:`Invalid option: expected one of ${Ri(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":""}: ${Ri(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 Ug(){return{localeError:MP()}}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 NP(){return new Au}var qo=NP();function qg(t,e){return new t({type:"string",...M(e)})}function Vg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...M(e)})}function Cu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...M(e)})}function Bg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...M(e)})}function Wg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(e)})}function Hg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(e)})}function Kg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(e)})}function Gg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...M(e)})}function Jg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...M(e)})}function Yg(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(e)})}function Qg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...M(e)})}function Xg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(e)})}function ey(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...M(e)})}function ty(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...M(e)})}function ry(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(e)})}function ny(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(e)})}function oy(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(e)})}function sy(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(e)})}function iy(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(e)})}function ay(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...M(e)})}function cy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...M(e)})}function uy(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...M(e)})}function ly(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...M(e)})}function dy(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(e)})}function py(t,e){return new t({type:"string",format:"date",check:"string_format",...M(e)})}function fy(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...M(e)})}function my(t,e){return new t({type:"string",format:"duration",check:"string_format",...M(e)})}function hy(t,e){return new t({type:"number",checks:[],...M(e)})}function gy(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...M(e)})}function yy(t,e){return new t({type:"boolean",...M(e)})}function vy(t,e){return new t({type:"null",...M(e)})}function _y(t){return new t({type:"unknown"})}function by(t,e){return new t({type:"never",...M(e)})}function Ni(t,e){return new Pu({check:"less_than",...M(e),value:t,inclusive:!1})}function Vo(t,e){return new Pu({check:"less_than",...M(e),value:t,inclusive:!0})}function ji(t,e){return new Tu({check:"greater_than",...M(e),value:t,inclusive:!1})}function Bo(t,e){return new Tu({check:"greater_than",...M(e),value:t,inclusive:!0})}function Li(t,e){return new Th({check:"multiple_of",...M(e),value:t})}function Fi(t,e){return new Rh({check:"max_length",...M(e),maximum:t})}function Mn(t,e){return new Ih({check:"min_length",...M(e),minimum:t})}function Zi(t,e){return new Ah({check:"length_equals",...M(e),length:t})}function Du(t,e){return new Ch({check:"string_format",format:"regex",...M(e),pattern:t})}function zu(t){return new Dh({check:"string_format",format:"lowercase",...M(t)})}function Ou(t){return new zh({check:"string_format",format:"uppercase",...M(t)})}function Mu(t,e){return new Oh({check:"string_format",format:"includes",...M(e),includes:t})}function Nu(t,e){return new Mh({check:"string_format",format:"starts_with",...M(e),prefix:t})}function ju(t,e){return new Nh({check:"string_format",format:"ends_with",...M(e),suffix:t})}function Gr(t){return new jh({check:"overwrite",tx:t})}function Lu(t){return Gr(e=>e.normalize(t))}function Fu(){return Gr(t=>t.trim())}function Zu(){return Gr(t=>t.toLowerCase())}function Uu(){return Gr(t=>t.toUpperCase())}function wy(t,e,r){return new t({type:"array",element:e,...M(r)})}function xy(t,e,r){let n=M(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Sy(t,e,r){return new t({type:"custom",check:"custom",fn:e,...M(r)})}function Nn(t){return!!t._zod}function lr(t,e){return Nn(t)?Zo(t,e):t.safeParse(e)}function Ui(t){if(!t)return;let e;if(Nn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $y(t){if(Nn(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 Ho={};Ze(Ho,{ZodISODate:()=>Py,ZodISODateTime:()=>ky,ZodISODuration:()=>Ey,ZodISOTime:()=>Ty,date:()=>Vu,datetime:()=>qu,duration:()=>Wu,time:()=>Bu});var ky=w("ZodISODateTime",(t,e)=>{ag.init(t,e),ve.init(t,e)});function qu(t){return dy(ky,t)}var Py=w("ZodISODate",(t,e)=>{cg.init(t,e),ve.init(t,e)});function Vu(t){return py(Py,t)}var Ty=w("ZodISOTime",(t,e)=>{ug.init(t,e),ve.init(t,e)});function Bu(t){return fy(Ty,t)}var Ey=w("ZodISODuration",(t,e)=>{lg.init(t,e),ve.init(t,e)});function Wu(t){return my(Ey,t)}var Ry=(t,e)=>{Ci.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Km(t,r)},flatten:{value:r=>Hm(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},fU=w("ZodError",Ry),Ko=w("ZodError",Ry,{Parent:Error});var Iy=Gm(Ko),Ay=Jm(Ko),Cy=wu(Ko),Dy=xu(Ko);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)=>Iy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Cy(t,r,n),t.parseAsync=async(r,n)=>Ay(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Dy(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(zT(r,n)),t.superRefine=r=>t.check(OT(r)),t.overwrite=r=>t.check(Gr(r)),t.optional=()=>xe(t),t.nullable=()=>My(t),t.nullish=()=>xe(My(t)),t.nonoptional=r=>TT(t,r),t.array=()=>Q(t),t.or=r=>fe([t,r]),t.and=r=>Vi(t,r),t.transform=r=>Ku(t,Zy(r)),t.default=r=>$T(t,r),t.prefault=r=>PT(t,r),t.catch=r=>RT(t,r),t.pipe=r=>Ku(t,r),t.readonly=()=>CT(t),t.describe=r=>{let n=t.clone();return qo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return qo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return qo.get(t);let n=t.clone();return qo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Ny=w("_ZodString",(t,e)=>{Mi.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(Nu(...n)),t.endsWith=(...n)=>t.check(ju(...n)),t.min=(...n)=>t.check(Mn(...n)),t.max=(...n)=>t.check(Fi(...n)),t.length=(...n)=>t.check(Zi(...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())}),WP=w("ZodString",(t,e)=>{Mi.init(t,e),Ny.init(t,e),t.email=r=>t.check(Vg(HP,r)),t.url=r=>t.check(Gg(KP,r)),t.jwt=r=>t.check(ly(uT,r)),t.emoji=r=>t.check(Jg(GP,r)),t.guid=r=>t.check(Cu(zy,r)),t.uuid=r=>t.check(Bg(qi,r)),t.uuidv4=r=>t.check(Wg(qi,r)),t.uuidv6=r=>t.check(Hg(qi,r)),t.uuidv7=r=>t.check(Kg(qi,r)),t.nanoid=r=>t.check(Yg(JP,r)),t.guid=r=>t.check(Cu(zy,r)),t.cuid=r=>t.check(Qg(YP,r)),t.cuid2=r=>t.check(Xg(QP,r)),t.ulid=r=>t.check(ey(XP,r)),t.base64=r=>t.check(ay(iT,r)),t.base64url=r=>t.check(cy(aT,r)),t.xid=r=>t.check(ty(eT,r)),t.ksuid=r=>t.check(ry(tT,r)),t.ipv4=r=>t.check(ny(rT,r)),t.ipv6=r=>t.check(oy(nT,r)),t.cidrv4=r=>t.check(sy(oT,r)),t.cidrv6=r=>t.check(iy(sT,r)),t.e164=r=>t.check(uy(cT,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 qg(WP,t)}var ve=w("ZodStringFormat",(t,e)=>{he.init(t,e),Ny.init(t,e)}),HP=w("ZodEmail",(t,e)=>{Qh.init(t,e),ve.init(t,e)});var zy=w("ZodGUID",(t,e)=>{Jh.init(t,e),ve.init(t,e)});var qi=w("ZodUUID",(t,e)=>{Yh.init(t,e),ve.init(t,e)});var KP=w("ZodURL",(t,e)=>{Xh.init(t,e),ve.init(t,e)});var GP=w("ZodEmoji",(t,e)=>{eg.init(t,e),ve.init(t,e)});var JP=w("ZodNanoID",(t,e)=>{tg.init(t,e),ve.init(t,e)});var YP=w("ZodCUID",(t,e)=>{rg.init(t,e),ve.init(t,e)});var QP=w("ZodCUID2",(t,e)=>{ng.init(t,e),ve.init(t,e)});var XP=w("ZodULID",(t,e)=>{og.init(t,e),ve.init(t,e)});var eT=w("ZodXID",(t,e)=>{sg.init(t,e),ve.init(t,e)});var tT=w("ZodKSUID",(t,e)=>{ig.init(t,e),ve.init(t,e)});var rT=w("ZodIPv4",(t,e)=>{dg.init(t,e),ve.init(t,e)});var nT=w("ZodIPv6",(t,e)=>{pg.init(t,e),ve.init(t,e)});var oT=w("ZodCIDRv4",(t,e)=>{fg.init(t,e),ve.init(t,e)});var sT=w("ZodCIDRv6",(t,e)=>{mg.init(t,e),ve.init(t,e)});var iT=w("ZodBase64",(t,e)=>{gg.init(t,e),ve.init(t,e)});var aT=w("ZodBase64URL",(t,e)=>{yg.init(t,e),ve.init(t,e)});var cT=w("ZodE164",(t,e)=>{vg.init(t,e),ve.init(t,e)});var uT=w("ZodJWT",(t,e)=>{_g.init(t,e),ve.init(t,e)});var jy=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(Bo(n,o)),t.min=(n,o)=>t.check(Bo(n,o)),t.lt=(n,o)=>t.check(Ni(n,o)),t.lte=(n,o)=>t.check(Vo(n,o)),t.max=(n,o)=>t.check(Vo(n,o)),t.int=n=>t.check(Oy(n)),t.safe=n=>t.check(Oy(n)),t.positive=n=>t.check(ji(0,n)),t.nonnegative=n=>t.check(Bo(0,n)),t.negative=n=>t.check(Ni(0,n)),t.nonpositive=n=>t.check(Vo(0,n)),t.multipleOf=(n,o)=>t.check(Li(n,o)),t.step=(n,o)=>t.check(Li(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 hy(jy,t)}var lT=w("ZodNumberFormat",(t,e)=>{bg.init(t,e),jy.init(t,e)});function Oy(t){return gy(lT,t)}var dT=w("ZodBoolean",(t,e)=>{wg.init(t,e),Se.init(t,e)});function Pe(t){return yy(dT,t)}var pT=w("ZodNull",(t,e)=>{xg.init(t,e),Se.init(t,e)});function Gu(t){return vy(pT,t)}var fT=w("ZodUnknown",(t,e)=>{Sg.init(t,e),Se.init(t,e)});function _e(){return _y(fT)}var mT=w("ZodNever",(t,e)=>{$g.init(t,e),Se.init(t,e)});function hT(t){return by(mT,t)}var gT=w("ZodArray",(t,e)=>{kg.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(Fi(r,n)),t.length=(r,n)=>t.check(Zi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return wy(gT,t,e)}var Ly=w("ZodObject",(t,e)=>{Pg.init(t,e),Se.init(t,e),ie.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:_e()}),t.loose=()=>t.clone({...t._zod.def,catchall:_e()}),t.strict=()=>t.clone({...t._zod.def,catchall:hT()}),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(Uy,t,r[0]),t.required=(...r)=>ie.required(qy,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 Ly(r)}function qe(t,e){return new Ly({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ie.normalizeParams(e)})}var Fy=w("ZodUnion",(t,e)=>{Iu.init(t,e),Se.init(t,e),t.options=e.options});function fe(t,e){return new Fy({type:"union",options:t,...ie.normalizeParams(e)})}var yT=w("ZodDiscriminatedUnion",(t,e)=>{Fy.init(t,e),Tg.init(t,e)});function Ju(t,e,r){return new yT({type:"union",options:e,discriminator:t,...ie.normalizeParams(r)})}var vT=w("ZodIntersection",(t,e)=>{Eg.init(t,e),Se.init(t,e)});function Vi(t,e){return new vT({type:"intersection",left:t,right:e})}var _T=w("ZodRecord",(t,e)=>{Rg.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new _T({type:"record",keyType:t,valueType:e,...ie.normalizeParams(r)})}var Hu=w("ZodEnum",(t,e)=>{Ig.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 Je(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 bT=w("ZodLiteral",(t,e)=>{Ag.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 bT({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var wT=w("ZodTransform",(t,e)=>{Cg.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 Zy(t){return new wT({type:"transform",transform:t})}var Uy=w("ZodOptional",(t,e)=>{Dg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new Uy({type:"optional",innerType:t})}var xT=w("ZodNullable",(t,e)=>{zg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function My(t){return new xT({type:"nullable",innerType:t})}var ST=w("ZodDefault",(t,e)=>{Og.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function $T(t,e){return new ST({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var kT=w("ZodPrefault",(t,e)=>{Mg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function PT(t,e){return new kT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var qy=w("ZodNonOptional",(t,e)=>{Ng.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function TT(t,e){return new qy({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var ET=w("ZodCatch",(t,e)=>{jg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function RT(t,e){return new ET({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var IT=w("ZodPipe",(t,e)=>{Lg.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function Ku(t,e){return new IT({type:"pipe",in:t,out:e})}var AT=w("ZodReadonly",(t,e)=>{Fg.init(t,e),Se.init(t,e)});function CT(t){return new AT({type:"readonly",innerType:t})}var Vy=w("ZodCustom",(t,e)=>{Zg.init(t,e),Se.init(t,e)});function DT(t){let e=new Ne({check:"custom"});return e._zod.check=t,e}function By(t,e){return xy(Vy,t??(()=>!0),e)}function zT(t,e={}){return Sy(Vy,t,e)}function OT(t){let e=DT(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(Zy(t),e)}at(Ug());var Xu="2025-11-25";var Wy=[Xu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],dr="io.modelcontextprotocol/related-task",Wi="2.0",Ee=By(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Hy=fe([b(),ae().int()]),Ky=b(),iq=qe({ttl:fe([ae(),Gu()]).optional(),pollInterval:ae().optional()}),MT=I({ttl:ae().optional()}),NT=I({taskId:b()}),el=qe({progressToken:Hy.optional(),[dr]:NT.optional()}),nt=I({_meta:el.optional()}),Go=nt.extend({task:MT.optional()}),Gy=t=>Go.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()}),Hi=fe([b(),ae().int()]),Jy=I({jsonrpc:C(Wi),id:Hi,...Re.shape}).strict(),tl=t=>Jy.safeParse(t).success,Yy=I({jsonrpc:C(Wi),...ut.shape}).strict(),Qy=t=>Yy.safeParse(t).success,rl=I({jsonrpc:C(Wi),id:Hi,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(Wi),id:Hi.optional(),error:I({code:ae().int(),message:b(),data:_e().optional()})}).strict();var Xy=t=>nl.safeParse(t).success;var ev=fe([Jy,Yy,rl,nl]),aq=fe([rl,nl]),Ki=Ie.strict(),jT=ct.extend({requestId:Hi.optional(),reason:b().optional()}),Gi=ut.extend({method:C("notifications/cancelled"),params:jT}),LT=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Je(["light","dark"]).optional()}),Yo=I({icons:Q(LT).optional()}),jn=I({name:b(),title:b().optional()}),tv=jn.extend({...jn.shape,...Yo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),FT=Vi(I({applyDefaults:Pe().optional()}),be(b(),_e())),ZT=Yu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Vi(I({form:FT.optional(),url:Ee.optional()}),be(b(),_e()).optional())),UT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({sampling:qe({createMessage:Ee.optional()}).optional(),elicitation:qe({create:Ee.optional()}).optional()}).optional()}),qT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({tools:qe({call:Ee.optional()}).optional()}).optional()}),VT=I({experimental:be(b(),Ee).optional(),sampling:I({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:ZT.optional(),roots:I({listChanged:Pe().optional()}).optional(),tasks:UT.optional()}),BT=nt.extend({protocolVersion:b(),capabilities:VT,clientInfo:tv}),ol=Re.extend({method:C("initialize"),params:BT});var WT=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:qT.optional()}),HT=Ie.extend({protocolVersion:b(),capabilities:WT,serverInfo:tv,instructions:b().optional()}),sl=ut.extend({method:C("notifications/initialized"),params:ct.optional()});var Ji=Re.extend({method:C("ping"),params:nt.optional()}),KT=I({progress:ae(),total:xe(ae()),message:xe(b())}),GT=I({...ct.shape,...KT.shape,progressToken:Hy}),Yi=ut.extend({method:C("notifications/progress"),params:GT}),JT=nt.extend({cursor:Ky.optional()}),Qo=Re.extend({params:JT.optional()}),Xo=Ie.extend({nextCursor:Ky.optional()}),YT=Je(["working","input_required","completed","failed","cancelled"]),es=I({taskId:b(),status:YT,ttl:fe([ae(),Gu()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ae()),statusMessage:xe(b())}),Ln=Ie.extend({task:es}),QT=ct.merge(es),ts=ut.extend({method:C("notifications/tasks/status"),params:QT}),Qi=Re.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Xi=Ie.merge(es),ea=Re.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),cq=Ie.loose(),ta=Qo.extend({method:C("tasks/list")}),ra=Xo.extend({tasks:Q(es)}),na=Re.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),rv=Ie.merge(es),nv=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),ov=nv.extend({text:b()}),il=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),sv=nv.extend({blob:il}),rs=Je(["user","assistant"]),Fn=I({audience:Q(rs).optional(),priority:ae().min(0).max(1).optional(),lastModified:Ho.datetime({offset:!0}).optional()}),iv=I({...jn.shape,...Yo.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),XT=I({...jn.shape,...Yo.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),eE=Qo.extend({method:C("resources/list")}),tE=Xo.extend({resources:Q(iv)}),rE=Qo.extend({method:C("resources/templates/list")}),nE=Xo.extend({resourceTemplates:Q(XT)}),al=nt.extend({uri:b()}),oE=al,sE=Re.extend({method:C("resources/read"),params:oE}),iE=Ie.extend({contents:Q(fe([ov,sv]))}),aE=ut.extend({method:C("notifications/resources/list_changed"),params:ct.optional()}),cE=al,uE=Re.extend({method:C("resources/subscribe"),params:cE}),lE=al,dE=Re.extend({method:C("resources/unsubscribe"),params:lE}),pE=ct.extend({uri:b()}),fE=ut.extend({method:C("notifications/resources/updated"),params:pE}),mE=I({name:b(),description:xe(b()),required:xe(Pe())}),hE=I({...jn.shape,...Yo.shape,description:xe(b()),arguments:xe(Q(mE)),_meta:xe(qe({}))}),gE=Qo.extend({method:C("prompts/list")}),yE=Xo.extend({prompts:Q(hE)}),vE=nt.extend({name:b(),arguments:be(b(),b()).optional()}),_E=Re.extend({method:C("prompts/get"),params:vE}),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()}),bE=I({type:C("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),wE=I({type:C("resource"),resource:fe([ov,sv]),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),xE=iv.extend({type:C("resource_link")}),dl=fe([cl,ul,ll,xE,wE]),SE=I({role:rs,content:dl}),$E=Ie.extend({description:b().optional(),messages:Q(SE)}),kE=ut.extend({method:C("notifications/prompts/list_changed"),params:ct.optional()}),PE=I({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),TE=I({taskSupport:Je(["required","optional","forbidden"]).optional()}),av=I({...jn.shape,...Yo.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:PE.optional(),execution:TE.optional(),_meta:be(b(),_e()).optional()}),pl=Qo.extend({method:C("tools/list")}),EE=Xo.extend({tools:Q(av)}),oa=Ie.extend({content:Q(dl).default([]),structuredContent:be(b(),_e()).optional(),isError:Pe().optional()}),uq=oa.or(Ie.extend({toolResult:_e()})),RE=Go.extend({name:b(),arguments:be(b(),_e()).optional()}),ns=Re.extend({method:C("tools/call"),params:RE}),IE=ut.extend({method:C("notifications/tools/list_changed"),params:ct.optional()}),lq=I({autoRefresh:Pe().default(!0),debounceMs:ae().int().nonnegative().default(300)}),os=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),AE=nt.extend({level:os}),fl=Re.extend({method:C("logging/setLevel"),params:AE}),CE=ct.extend({level:os,logger:b().optional(),data:_e()}),DE=ut.extend({method:C("notifications/message"),params:CE}),zE=I({name:b().optional()}),OE=I({hints:Q(zE).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),ME=I({mode:Je(["auto","required","none"]).optional()}),NE=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()}),jE=Ju("type",[cl,ul,ll]),Bi=Ju("type",[cl,ul,ll,bE,NE]),LE=I({role:rs,content:fe([Bi,Q(Bi)]),_meta:be(b(),_e()).optional()}),FE=Go.extend({messages:Q(LE),modelPreferences:OE.optional(),systemPrompt:b().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:Q(b()).optional(),metadata:Ee.optional(),tools:Q(av).optional(),toolChoice:ME.optional()}),ZE=Re.extend({method:C("sampling/createMessage"),params:FE}),ml=Ie.extend({model:b(),stopReason:xe(Je(["endTurn","stopSequence","maxTokens"]).or(b())),role:rs,content:jE}),hl=Ie.extend({model:b(),stopReason:xe(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:rs,content:fe([Bi,Q(Bi)])}),UE=I({type:C("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),qE=I({type:C("string"),title:b().optional(),description:b().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:Je(["email","uri","date","date-time"]).optional(),default:b().optional()}),VE=I({type:Je(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),BE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),WE=I({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),HE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),KE=fe([BE,WE]),GE=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()}),JE=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()}),YE=fe([GE,JE]),QE=fe([HE,KE,YE]),XE=fe([QE,UE,qE,VE]),eR=Go.extend({mode:C("form").optional(),message:b(),requestedSchema:I({type:C("object"),properties:be(b(),XE),required:Q(b()).optional()})}),tR=Go.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),rR=fe([eR,tR]),nR=Re.extend({method:C("elicitation/create"),params:rR}),oR=ct.extend({elicitationId:b()}),sR=ut.extend({method:C("notifications/elicitation/complete"),params:oR}),sa=Ie.extend({action:Je(["accept","decline","cancel"]),content:Yu(t=>t===null?void 0:t,be(b(),fe([b(),ae(),Pe(),Q(b())])).optional())}),iR=I({type:C("ref/resource"),uri:b()});var aR=I({type:C("ref/prompt"),name:b()}),cR=nt.extend({ref:fe([aR,iR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),uR=Re.extend({method:C("completion/complete"),params:cR});var lR=Ie.extend({completion:qe({values:Q(b()).max(100),total:xe(ae().int()),hasMore:xe(Pe())})}),dR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),pR=Re.extend({method:C("roots/list"),params:nt.optional()}),gl=Ie.extend({roots:Q(dR)}),fR=ut.extend({method:C("notifications/roots/list_changed"),params:ct.optional()}),dq=fe([Ji,ol,uR,fl,_E,gE,eE,rE,sE,uE,dE,ns,pl,Qi,ea,ta,na]),pq=fe([Gi,Yi,sl,fR,ts]),fq=fe([Ki,ml,hl,sa,gl,Xi,ra,Ln]),mq=fe([Ji,ZE,nR,pR,Qi,ea,ta,na]),hq=fe([Gi,Yi,DE,fE,aE,IE,kE,ts,sR]),gq=fe([Ki,HT,lR,$E,yE,tE,nE,iE,oa,EE,Xi,ra,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 uv=Symbol("Let zodToJsonSchema decide on which parser to use");var cv={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"},lv=t=>typeof t=="string"?{...cv,name:t}:{...cv,...t};var dv=t=>{let e=lv(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 ia=(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"?ia(e,t.currentPath):e.join("/")}}function pv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==k.ZodAny&&(r.items=j(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 fv(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 mv(){return{type:"boolean"}}function aa(t,e){return j(t.type._def,e)}var hv=(t,e)=>j(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 mR(t,e)}}var mR=(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 gv(t,e){return{...j(t.innerType._def,e),default:t.defaultValue()}}function yv(t,e){return e.effectStrategy==="input"?j(t.schema._def,e):we(e)}function vv(t){return{type:"string",enum:Array.from(t.values)}}var hR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function _v(t,e){let r=[j(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),j(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(hR(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 bv(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 ca(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"?yR(t):t}var gR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yR(t){let e="";for(let r=0;r<t.length;r++)gR.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:wv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",wv(e,n),r,n)}function wv(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
236
+ path: iss.path ? [${en(S)}, ...iss.path] : [${en(S)}]
237
+ })));`),p.write(`newResult[${en(S)}] = ${y}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(S,y)=>_(d,S,y)},o,s=Ln,i=!Ai.jitless,c=i&&Tu.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 y=l.shape;for(let x of l.keys){let $=y[x],M=$._zod.run({value:f[x],issues:[]},p),O=$._zod.optin==="optional"&&$._zod.optout==="optional";M instanceof Promise?m.push(M.then(Y=>O?tg(Y,d,x,f):ji(Y,d,x))):O?tg(M,d,x,f):ji(M,d,x)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],v=l.keySet,_=u._zod,S=_.def.type;for(let y of Object.keys(f)){if(v.has(y))continue;if(S==="never"){g.push(y);continue}let x=_.run({value:f[y],issues:[]},p);x instanceof Promise?m.push(x.then($=>ji($,d,y))):ji(x,d,y)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function rg(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=>wt(s,n,ft())))}),e}var Uu=w("$ZodUnion",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),pe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),pe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),pe(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=>Bo(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=>rg(i,r,t,n)):rg(s,r,t,n)}}),Fg=w("$ZodDiscriminatedUnion",(t,e)=>{Uu.init(t,e);let r=t._zod.parse;pe(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=qo(()=>{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(!Ln(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)}}),Zg=w("$ZodIntersection",(t,e)=>{fe.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])=>ng(r,c,u)):ng(r,s,i)}});function Fu(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(Fn(t)&&Fn(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=Fu(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=Fu(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 ng(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),tn(t))return t;let n=Fu(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 Ug=w("$ZodRecord",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Fn(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(...Mt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Mt(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=>wt(u,n,ft())),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(...Mt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Mt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var qg=w("$ZodEnum",(t,e)=>{fe.init(t,e);let r=Su(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Eu.has(typeof n)).map(n=>typeof n=="string"?mr(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}}),Vg=w("$ZodLiteral",(t,e)=>{fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?mr(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 Bg=w("$ZodTransform",(t,e)=>{fe.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 Qt;return r.value=o,r}}),Wg=w("$ZodOptional",(t,e)=>{fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Bo(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)}),Hg=w("$ZodNullable",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Bo(r.source)}|null)$`):void 0}),pe(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)}),Kg=w("$ZodDefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(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=>og(s,e)):og(o,e)}});function og(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Jg=w("$ZodPrefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(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))}),Gg=w("$ZodNonOptional",(t,e)=>{fe.init(t,e),pe(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=>sg(s,t)):sg(o,t)}});function sg(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 Yg=w("$ZodCatch",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(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=>wt(i,n,ft()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>wt(s,n,ft()))},input:r.value}),r.issues=[]),r)}});var Xg=w("$ZodPipe",(t,e)=>{fe.init(t,e),pe(t._zod,"values",()=>e.in._zod.values),pe(t._zod,"optin",()=>e.in._zod.optin),pe(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=>ig(s,e,n)):ig(o,e,n)}});function ig(t,e,r){return tn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Qg=w("$ZodReadonly",(t,e)=>{fe.init(t,e),pe(t._zod,"propValues",()=>e.innerType._zod.propValues),pe(t._zod,"values",()=>e.innerType._zod.values),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(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(ag):ag(o)}});function ag(t){return t.value=Object.freeze(t.value),t}var ey=w("$ZodCustom",(t,e)=>{Fe.init(t,e),fe.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=>cg(s,r,n,t));cg(o,r,n,t)}});function cg(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(Au(o))}}var oT=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},sT=()=>{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 ${oT(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${zi(n.values[0])}`:`Invalid option: expected one of ${Ci(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":""}: ${Ci(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 ty(){return{localeError:sT()}}var qu=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 iT(){return new qu}var Jo=iT();function ry(t,e){return new t({type:"string",...j(e)})}function ny(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Vu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function oy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function sy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function iy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function ay(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function cy(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function uy(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function ly(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function dy(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function py(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function fy(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function my(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function hy(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function gy(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function yy(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function vy(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function _y(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function by(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function wy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function xy(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function Sy(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function $y(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function ky(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function Py(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function Ty(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function Ey(t,e){return new t({type:"number",checks:[],...j(e)})}function Ry(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function Iy(t,e){return new t({type:"boolean",...j(e)})}function Ay(t,e){return new t({type:"null",...j(e)})}function Cy(t){return new t({type:"unknown"})}function Dy(t,e){return new t({type:"never",...j(e)})}function Fi(t,e){return new ju({check:"less_than",...j(e),value:t,inclusive:!1})}function Go(t,e){return new ju({check:"less_than",...j(e),value:t,inclusive:!0})}function Zi(t,e){return new Lu({check:"greater_than",...j(e),value:t,inclusive:!1})}function Yo(t,e){return new Lu({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ui(t,e){return new Fh({check:"multiple_of",...j(e),value:t})}function qi(t,e){return new Uh({check:"max_length",...j(e),maximum:t})}function Zn(t,e){return new qh({check:"min_length",...j(e),minimum:t})}function Vi(t,e){return new Vh({check:"length_equals",...j(e),length:t})}function Bu(t,e){return new Bh({check:"string_format",format:"regex",...j(e),pattern:t})}function Wu(t){return new Wh({check:"string_format",format:"lowercase",...j(t)})}function Hu(t){return new Hh({check:"string_format",format:"uppercase",...j(t)})}function Ku(t,e){return new Kh({check:"string_format",format:"includes",...j(e),includes:t})}function Ju(t,e){return new Jh({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Gu(t,e){return new Gh({check:"string_format",format:"ends_with",...j(e),suffix:t})}function rn(t){return new Yh({check:"overwrite",tx:t})}function Yu(t){return rn(e=>e.normalize(t))}function Xu(){return rn(t=>t.trim())}function Qu(){return rn(t=>t.toLowerCase())}function el(){return rn(t=>t.toUpperCase())}function zy(t,e,r){return new t({type:"array",element:e,...j(r)})}function Oy(t,e,r){let n=j(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function My(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function Un(t){return!!t._zod}function hr(t,e){return Un(t)?Ho(t,e):t.safeParse(e)}function Bi(t){if(!t)return;let e;if(Un(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ny(t){if(Un(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 Qo={};Ve(Qo,{ZodISODate:()=>Ly,ZodISODateTime:()=>jy,ZodISODuration:()=>Zy,ZodISOTime:()=>Fy,date:()=>rl,datetime:()=>tl,duration:()=>ol,time:()=>nl});var jy=w("ZodISODateTime",(t,e)=>{bg.init(t,e),ve.init(t,e)});function tl(t){return $y(jy,t)}var Ly=w("ZodISODate",(t,e)=>{wg.init(t,e),ve.init(t,e)});function rl(t){return ky(Ly,t)}var Fy=w("ZodISOTime",(t,e)=>{xg.init(t,e),ve.init(t,e)});function nl(t){return Py(Fy,t)}var Zy=w("ZodISODuration",(t,e)=>{Sg.init(t,e),ve.init(t,e)});function ol(t){return Ty(Zy,t)}var Uy=(t,e)=>{Oi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>ah(t,r)},flatten:{value:r=>ih(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},BU=w("ZodError",Uy),es=w("ZodError",Uy,{Parent:Error});var qy=ch(es),Vy=uh(es),By=Du(es),Wy=zu(es);var Se=w("ZodType",(t,e)=>(fe.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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>qy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>By(t,r,n),t.parseAsync=async(r,n)=>Vy(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wy(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(nE(r,n)),t.superRefine=r=>t.check(oE(r)),t.overwrite=r=>t.check(rn(r)),t.optional=()=>xe(t),t.nullable=()=>Jy(t),t.nullish=()=>xe(Jy(t)),t.nonoptional=r=>GT(t,r),t.array=()=>Q(t),t.or=r=>me([t,r]),t.and=r=>Hi(t,r),t.transform=r=>il(t,ev(r)),t.default=r=>HT(t,r),t.prefault=r=>JT(t,r),t.catch=r=>XT(t,r),t.pipe=r=>il(t,r),t.readonly=()=>tE(t),t.describe=r=>{let n=t.clone();return Jo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Jo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Jo.get(t);let n=t.clone();return Jo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Gy=w("_ZodString",(t,e)=>{Li.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(Bu(...n)),t.includes=(...n)=>t.check(Ku(...n)),t.startsWith=(...n)=>t.check(Ju(...n)),t.endsWith=(...n)=>t.check(Gu(...n)),t.min=(...n)=>t.check(Zn(...n)),t.max=(...n)=>t.check(qi(...n)),t.length=(...n)=>t.check(Vi(...n)),t.nonempty=(...n)=>t.check(Zn(1,...n)),t.lowercase=n=>t.check(Wu(n)),t.uppercase=n=>t.check(Hu(n)),t.trim=()=>t.check(Xu()),t.normalize=(...n)=>t.check(Yu(...n)),t.toLowerCase=()=>t.check(Qu()),t.toUpperCase=()=>t.check(el())}),hT=w("ZodString",(t,e)=>{Li.init(t,e),Gy.init(t,e),t.email=r=>t.check(ny(gT,r)),t.url=r=>t.check(cy(yT,r)),t.jwt=r=>t.check(Sy(CT,r)),t.emoji=r=>t.check(uy(vT,r)),t.guid=r=>t.check(Vu(Hy,r)),t.uuid=r=>t.check(oy(Wi,r)),t.uuidv4=r=>t.check(sy(Wi,r)),t.uuidv6=r=>t.check(iy(Wi,r)),t.uuidv7=r=>t.check(ay(Wi,r)),t.nanoid=r=>t.check(ly(_T,r)),t.guid=r=>t.check(Vu(Hy,r)),t.cuid=r=>t.check(dy(bT,r)),t.cuid2=r=>t.check(py(wT,r)),t.ulid=r=>t.check(fy(xT,r)),t.base64=r=>t.check(by(RT,r)),t.base64url=r=>t.check(wy(IT,r)),t.xid=r=>t.check(my(ST,r)),t.ksuid=r=>t.check(hy($T,r)),t.ipv4=r=>t.check(gy(kT,r)),t.ipv6=r=>t.check(yy(PT,r)),t.cidrv4=r=>t.check(vy(TT,r)),t.cidrv6=r=>t.check(_y(ET,r)),t.e164=r=>t.check(xy(AT,r)),t.datetime=r=>t.check(tl(r)),t.date=r=>t.check(rl(r)),t.time=r=>t.check(nl(r)),t.duration=r=>t.check(ol(r))});function b(t){return ry(hT,t)}var ve=w("ZodStringFormat",(t,e)=>{he.init(t,e),Gy.init(t,e)}),gT=w("ZodEmail",(t,e)=>{dg.init(t,e),ve.init(t,e)});var Hy=w("ZodGUID",(t,e)=>{ug.init(t,e),ve.init(t,e)});var Wi=w("ZodUUID",(t,e)=>{lg.init(t,e),ve.init(t,e)});var yT=w("ZodURL",(t,e)=>{pg.init(t,e),ve.init(t,e)});var vT=w("ZodEmoji",(t,e)=>{fg.init(t,e),ve.init(t,e)});var _T=w("ZodNanoID",(t,e)=>{mg.init(t,e),ve.init(t,e)});var bT=w("ZodCUID",(t,e)=>{hg.init(t,e),ve.init(t,e)});var wT=w("ZodCUID2",(t,e)=>{gg.init(t,e),ve.init(t,e)});var xT=w("ZodULID",(t,e)=>{yg.init(t,e),ve.init(t,e)});var ST=w("ZodXID",(t,e)=>{vg.init(t,e),ve.init(t,e)});var $T=w("ZodKSUID",(t,e)=>{_g.init(t,e),ve.init(t,e)});var kT=w("ZodIPv4",(t,e)=>{$g.init(t,e),ve.init(t,e)});var PT=w("ZodIPv6",(t,e)=>{kg.init(t,e),ve.init(t,e)});var TT=w("ZodCIDRv4",(t,e)=>{Pg.init(t,e),ve.init(t,e)});var ET=w("ZodCIDRv6",(t,e)=>{Tg.init(t,e),ve.init(t,e)});var RT=w("ZodBase64",(t,e)=>{Rg.init(t,e),ve.init(t,e)});var IT=w("ZodBase64URL",(t,e)=>{Ig.init(t,e),ve.init(t,e)});var AT=w("ZodE164",(t,e)=>{Ag.init(t,e),ve.init(t,e)});var CT=w("ZodJWT",(t,e)=>{Cg.init(t,e),ve.init(t,e)});var Yy=w("ZodNumber",(t,e)=>{Zu.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(Zi(n,o)),t.gte=(n,o)=>t.check(Yo(n,o)),t.min=(n,o)=>t.check(Yo(n,o)),t.lt=(n,o)=>t.check(Fi(n,o)),t.lte=(n,o)=>t.check(Go(n,o)),t.max=(n,o)=>t.check(Go(n,o)),t.int=n=>t.check(Ky(n)),t.safe=n=>t.check(Ky(n)),t.positive=n=>t.check(Zi(0,n)),t.nonnegative=n=>t.check(Yo(0,n)),t.negative=n=>t.check(Fi(0,n)),t.nonpositive=n=>t.check(Go(0,n)),t.multipleOf=(n,o)=>t.check(Ui(n,o)),t.step=(n,o)=>t.check(Ui(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 ce(t){return Ey(Yy,t)}var DT=w("ZodNumberFormat",(t,e)=>{Dg.init(t,e),Yy.init(t,e)});function Ky(t){return Ry(DT,t)}var zT=w("ZodBoolean",(t,e)=>{zg.init(t,e),Se.init(t,e)});function Ee(t){return Iy(zT,t)}var OT=w("ZodNull",(t,e)=>{Og.init(t,e),Se.init(t,e)});function al(t){return Ay(OT,t)}var MT=w("ZodUnknown",(t,e)=>{Mg.init(t,e),Se.init(t,e)});function _e(){return Cy(MT)}var NT=w("ZodNever",(t,e)=>{Ng.init(t,e),Se.init(t,e)});function jT(t){return Dy(NT,t)}var LT=w("ZodArray",(t,e)=>{jg.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Zn(r,n)),t.nonempty=r=>t.check(Zn(1,r)),t.max=(r,n)=>t.check(qi(r,n)),t.length=(r,n)=>t.check(Vi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return zy(LT,t,e)}var Xy=w("ZodObject",(t,e)=>{Lg.init(t,e),Se.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Qe(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:jT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ae.extend(t,r),t.merge=r=>ae.merge(t,r),t.pick=r=>ae.pick(t,r),t.omit=r=>ae.omit(t,r),t.partial=(...r)=>ae.partial(tv,t,r[0]),t.required=(...r)=>ae.required(rv,t,r[0])});function I(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new Xy(r)}function He(t,e){return new Xy({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ae.normalizeParams(e)})}var Qy=w("ZodUnion",(t,e)=>{Uu.init(t,e),Se.init(t,e),t.options=e.options});function me(t,e){return new Qy({type:"union",options:t,...ae.normalizeParams(e)})}var FT=w("ZodDiscriminatedUnion",(t,e)=>{Qy.init(t,e),Fg.init(t,e)});function cl(t,e,r){return new FT({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}var ZT=w("ZodIntersection",(t,e)=>{Zg.init(t,e),Se.init(t,e)});function Hi(t,e){return new ZT({type:"intersection",left:t,right:e})}var UT=w("ZodRecord",(t,e)=>{Ug.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new UT({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}var sl=w("ZodEnum",(t,e)=>{qg.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 sl({...e,checks:[],...ae.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 sl({...e,checks:[],...ae.normalizeParams(o),entries:s})}});function Qe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new sl({type:"enum",entries:r,...ae.normalizeParams(e)})}var qT=w("ZodLiteral",(t,e)=>{Vg.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 qT({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}var VT=w("ZodTransform",(t,e)=>{Bg.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ae.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(ae.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 ev(t){return new VT({type:"transform",transform:t})}var tv=w("ZodOptional",(t,e)=>{Wg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new tv({type:"optional",innerType:t})}var BT=w("ZodNullable",(t,e)=>{Hg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Jy(t){return new BT({type:"nullable",innerType:t})}var WT=w("ZodDefault",(t,e)=>{Kg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function HT(t,e){return new WT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var KT=w("ZodPrefault",(t,e)=>{Jg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function JT(t,e){return new KT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var rv=w("ZodNonOptional",(t,e)=>{Gg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function GT(t,e){return new rv({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}var YT=w("ZodCatch",(t,e)=>{Yg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function XT(t,e){return new YT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var QT=w("ZodPipe",(t,e)=>{Xg.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function il(t,e){return new QT({type:"pipe",in:t,out:e})}var eE=w("ZodReadonly",(t,e)=>{Qg.init(t,e),Se.init(t,e)});function tE(t){return new eE({type:"readonly",innerType:t})}var nv=w("ZodCustom",(t,e)=>{ey.init(t,e),Se.init(t,e)});function rE(t){let e=new Fe({check:"custom"});return e._zod.check=t,e}function ov(t,e){return Oy(nv,t??(()=>!0),e)}function nE(t,e={}){return My(nv,t,e)}function oE(t){let e=rE(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.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(ae.issue(o))}},t(r.value,r)));return e}function ul(t,e){return il(ev(t),e)}ft(ty());var dl="2025-11-25";var sv=[dl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gr="io.modelcontextprotocol/related-task",Ji="2.0",Ae=ov(t=>t!==null&&(typeof t=="object"||typeof t=="function")),iv=me([b(),ce().int()]),av=b(),jq=He({ttl:me([ce(),al()]).optional(),pollInterval:ce().optional()}),sE=I({ttl:ce().optional()}),iE=I({taskId:b()}),pl=He({progressToken:iv.optional(),[gr]:iE.optional()}),at=I({_meta:pl.optional()}),ts=at.extend({task:sE.optional()}),cv=t=>ts.safeParse(t).success,Ce=I({method:b(),params:at.loose().optional()}),mt=I({_meta:pl.optional()}),ht=I({method:b(),params:mt.loose().optional()}),De=He({_meta:pl.optional()}),Gi=me([b(),ce().int()]),uv=I({jsonrpc:C(Ji),id:Gi,...Ce.shape}).strict(),fl=t=>uv.safeParse(t).success,lv=I({jsonrpc:C(Ji),...ht.shape}).strict(),dv=t=>lv.safeParse(t).success,ml=I({jsonrpc:C(Ji),id:Gi,result:De}).strict(),rs=t=>ml.safeParse(t).success;var ee;(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"})(ee||(ee={}));var hl=I({jsonrpc:C(Ji),id:Gi.optional(),error:I({code:ce().int(),message:b(),data:_e().optional()})}).strict();var pv=t=>hl.safeParse(t).success;var fv=me([uv,lv,ml,hl]),Lq=me([ml,hl]),Yi=De.strict(),aE=mt.extend({requestId:Gi.optional(),reason:b().optional()}),Xi=ht.extend({method:C("notifications/cancelled"),params:aE}),cE=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Qe(["light","dark"]).optional()}),ns=I({icons:Q(cE).optional()}),qn=I({name:b(),title:b().optional()}),mv=qn.extend({...qn.shape,...ns.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),uE=Hi(I({applyDefaults:Ee().optional()}),be(b(),_e())),lE=ul(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Hi(I({form:uE.optional(),url:Ae.optional()}),be(b(),_e()).optional())),dE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({sampling:He({createMessage:Ae.optional()}).optional(),elicitation:He({create:Ae.optional()}).optional()}).optional()}),pE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({tools:He({call:Ae.optional()}).optional()}).optional()}),fE=I({experimental:be(b(),Ae).optional(),sampling:I({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:lE.optional(),roots:I({listChanged:Ee().optional()}).optional(),tasks:dE.optional()}),mE=at.extend({protocolVersion:b(),capabilities:fE,clientInfo:mv}),gl=Ce.extend({method:C("initialize"),params:mE});var hE=I({experimental:be(b(),Ae).optional(),logging:Ae.optional(),completions:Ae.optional(),prompts:I({listChanged:Ee().optional()}).optional(),resources:I({subscribe:Ee().optional(),listChanged:Ee().optional()}).optional(),tools:I({listChanged:Ee().optional()}).optional(),tasks:pE.optional()}),gE=De.extend({protocolVersion:b(),capabilities:hE,serverInfo:mv,instructions:b().optional()}),yl=ht.extend({method:C("notifications/initialized"),params:mt.optional()});var Qi=Ce.extend({method:C("ping"),params:at.optional()}),yE=I({progress:ce(),total:xe(ce()),message:xe(b())}),vE=I({...mt.shape,...yE.shape,progressToken:iv}),ea=ht.extend({method:C("notifications/progress"),params:vE}),_E=at.extend({cursor:av.optional()}),os=Ce.extend({params:_E.optional()}),ss=De.extend({nextCursor:av.optional()}),bE=Qe(["working","input_required","completed","failed","cancelled"]),is=I({taskId:b(),status:bE,ttl:me([ce(),al()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ce()),statusMessage:xe(b())}),Vn=De.extend({task:is}),wE=mt.merge(is),as=ht.extend({method:C("notifications/tasks/status"),params:wE}),ta=Ce.extend({method:C("tasks/get"),params:at.extend({taskId:b()})}),ra=De.merge(is),na=Ce.extend({method:C("tasks/result"),params:at.extend({taskId:b()})}),Fq=De.loose(),oa=os.extend({method:C("tasks/list")}),sa=ss.extend({tasks:Q(is)}),ia=Ce.extend({method:C("tasks/cancel"),params:at.extend({taskId:b()})}),hv=De.merge(is),gv=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),yv=gv.extend({text:b()}),vl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),vv=gv.extend({blob:vl}),cs=Qe(["user","assistant"]),Bn=I({audience:Q(cs).optional(),priority:ce().min(0).max(1).optional(),lastModified:Qo.datetime({offset:!0}).optional()}),_v=I({...qn.shape,...ns.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),xE=I({...qn.shape,...ns.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),SE=os.extend({method:C("resources/list")}),$E=ss.extend({resources:Q(_v)}),kE=os.extend({method:C("resources/templates/list")}),PE=ss.extend({resourceTemplates:Q(xE)}),_l=at.extend({uri:b()}),TE=_l,EE=Ce.extend({method:C("resources/read"),params:TE}),RE=De.extend({contents:Q(me([yv,vv]))}),IE=ht.extend({method:C("notifications/resources/list_changed"),params:mt.optional()}),AE=_l,CE=Ce.extend({method:C("resources/subscribe"),params:AE}),DE=_l,zE=Ce.extend({method:C("resources/unsubscribe"),params:DE}),OE=mt.extend({uri:b()}),ME=ht.extend({method:C("notifications/resources/updated"),params:OE}),NE=I({name:b(),description:xe(b()),required:xe(Ee())}),jE=I({...qn.shape,...ns.shape,description:xe(b()),arguments:xe(Q(NE)),_meta:xe(He({}))}),LE=os.extend({method:C("prompts/list")}),FE=ss.extend({prompts:Q(jE)}),ZE=at.extend({name:b(),arguments:be(b(),b()).optional()}),UE=Ce.extend({method:C("prompts/get"),params:ZE}),bl=I({type:C("text"),text:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),wl=I({type:C("image"),data:vl,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),xl=I({type:C("audio"),data:vl,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),qE=I({type:C("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),VE=I({type:C("resource"),resource:me([yv,vv]),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),BE=_v.extend({type:C("resource_link")}),Sl=me([bl,wl,xl,BE,VE]),WE=I({role:cs,content:Sl}),HE=De.extend({description:b().optional(),messages:Q(WE)}),KE=ht.extend({method:C("notifications/prompts/list_changed"),params:mt.optional()}),JE=I({title:b().optional(),readOnlyHint:Ee().optional(),destructiveHint:Ee().optional(),idempotentHint:Ee().optional(),openWorldHint:Ee().optional()}),GE=I({taskSupport:Qe(["required","optional","forbidden"]).optional()}),bv=I({...qn.shape,...ns.shape,description:b().optional(),inputSchema:I({type:C("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()),outputSchema:I({type:C("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()).optional(),annotations:JE.optional(),execution:GE.optional(),_meta:be(b(),_e()).optional()}),$l=os.extend({method:C("tools/list")}),YE=ss.extend({tools:Q(bv)}),aa=De.extend({content:Q(Sl).default([]),structuredContent:be(b(),_e()).optional(),isError:Ee().optional()}),Zq=aa.or(De.extend({toolResult:_e()})),XE=ts.extend({name:b(),arguments:be(b(),_e()).optional()}),us=Ce.extend({method:C("tools/call"),params:XE}),QE=ht.extend({method:C("notifications/tools/list_changed"),params:mt.optional()}),Uq=I({autoRefresh:Ee().default(!0),debounceMs:ce().int().nonnegative().default(300)}),ls=Qe(["debug","info","notice","warning","error","critical","alert","emergency"]),eR=at.extend({level:ls}),kl=Ce.extend({method:C("logging/setLevel"),params:eR}),tR=mt.extend({level:ls,logger:b().optional(),data:_e()}),rR=ht.extend({method:C("notifications/message"),params:tR}),nR=I({name:b().optional()}),oR=I({hints:Q(nR).optional(),costPriority:ce().min(0).max(1).optional(),speedPriority:ce().min(0).max(1).optional(),intelligencePriority:ce().min(0).max(1).optional()}),sR=I({mode:Qe(["auto","required","none"]).optional()}),iR=I({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(Sl).default([]),structuredContent:I({}).loose().optional(),isError:Ee().optional(),_meta:be(b(),_e()).optional()}),aR=cl("type",[bl,wl,xl]),Ki=cl("type",[bl,wl,xl,qE,iR]),cR=I({role:cs,content:me([Ki,Q(Ki)]),_meta:be(b(),_e()).optional()}),uR=ts.extend({messages:Q(cR),modelPreferences:oR.optional(),systemPrompt:b().optional(),includeContext:Qe(["none","thisServer","allServers"]).optional(),temperature:ce().optional(),maxTokens:ce().int(),stopSequences:Q(b()).optional(),metadata:Ae.optional(),tools:Q(bv).optional(),toolChoice:sR.optional()}),lR=Ce.extend({method:C("sampling/createMessage"),params:uR}),Pl=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens"]).or(b())),role:cs,content:aR}),Tl=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:cs,content:me([Ki,Q(Ki)])}),dR=I({type:C("boolean"),title:b().optional(),description:b().optional(),default:Ee().optional()}),pR=I({type:C("string"),title:b().optional(),description:b().optional(),minLength:ce().optional(),maxLength:ce().optional(),format:Qe(["email","uri","date","date-time"]).optional(),default:b().optional()}),fR=I({type:Qe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ce().optional(),maximum:ce().optional(),default:ce().optional()}),mR=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),hR=I({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),gR=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),yR=me([mR,hR]),vR=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({type:C("string"),enum:Q(b())}),default:Q(b()).optional()}),_R=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({anyOf:Q(I({const:b(),title:b()}))}),default:Q(b()).optional()}),bR=me([vR,_R]),wR=me([gR,yR,bR]),xR=me([wR,dR,pR,fR]),SR=ts.extend({mode:C("form").optional(),message:b(),requestedSchema:I({type:C("object"),properties:be(b(),xR),required:Q(b()).optional()})}),$R=ts.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),kR=me([SR,$R]),PR=Ce.extend({method:C("elicitation/create"),params:kR}),TR=mt.extend({elicitationId:b()}),ER=ht.extend({method:C("notifications/elicitation/complete"),params:TR}),ca=De.extend({action:Qe(["accept","decline","cancel"]),content:ul(t=>t===null?void 0:t,be(b(),me([b(),ce(),Ee(),Q(b())])).optional())}),RR=I({type:C("ref/resource"),uri:b()});var IR=I({type:C("ref/prompt"),name:b()}),AR=at.extend({ref:me([IR,RR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),CR=Ce.extend({method:C("completion/complete"),params:AR});var DR=De.extend({completion:He({values:Q(b()).max(100),total:xe(ce().int()),hasMore:xe(Ee())})}),zR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),OR=Ce.extend({method:C("roots/list"),params:at.optional()}),El=De.extend({roots:Q(zR)}),MR=ht.extend({method:C("notifications/roots/list_changed"),params:mt.optional()}),qq=me([Qi,gl,CR,kl,UE,LE,SE,kE,EE,CE,zE,us,$l,ta,na,oa,ia]),Vq=me([Xi,ea,yl,MR,as]),Bq=me([Yi,Pl,Tl,ca,El,ra,sa,Vn]),Wq=me([Qi,lR,PR,OR,ta,na,oa,ia]),Hq=me([Xi,ea,rR,ME,IE,QE,KE,as,ER]),Kq=me([Yi,gE,DR,HE,FE,$E,PE,RE,aa,YE,ra,sa,Vn]),B=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===ee.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ll(o.elicitations,r)}return new t(e,r,n)}},ll=class extends B{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ee.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function yr(t){return t==="completed"||t==="failed"||t==="cancelled"}var xv=Symbol("Let zodToJsonSchema decide on which parser to use");var wv={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"},Sv=t=>typeof t=="string"?{...wv,name:t}:{...wv,...t};var $v=t=>{let e=Sv(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 Rl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function te(t,e,r,n,o){t[e]=r,Rl(t,e,n,o)}var ua=(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"?ua(e,t.currentPath):e.join("/")}}function kv(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&&te(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&te(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(te(r,"minItems",t.exactLength.value,t.exactLength.message,e),te(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Pv(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?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function Tv(){return{type:"boolean"}}function la(t,e){return L(t.type._def,e)}var Ev=(t,e)=>L(t.innerType._def,e);function Il(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Il(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 NR(t,e)}}var NR=(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":te(r,"minimum",n.value,n.message,e);break;case"max":te(r,"maximum",n.value,n.message,e);break}return r};function Rv(t,e){return{...L(t.innerType._def,e),default:t.defaultValue()}}function Iv(t,e){return e.effectStrategy==="input"?L(t.schema._def,e):we(e)}function Av(t){return{type:"string",enum:Array.from(t.values)}}var jR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Cv(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(jR(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 Dv(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 Al,xt={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:()=>(Al===void 0&&(Al=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Al),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 da(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":te(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":St(r,"email",n.message,e);break;case"format:idn-email":St(r,"idn-email",n.message,e);break;case"pattern:zod":Ke(r,xt.email,n.message,e);break}break;case"url":St(r,"uri",n.message,e);break;case"uuid":St(r,"uuid",n.message,e);break;case"regex":Ke(r,n.regex,n.message,e);break;case"cuid":Ke(r,xt.cuid,n.message,e);break;case"cuid2":Ke(r,xt.cuid2,n.message,e);break;case"startsWith":Ke(r,RegExp(`^${Cl(n.value,e)}`),n.message,e);break;case"endsWith":Ke(r,RegExp(`${Cl(n.value,e)}$`),n.message,e);break;case"datetime":St(r,"date-time",n.message,e);break;case"date":St(r,"date",n.message,e);break;case"time":St(r,"time",n.message,e);break;case"duration":St(r,"duration",n.message,e);break;case"length":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),te(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ke(r,RegExp(Cl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,e),n.version!=="v4"&&St(r,"ipv6",n.message,e);break}case"base64url":Ke(r,xt.base64url,n.message,e);break;case"jwt":Ke(r,xt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ke(r,xt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ke(r,xt.ipv6Cidr,n.message,e);break}case"emoji":Ke(r,xt.emoji(),n.message,e);break;case"ulid":{Ke(r,xt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{St(r,"binary",n.message,e);break}case"contentEncoding:base64":{te(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ke(r,xt.base64,n.message,e);break}}break}case"nanoid":Ke(r,xt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Cl(t,e){return e.patternStrategy==="escape"?FR(t):t}var LR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function FR(t){let e="";for(let r=0;r<t.length;r++)LR.has(t[r])||(e+="\\"),e+=t[r];return e}function St(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}}})):te(t,"format",e,r,n)}function Ke(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:zv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):te(t,"pattern",zv(e,n),r,n)}function zv(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
234
238
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
235
239
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
236
240
  `:`[${n[c]}\r
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 ua(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===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===k.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ca(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===k.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=aa(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function xv(t,e){if(e.mapStrategy==="record")return ua(t,e);let r=j(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=j(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 Sv(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 $v(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function kv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ss={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Tv(t,e){if(e.target==="openApi3")return Pv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ss&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ss[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 Pv(t,e)}var Pv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>j(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 Ev(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:ss[t.innerType._def.typeName],nullable:!0}:{type:[ss[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=j(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Rv(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 Iv(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=_R(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=j(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=vR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function vR(t,e){if(t.catchall._def.typeName!=="ZodNever")return j(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 _R(t){try{return t.isOptional()}catch{return!0}}var Av=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return j(t.innerType._def,e);let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Cv=(t,e)=>{if(e.pipeStrategy==="input")return j(t.in._def,e);if(e.pipeStrategy==="output")return j(t.out._def,e);let r=j(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=j(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Dv(t,e){return j(t.type._def,e)}function zv(t,e){let n={type:"array",uniqueItems:!0,items:j(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 Ov(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:j(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Mv(t){return{not:we(t)}}function Nv(t){return we(t)}var jv=(t,e)=>j(t.innerType._def,e);var Lv=(t,e,r)=>{switch(e){case k.ZodString:return ca(t,r);case k.ZodNumber:return Rv(t,r);case k.ZodObject:return Iv(t,r);case k.ZodBigInt:return fv(t,r);case k.ZodBoolean:return mv();case k.ZodDate:return vl(t,r);case k.ZodUndefined:return Mv(r);case k.ZodNull:return kv(r);case k.ZodArray:return pv(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Tv(t,r);case k.ZodIntersection:return _v(t,r);case k.ZodTuple:return Ov(t,r);case k.ZodRecord:return ua(t,r);case k.ZodLiteral:return bv(t,r);case k.ZodEnum:return vv(t);case k.ZodNativeEnum:return Sv(t);case k.ZodNullable:return Ev(t,r);case k.ZodOptional:return Av(t,r);case k.ZodMap:return xv(t,r);case k.ZodSet:return zv(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return Dv(t,r);case k.ZodNaN:case k.ZodNever:return $v(r);case k.ZodEffects:return yv(t,r);case k.ZodAny:return we(r);case k.ZodUnknown:return Nv(r);case k.ZodDefault:return gv(t,r);case k.ZodBranded:return aa(t,r);case k.ZodReadonly:return jv(t,r);case k.ZodCatch:return hv(t,r);case k.ZodPipeline:return Cv(t,r);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(n=>{})(e)}};function j(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==uv)return a}if(n&&!r){let a=bR(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=Lv(t,t.typeName,e),i=typeof s=="function"?j(s(),e):s;if(i&&wR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var bR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ia(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}},wR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var la=(t,e)=>{let r=dv(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:j(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=j(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=Ui(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$y(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 xR=6e4,da=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(Gi,r=>{this._oncancel(r)}),this.setNotificationHandler(Yi,r=>{this._onprogress(r)}),this.setRequestHandler(Ji,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Qi,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(ea,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(ta,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(na,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)||Xy(s)?this._onresponse(s):tl(s)?this._onrequest(s,i):Qy(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=Gy(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=x=>{l(x)};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(x){d(x);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=x=>{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(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let v=x instanceof W?x:new W(X.RequestTimeout,String(x));l(v)};this._responseHandlers.set(p,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let v=lr(r,x.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??xR,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 x=v=>{let P=this._responseHandlers.get(p);P?P(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,x),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(x=>{this._cleanupTimeout(p),l(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Xi,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},ra,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},rv,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=ts.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=ts.parse({method:"notifications/tasks/status",params:c});await this.notification(u),pr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Fv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Zv(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];Fv(i)&&Fv(s)?r[o]={...i,...s}:r[o]=s}return r}var Tw=Jp(ap(),1),Ew=Jp(Pw(),1);function pO(){let t=new Tw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ew.default)(t),t}var Ka=class{constructor(e){this._ajv=e??pO()}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 Ga=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 Rw(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 Iw(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 da{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(os.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 Ka,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=os.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ga(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zv(this._capabilities,e)}setRequestHandler(e,r){let o=Ui(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Nn(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(ns,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(oa,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){Iw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Rw(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:Wy.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"},Ki)}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},sa,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},sa,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 Cw from"node:process";var Ya=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),fO(r)}clear(){this._buffer=void 0}};function fO(t){return ev.parse(JSON.parse(t))}function Aw(t){return JSON.stringify(t)+`
239
- `}var Qa=class{constructor(e=Cw.stdin,r=Cw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ya,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=Aw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as QN}from"url";var hp={};Ze(hp,{AI_CHAT_TIMEOUT_MS:()=>Nw,getTools:()=>hO,handleTool:()=>_O});import{readFileSync as Dw}from"fs";function V(t){let e=la(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var mO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider initial analysis) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/.")}).optional(),zw=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:mO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Ow=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")}),Mw=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.")}),Nw=9e4;function hO(){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(zw)},{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(Ow)},{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(Mw)}]}async function gO(t,e){let r=zw.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:Dw(d,"utf-8")}})}),a=e.aiChatTimeoutMs??Nw,c;try{c=await Promise.race([i,new Promise((l,d)=>setTimeout(()=>d(new Error("__AI_CHAT_TIMEOUT__")),a))])}catch(l){if(z(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.
240
-
241
- **Job ID:** ${p}
242
-
243
- Use \`cli_job_status\` to check progress.`}]}}throw l}let u="";if(r.save_as_document&&e.documentManager)try{u=`
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},kind:r.save_as_document.kind})).id}`}catch(l){u=`
245
- \u26A0 Document save failed: ${z(l)}`}return{content:[{type:"text",text:`**Provider:** ${c.provider}
246
- **Model:** ${c.model}${u}
247
-
248
- ${c.text}`}]}}async function yO(t,e){let r=Ow.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=Dw(d,"utf-8");return`--- ${d} ---
249
- ${p}`}).join(`
241
+ ]`;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 pa(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}=da(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}=la(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Ov(t,e){if(e.mapStrategy==="record")return pa(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 Mv(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 Nv(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function jv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ds={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Fv(t,e){if(e.target==="openApi3")return Lv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ds&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ds[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 Lv(t,e)}var Lv=(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 Zv(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:ds[t.innerType._def.typeName],nullable:!0}:{type:[ds[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 Uv(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",Rl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function qv(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=UR(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=ZR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function ZR(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 UR(t){try{return t.isOptional()}catch{return!0}}var Vv=(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 Bv=(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 Wv(t,e){return L(t.type._def,e)}function Hv(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&te(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&te(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Kv(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 Jv(t){return{not:we(t)}}function Gv(t){return we(t)}var Yv=(t,e)=>L(t.innerType._def,e);var Xv=(t,e,r)=>{switch(e){case P.ZodString:return da(t,r);case P.ZodNumber:return Uv(t,r);case P.ZodObject:return qv(t,r);case P.ZodBigInt:return Pv(t,r);case P.ZodBoolean:return Tv();case P.ZodDate:return Il(t,r);case P.ZodUndefined:return Jv(r);case P.ZodNull:return jv(r);case P.ZodArray:return kv(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return Fv(t,r);case P.ZodIntersection:return Cv(t,r);case P.ZodTuple:return Kv(t,r);case P.ZodRecord:return pa(t,r);case P.ZodLiteral:return Dv(t,r);case P.ZodEnum:return Av(t);case P.ZodNativeEnum:return Mv(t);case P.ZodNullable:return Zv(t,r);case P.ZodOptional:return Vv(t,r);case P.ZodMap:return Ov(t,r);case P.ZodSet:return Hv(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return Wv(t,r);case P.ZodNaN:case P.ZodNever:return Nv(r);case P.ZodEffects:return Iv(t,r);case P.ZodAny:return we(r);case P.ZodUnknown:return Gv(r);case P.ZodDefault:return Rv(t,r);case P.ZodBranded:return la(t,r);case P.ZodReadonly:return Yv(t,r);case P.ZodCatch:return Ev(t,r);case P.ZodPipeline:return Bv(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!==xv)return a}if(n&&!r){let a=qR(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=Xv(t,t.typeName,e),i=typeof s=="function"?L(s(),e):s;if(i&&VR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var qR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ua(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}},VR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fa=(t,e)=>{let r=$v(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 Dl(t){let r=Bi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ny(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zl(t,e){let r=hr(t,e);if(!r.success)throw r.error;return r.data}var BR=6e4,ma=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(Xi,r=>{this._oncancel(r)}),this.setNotificationHandler(ea,r=>{this._onprogress(r)}),this.setRequestHandler(Qi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ta,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(na,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 B(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 B(ee.InvalidParams,`Task not found: ${s}`);if(!yr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(yr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[gr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(oa,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 B(ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ia,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(yr(o.status))throw new B(ee.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 B(ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof B?o:new B(ee.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),B.fromError(ee.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),rs(s)||pv(s)?this._onresponse(s):fl(s)?this._onrequest(s,i):dv(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=B.fromError(ee.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?.[gr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:ee.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=cv(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:ee.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),rs(e))n(e);else{let i=new B(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(rs(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),rs(e))o(e);else{let i=B.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 B?i:new B(ee.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Vn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new B(ee.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},yr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new B(ee.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(ee.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 B?i:new B(ee.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||{},[gr]: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(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=S instanceof B?S:new B(ee.RequestTimeout,String(S));l(y)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let y=hr(r,S.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??BR,v=()=>m(B.fromError(ee.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let S=y=>{let x=this._responseHandlers.get(p);x?x(y):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(y=>{this._cleanupTimeout(p),l(y)})}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},ra,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},sa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},hv,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||{},[gr]: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||{},[gr]: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||{},[gr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Dl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=zl(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=Dl(e);this._notificationHandlers.set(n,o=>{let s=zl(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"&&fl(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new B(ee.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 B(ee.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new B(ee.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 B(ee.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=as.parse({method:"notifications/tasks/status",params:a});await this.notification(c),yr(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 B(ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(yr(a.status))throw new B(ee.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=as.parse({method:"notifications/tasks/status",params:c});await this.notification(u),yr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Qv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function e_(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];Qv(i)&&Qv(s)?r[o]={...i,...s}:r[o]=s}return r}var Fw=uf(_p(),1),Zw=uf(Lw(),1);function OO(){let t=new Fw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Zw.default)(t),t}var Ya=class{constructor(e){this._ajv=e??OO()}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 Xa=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 Uw(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 qw(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 Qa=class extends ma{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ls.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 Ya,this.setRequestHandler(gl,n=>this._oninitialize(n)),this.setNotificationHandler(yl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(kl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ls.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Xa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=e_(this._capabilities,e)}setRequestHandler(e,r){let o=Bi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Un(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=hr(us,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new B(ee.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=hr(Vn,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new B(ee.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=hr(aa,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new B(ee.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){qw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Uw(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:sv.includes(r)?r:dl,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"},Yi)}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},Tl,r):this.request({method:"sampling/createMessage",params:e},Pl,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},ca,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},ca,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new B(ee.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof B?i:new B(ee.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},El,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 Bw from"node:process";var ec=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
242
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),MO(r)}clear(){this._buffer=void 0}};function MO(t){return fv.parse(JSON.parse(t))}function Vw(t){return JSON.stringify(t)+`
243
+ `}var tc=class{constructor(e=Bw.stdin,r=Bw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new ec,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=Vw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as $j}from"url";var Tp={};Ve(Tp,{AI_CHAT_TIMEOUT_MS:()=>Gw,getTools:()=>FO,handleTool:()=>VO});import{readFileSync as Ww}from"fs";import{join as NO}from"path";import{randomUUID as jO}from"crypto";function q(t){let e=fa(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var LO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider initial analysis) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/.")}).optional(),Hw=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"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false. Relative paths remain sandboxed either way. Audit trail is the call log \u2014 use sparingly."),save_as_document:LO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Kw=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"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false.")}),Jw=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.")}),Gw=9e4;function Yw(t,e,r){let n=`${r.tool}-${Date.now()}-${jO().slice(0,8)}`,o=NO(t,".agestra","pending-saves",`${n}.md`),s=[["id",n],["tool",r.tool],["provider",e.provider],["model",e.model],["created_at",new Date().toISOString()]];if(r.title&&s.push(["title",r.title]),r.originalTarget&&s.push(["original_target",r.originalTarget]),r.extraMetadata)for(let[a,c]of Object.entries(r.extraMetadata))c!=null&&c!==""&&s.push([a,c]);let i=["---",...s.map(([a,c])=>`${a}: ${JSON.stringify(c)}`),"---",""].join(`
244
+ `);return oe(o,i+`
245
+ `+e.text),o}function FO(){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:q(Hw)},{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:q(Kw)},{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:q(Jw)}]}async function ZO(t,e){let r=Hw.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=r.allow_external_paths?eu:Gt,a=e.aiChatTimeoutMs??Gw,c=new AbortController,u=!1,l,d=s.chat({prompt:r.prompt,model:r.model,system:r.system,workspaceBaseDir:n,signal:c.signal,files:r.files?.map(g=>{let v=i(g,n);return{path:v,content:Ww(v,"utf-8")}})});d.catch(()=>{});let p;try{p=await Promise.race([d,new Promise((g,v)=>{l=setTimeout(()=>{u=!0,c.abort(new Error("__AI_CHAT_TIMEOUT__")),v(new Error("__AI_CHAT_TIMEOUT__"))},a)})])}catch(g){if(u&&e.jobManager){let v=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5,saveAsDocument:r.save_as_document}),_=r.save_as_document?`
246
+ **Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`\u23F1 Provider "${r.provider}" timed out after ${a/1e3}s. Auto-submitted as background job.
247
+
248
+ **Job ID:** ${v}${_}
249
+
250
+ Use \`cli_job_status\` to check progress.`}]}}throw g}finally{l!==void 0&&clearTimeout(l)}let f="",m=!1;if(r.save_as_document&&e.documentManager)try{f=`
251
+ **Document ID:** ${(await e.documentManager.createDocument({title:r.save_as_document.title,content:p.text,metadata:{...r.save_as_document.metadata,Provider:p.provider,Model:p.model},kind:r.save_as_document.kind})).id}`}catch(g){m=!0;let v=z(g);try{let _=Yw(n,p,{tool:"ai_chat",title:r.save_as_document.title,extraMetadata:{kind:r.save_as_document.kind,...r.save_as_document.metadata}});f=`
252
+ \u26A0 Document save failed: ${v}
253
+ **Pending save:** ${_}`}catch(_){f=`
254
+ \u26A0 Document save failed: ${v}
255
+ \u26A0 Pending-save dump also failed: ${z(_)}`}}return{content:[{type:"text",text:`**Provider:** ${p.provider}
256
+ **Model:** ${p.model}${f}
257
+
258
+ ${p.text}`}],...m?{isError:!0}:{}}}async function UO(t,e){let r=Kw.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 i=r.allow_external_paths?eu:Gt,c=`${r.file_paths.map(p=>{let f=i(p,n),m=Ww(f,"utf-8");return`--- ${f} ---
259
+ ${m}`}).join(`
250
260
 
251
261
  `)}
252
262
 
253
263
  ---
254
264
 
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?`
265
+ Question: ${r.question}`,u=await s.chat({prompt:c,workspaceBaseDir:n}),l="",d=!1;if(r.save_to_file)try{let p=pt(r.save_to_file,n);oe(p,u.text),l=`
266
+
267
+ _Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=z(p);try{let m=Yw(n,u,{tool:"ai_analyze_files",originalTarget:r.save_to_file,extraMetadata:{question:r.question,file_paths:r.file_paths.join(", ")}});l=`
268
+
269
+ \u26A0 Save to ${r.save_to_file} failed: ${f}
270
+ **Pending save:** ${m}`}catch(m){l=`
256
271
 
257
- _Result saved to: ${r.save_to_file}_`:"";return{content:[{type:"text",text:`**Provider:** ${c.provider}
272
+ \u26A0 Save to ${r.save_to_file} failed: ${f}
273
+ \u26A0 Pending-save dump also failed: ${z(m)}`}}return{content:[{type:"text",text:`**Provider:** ${u.provider}
258
274
  **Files analyzed:** ${r.file_paths.join(", ")}
259
275
 
260
- ${c.text}${u}`}]}}async function vO(t,e){let r=Mw.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:z(u)}}})),s=`# Comparison
276
+ ${u.text}${l}`}],...d?{isError:!0}:{}}}async function qO(t,e){let r=Jw.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:z(u)}}})),s=`# Comparison
261
277
 
262
278
  **Prompt:** ${r.prompt}
263
279
 
@@ -276,44 +292,44 @@ ${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${z
276
292
 
277
293
  # Synthesis
278
294
 
279
- ${i}`),{content:[{type:"text",text:a}]}}async function _O(t,e,r){switch(t){case"ai_chat":return gO(e,r);case"ai_analyze_files":return yO(e,r);case"ai_compare":return vO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ip={};Ze(Ip,{getTools:()=>gp,handleTool:()=>Lx});var Xa=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)")}),ec=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")}),tc=h.object({session_id:h.string().describe("Session ID to check")}),rc=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)")}),nc=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.")}),oc=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")}),sc=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")}),ic=h.object({task_id:h.string().describe("Task ID to review changes for")}),ac=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),cc=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),jw=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()}),uc=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.")}),lc=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'.")}),dc=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.")}),pc=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 fc="agent_debate_structured",no="agent_debate_approve",oo="agent_debate_continue",so="agent_debate_reject";function mc(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 Lw(t,e){let r=mc(e);if(r)return r;let n;try{n=uc.parse(t)}catch(s){return Xt(`Invalid arguments: ${z(s)}`)}let o=bO(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(qw(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(Bw(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(Vw(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
295
+ ${i}`),{content:[{type:"text",text:a}]}}async function VO(t,e,r){switch(t){case"ai_chat":return ZO(e,r);case"ai_analyze_files":return UO(e,r);case"ai_compare":return qO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Up={};Ve(Up,{getTools:()=>Ep,handleTool:()=>Qx});var rc=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)")}),nc=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")}),oc=h.object({session_id:h.string().describe("Session ID to check")}),sc=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)")}),ic=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.")}),ac=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")}),cc=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")}),uc=h.object({task_id:h.string().describe("Task ID to review changes for")}),lc=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),dc=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),Xw=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()}),pc=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.")}),fc=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'.")}),mc=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.")}),hc=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 gc="agent_debate_structured",co="agent_debate_approve",uo="agent_debate_continue",lo="agent_debate_reject";function yc(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 Qw(t,e){let r=yc(e);if(r)return r;let n;try{n=pc.parse(t)}catch(s){return sr(`Invalid arguments: ${z(s)}`)}let o=BO(n.leader,n.participants,e);if(!o)return sr("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(nx(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(sx(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(ox(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
280
296
 
281
- `)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return Xt(`Failed to start structured debate: ${z(s)}`)}}async function Fw(t,e){let r=mc(e);if(r)return r;let n;try{n=lc.parse(t)}catch(o){return Xt(`Invalid arguments: ${z(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(`
297
+ `)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return sr(`Failed to start structured debate: ${z(s)}`)}}async function ex(t,e){let r=yc(e);if(r)return r;let n;try{n=fc.parse(t)}catch(o){return sr(`Invalid arguments: ${z(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(`
282
298
 
283
- `)}]}}catch(o){return Xt(`Approve failed: ${z(o)}`)}}async function Zw(t,e){let r=mc(e);if(r)return r;let n;try{n=dc.parse(t)}catch(o){return Xt(`Invalid arguments: ${z(o)}`)}try{let o=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds}),s=[o.terminalReport];return s.push(qw(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(Bw(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(Vw(n.session_id)),{content:[{type:"text",text:s.join(`
299
+ `)}]}}catch(o){return sr(`Approve failed: ${z(o)}`)}}async function tx(t,e){let r=yc(e);if(r)return r;let n;try{n=mc.parse(t)}catch(o){return sr(`Invalid arguments: ${z(o)}`)}try{let o=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds}),s=[o.terminalReport];return s.push(nx(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(sx(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(ox(n.session_id)),{content:[{type:"text",text:s.join(`
284
300
 
285
- `)}]}}catch(o){return Xt(`Continue failed: ${z(o)}`)}}async function Uw(t,e){let r=mc(e);if(r)return r;let n;try{n=pc.parse(t)}catch(o){return Xt(`Invalid arguments: ${z(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: ${z(o)}`)}}function bO(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 qw(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function Vw(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 Bw(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(Xa)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:V(tc)},{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(ec)},{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(rc)},{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(nc)},{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(oc)},{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(sc)},{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(ic)},{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(ac)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:V(cc)},{name:fc,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(uc)},{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(lc)},{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(dc)},{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(pc)}]}import{readFileSync as xO}from"fs";import{join as Yw}from"path";function Ww(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 hc="claude-reviewer",gc="claude-qa",wO={"agestra-reviewer":hc,"agestra-qa":gc};function Hw(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=Ww(e,r),u=c!==null?wO[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",SO=new Set([hc,gc]),bp=Object.freeze({[hc]:"agestra-reviewer",[gc]:"agestra-qa"});function $O(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
301
+ `)}]}}catch(o){return sr(`Continue failed: ${z(o)}`)}}async function rx(t,e){let r=yc(e);if(r)return r;let n;try{n=hc.parse(t)}catch(o){return sr(`Invalid arguments: ${z(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(`
302
+ `)}]}}catch(o){return sr(`Reject failed: ${z(o)}`)}}function BO(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 nx(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function ox(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${co}\` with { session_id: "${t}" }`,`- Extend debate: call \`${uo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${lo}\` with { session_id: "${t}" }`].join(`
303
+ `)}function sx(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${uo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${co}\` to accept the current synthesis with open items captured.`,`- \`${lo}\` to abandon the session.`,`Session ID: ${t}`].join(`
304
+ `)}function sr(t){return{content:[{type:"text",text:t}],isError:!0}}function Ep(){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:q(rc)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:q(oc)},{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:q(nc)},{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:q(sc)},{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:q(ic)},{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:q(ac)},{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:q(cc)},{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:q(uc)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:q(lc)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:q(dc)},{name:gc,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:q(pc)},{name:co,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:q(fc)},{name:uo,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:q(mc)},{name:lo,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:q(hc)}]}import{readFileSync as HO}from"fs";import{join as dx}from"path";function ix(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 vc="claude-reviewer",_c="claude-qa",WO={"agestra-reviewer":vc,"agestra-qa":_c};function ax(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=ix(e,r),u=c!==null?WO[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 Ip="claude",Ap="claude-cli",KO=new Set([vc,_c]),Cp=Object.freeze({[vc]:"agestra-reviewer",[_c]:"agestra-qa"});function JO(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
289
305
  `,3);if(e<0)return t;let r=t.indexOf(`
290
306
  ---`,e);if(r<0)return t;let n=t.indexOf(`
291
- `,r+4);return n<0?"":t.slice(n+1)}function kO(t,e){return SO.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 Kw(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var Gw=18e4;function yp(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${Gw/1e3}s)`)),Gw))])}function Jw(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=Yw(r,`${s}.md`);try{let a=$O(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??Yw(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>xO(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=Jw(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:Kw(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?Jw(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:Kw(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,z(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=kO(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 Qw(t){return new wp(t)}function Xw(t,e){return e(t)}var PO=/[.,!?;:]/g,TO=/\s+/g;function ex(t){return t.toLowerCase().replace(PO," ").replace(TO," ").trim()}function tx(t){return typeof t.location=="string"&&t.location.length>0}function rx(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 EO(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 RO(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=ex(t.title)===ex(e.title),s=t.severity===e.severity,a=tx(t)&&tx(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=rx(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=IO(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(EO(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=rx(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 IO(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function nx(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=RO(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 AO=new Set(df);function CO(t){return AO.has(t)}var DO=new Set(["disagree","revise"]);function zO(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 OO(t){let e=`<${ln}>`;return t.includes(e)}var MO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function NO(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 MO[r]??e})}function jO(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]=NO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function xp(t,e){let r=zO(t);if(!r)return OO(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(!ox(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(!ox(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=jO(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(!CO(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(DO.has(g)&&_===void 0){d.add(m),l.push({proposalId:m,reason:"missing-reason",raw:p.raw});continue}d.add(m);let x={proposalId:m,vote:g};_!==void 0&&(x.reason=_),u.push(x)}return{ok:!0,entries:u,entryErrors:l}}function ox(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var LO=Object.freeze(["same","different","unsure"]),Os="alias-votes",FO=new Set(LO);function ZO(t){return FO.has(t)}function UO(t){let e=`<${Os}>`,r=`</${Os}>`,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 qO(t){let e=`<${Os}>`;return t.includes(e)}var VO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function BO(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 VO[r]??e})}function WO(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]=BO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function sx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Sp(t,e){let r=UO(t);if(!r)return qO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Os}> without matching </${Os}>`}}:{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(!sx(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(!sx(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=WO(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(!ZO(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 x={pair:m,vote:g};_!==void 0&&(x.reason=_),u.push(x)}return{ok:!0,entries:u,entryErrors:l}}var HO="__";function KO(t){return`${t.proposalA}${HO}${t.proposalB}`}var GO=["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(" "),JO=["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(" "),YO=["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
- `),QO="Candidate pairs:";function XO(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 lx(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(KO),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=eM(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:ux(m.reason)}),yc(l,s);continue}let{response:y}=m.value;if(y.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),yc(l,s);continue}let _=Sp(y.text,s),x=new Set;if(!_.ok){let v=await n(g,XO(s,_.error.details!==void 0?`${_.error.kind}: ${_.error.details}`:_.error.kind)).catch(S=>({text:"",failed:!0,reason:ux(S)}));if(v.failed===!0){u.push({participantId:g,reason:"reason"in v&&typeof v.reason=="string"?v.reason:"retry failed"}),yc(l,s);continue}let P=Sp(v.text,s);if(!P.ok){u.push({participantId:g,reason:P.error.details!==void 0?`${P.error.kind}: ${P.error.details}`:P.error.kind}),yc(l,s);continue}for(let S of P.entries)cx(l,S),x.add(S.pair);for(let S of s)if(!x.has(S)){let N=l.get(S);N!==void 0&&(N.missing+=1)}continue}for(let v of _.entries)cx(l,v),x.add(v.pair);for(let v of s)if(!x.has(v)){let P=l.get(v);P!==void 0&&(P.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=rM(g);if(y.kind==="merge"){let _=m.proposalA,x=m.proposalB;if(e.proposals.get(_)===void 0||e.proposals.get(x)===void 0)continue;e.applyAliasMerge(_,x),d.push({primary:_,alias:x,voteBreakdown:{...g}});continue}p.push({pair:m,voteBreakdown:{...g},reason:y.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function eM(t,e,r){let n=[];n.push(GO),n.push(""),n.push(JO),n.push(""),n.push(QO),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:"),ix(n,a),n.push(" Proposal B:"),ix(n,c),n.push("")}return n.push(YO),n.join(`
294
- `)}function ix(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=tM(e.description);t.push(` description: ${r}`)}}var ax=400;function tM(t){return t.length<=ax?t:`${t.slice(0,ax)}\u2026`}function cx(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 yc(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function rM(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 ux(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as nM}from"fs/promises";import{readFileSync as oM,existsSync as $p,unlinkSync as sM,mkdirSync as iM}from"fs";import{join as Ms}from"path";var Pp=".approval.json";function kp(t){return`${t}${Pp}`}function aM(t){return t.endsWith(Pp)?t.slice(0,t.length-Pp.length):null}function dx(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+pf).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=Ms(e,qs)}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}`);iM(this.debatesDir,{recursive:!0});let r=Ms(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=Ms(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=Ms(this.debatesDir,kp(e));if($p(r))try{sM(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 nM(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=aM(r);if(!n)continue;let o=this.readSnapshotFile(Ms(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=oM(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 cM(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function cM(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 uM(t,e){let r=[];r.push(...pM(t,e)),r.push(""),r.push(...fx(t,e));let n=mx(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...hx(t,e)),r.push(""),r.push(...mM(t,e)),r.join(`
295
- `)}function lM(t,e){let r=[];r.push(...fx(t,e));let n=hM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=gM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=yM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=mx(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...hx(t,e)),r.join(`
296
- `)}function px(){return{renderTerminal:uM,renderSynthesis:lM}}var dM=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 pM(t,e){let r=e.t(dM[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 fx(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=fM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function fM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function mx(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 hx(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 mM(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 hM(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 gM(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 yM(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=px();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??vM)(),n=this.nowIso(),o=Hw({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}=nx(u);c.ledger=l,c.nextProposalIndex=kM(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,gx(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",vc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:vc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:vc(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):vx(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??_c(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=gx(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??_c(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:$M(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=_c(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=CM(),o=DM(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=AM(u.text);for(let f of p){let m=yx(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 lx({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=jM(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:zM({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"?vc(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,MM(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(bM(p.tally,m)){e.ledger.setStatus(p.proposalId,"consensus"),e.allAbstainCount.delete(p.proposalId);continue}if(wM(p.tally,m)){e.ledger.setStatus(p.proposalId,"rejected"),e.allAbstainCount.delete(p.proposalId);continue}if(xM(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:NM({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:OM({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}
307
+ `,r+4);return n<0?"":t.slice(n+1)}function GO(t,e){return KO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:Cp[t]}:{transport:"cli-bridge",providerId:Ap,agentName:Cp[t]}:t===Ip?e==="claude-code"?{transport:"read-only-chat",providerId:Ip}:{transport:"cli-bridge",providerId:Ap}:{transport:"read-only-chat",providerId:t}}function cx(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var ux=18e4;function Rp(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${ux/1e3}s)`)),ux))])}function lx(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=Cp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=dx(r,`${s}.md`);try{let a=JO(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var Dp=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??dx(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>HO(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 Rp(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??Ap,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=lx(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await Rp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:cx(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?lx(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await Rp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:cx(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,z(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=GO(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:Ip,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 px(t){return new Dp(t)}function fx(t,e){return e(t)}var YO=/[.,!?;:]/g,XO=/\s+/g;function mx(t){return t.toLowerCase().replace(YO," ").replace(XO," ").trim()}function hx(t){return typeof t.location=="string"&&t.location.length>0}function gx(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 QO(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 eM(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=mx(t.title)===mx(e.title),s=t.severity===e.severity,a=hx(t)&&hx(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 po=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=gx(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=tM(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(QO(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=gx(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 tM(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function yx(t){let e=new po,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=eM(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 rM=new Set(Sf);function nM(t){return rM.has(t)}var oM=new Set(["disagree","revise"]);function sM(t){let e=`<${gn}>`,r=`</${gn}>`,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 iM(t){let e=`<${gn}>`;return t.includes(e)}var aM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function cM(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 aM[r]??e})}function uM(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]=cM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function zp(t,e){let r=sM(t);if(!r)return iM(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${gn}> without matching </${gn}>`}}:{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(!vx(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(!vx(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=uM(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(!nM(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 v=f.reason,_=typeof v=="string"&&v.length>0?v:void 0;if(oM.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 vx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var lM=Object.freeze(["same","different","unsure"]),Zs="alias-votes",dM=new Set(lM);function pM(t){return dM.has(t)}function fM(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 mM(t){let e=`<${Zs}>`;return t.includes(e)}var hM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function gM(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 hM[r]??e})}function yM(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]=gM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function _x(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Op(t,e){let r=fM(t);if(!r)return mM(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(!_x(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(!_x(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=yM(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(!pM(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 v=f.reason,_=typeof v=="string"&&v.length>0?v: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 vM="__";function _M(t){return`${t.proposalA}${vM}${t.proposalB}`}var bM=["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(" "),wM=["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(" "),xM=["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(`
308
+ `),SM="Candidate pairs:";function $M(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(`
309
+ `)}async function $x(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(_M),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=kM(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)}),bc(l,s);continue}let{response:v}=m.value;if(v.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),bc(l,s);continue}let _=Op(v.text,s),S=new Set;if(!_.ok){let y=await n(g,$M(s,_.error.details!==void 0?`${_.error.kind}: ${_.error.details}`:_.error.kind)).catch($=>({text:"",failed:!0,reason:Sx($)}));if(y.failed===!0){u.push({participantId:g,reason:"reason"in y&&typeof y.reason=="string"?y.reason:"retry failed"}),bc(l,s);continue}let x=Op(y.text,s);if(!x.ok){u.push({participantId:g,reason:x.error.details!==void 0?`${x.error.kind}: ${x.error.details}`:x.error.kind}),bc(l,s);continue}for(let $ of x.entries)xx(l,$),S.add($.pair);for(let $ of s)if(!S.has($)){let M=l.get($);M!==void 0&&(M.missing+=1)}continue}for(let y of _.entries)xx(l,y),S.add(y.pair);for(let y of s)if(!S.has(y)){let x=l.get(y);x!==void 0&&(x.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 v=TM(g);if(v.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:v.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function kM(t,e,r){let n=[];n.push(bM),n.push(""),n.push(wM),n.push(""),n.push(SM),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:"),bx(n,a),n.push(" Proposal B:"),bx(n,c),n.push("")}return n.push(xM),n.join(`
310
+ `)}function bx(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=PM(e.description);t.push(` description: ${r}`)}}var wx=400;function PM(t){return t.length<=wx?t:`${t.slice(0,wx)}\u2026`}function xx(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 bc(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function TM(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 EM}from"fs/promises";import{readFileSync as RM,existsSync as Mp,unlinkSync as IM,mkdirSync as AM}from"fs";import{join as Us}from"path";var jp=".approval.json";function Np(t){return`${t}${jp}`}function CM(t){return t.endsWith(jp)?t.slice(0,t.length-jp.length):null}function kx(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+$f).toISOString()}var fo=class{debatesDir;cache=new Map;hydrated=!1;constructor(e){if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=Us(e,Hs)}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}`);AM(this.debatesDir,{recursive:!0});let r=Us(this.debatesDir,Np(e.sessionId));je(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=Us(this.debatesDir,Np(e));if(!Mp(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=Us(this.debatesDir,Np(e));if(Mp(r))try{IM(r)}catch(n){if(n.code!=="ENOENT")throw n}}async hydrateFromDisk(){if(this.cache.clear(),!Mp(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await EM(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=CM(r);if(!n)continue;let o=this.readSnapshotFile(Us(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=[],o=[];for(let s of this.cache.values()){if(s.status!=="ready-for-approval")continue;let i=Date.parse(s.deadline);if(Number.isNaN(i)||r<=i)continue;let a={...s,status:"leader-timeout",terminalNote:s.terminalNote??"leader-timeout after approval window"};try{await this.persist(a),n.push(a)}catch(c){o.push({sessionId:s.sessionId,error:c})}}return o.length>0&&console.warn(`[session-registry] sweepTimeouts: ${o.length} snapshot(s) failed to transition; will retry on next sweep`,o.map(s=>({sessionId:s.sessionId,message:s.error instanceof Error?s.error.message:String(s.error)}))),n}isHydrated(){return this.hydrated}readSnapshotFile(e){let r;try{r=RM(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 DM(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function DM(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 zM(t,e){let r=[];r.push(...NM(t,e)),r.push(""),r.push(...Tx(t,e));let n=Ex(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...Rx(t,e)),r.push(""),r.push(...LM(t,e)),r.join(`
311
+ `)}function OM(t,e){let r=[];r.push(...Tx(t,e));let n=FM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=ZM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=UM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=Ex(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...Rx(t,e)),r.join(`
312
+ `)}function Px(){return{renderTerminal:zM,renderSynthesis:OM}}var MM=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 NM(t,e){let r=e.t(MM[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 Tx(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=jM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function jM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function Ex(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(Lp(o))}return r}function Lp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function Rx(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 LM(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 FM(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 ZM(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(Lp(s))}return n}function UM(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(Lp(s))}return n}var mo=class{deps;sessions=new Map;formatter=Px();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??qM)(),n=this.nowIso(),o=ax({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??Nc,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 po,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}=yx(u);c.ledger=l,c.nextProposalIndex=GM(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,Ix(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",wc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:wc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:wc(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}}Fp(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?this.buildReportData(n,r,e.leaderNote):Cx(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??xc(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);Fp(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=Ix(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}:{}};Fp(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??xc(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:JM(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=xc(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=nN(),o=oN(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=rN(u.text);for(let f of p){let m=Ax(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 $x({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=uN(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:sN({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 v=f.status==="rejected"?wc(f.reason):f.value.resp.failureReason??"unknown";u.push({participantId:m,text:`(no response: ${v})`,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 v of g.parsed.entries)e.ledger.recordVote(v.proposalId,m,{vote:v.vote,roundRecorded:n,...v.reason!==void 0?{reason:v.reason}:{}});g.parsed.entryErrors.length>0&&a.set(m,aN(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(BM(p.tally,m)){e.ledger.setStatus(p.proposalId,"consensus"),e.allAbstainCount.delete(p.proposalId);continue}if(WM(p.tally,m)){e.ledger.setStatus(p.proposalId,"rejected"),e.allAbstainCount.delete(p.proposalId);continue}if(HM(p.tally)){let g=(e.allAbstainCount.get(p.proposalId)??0)+1;e.allAbstainCount.set(p.proposalId,g),g>=Lc&&(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:cN({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=zp(n,i);if(a.ok)return{ok:!0,parsed:a,displayText:n};let c={prompt:iN({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
313
 
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}
314
+ [retry failed: ${u.failureReason??"unknown"}]`,warnings:[`Missing or malformed <votes> block (${a.error.kind}). Retry failed: ${u.failureReason??"unknown"}.`]};let l=zp(u.text,i),d=`${n}
299
315
 
300
316
  [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=yx(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:_c(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=_M(r)?Xw(o,dx):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:SM(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){let n=e?this.buildReportData(e,r):vx(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=PM(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=TM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:_x(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}
317
+ ${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>=jc&&e.unavailableParticipants.add(r)}clearFailure(e,r){e.consecutiveFailures.delete(r)}synthesizeReviseSuccessor(e,r,n){let o=Ax(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=po.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:xc(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=VM(r)?fx(o,kx):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:KM(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){let n=e?this.buildReportData(e,r):Cx(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=YM(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=XM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:Dx(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
318
 
303
319
  **${n}:** ${e}`}formatRejectionFooter(e){let r=this.deps.i18n.t("moderator.narration.rejected");return e?`${r}
304
320
 
305
321
  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
322
 
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 vM(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function gx(t){for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function _M(t){return t==="ready-for-approval"||t==="escalated"}function bM(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 wM(t,e){if(e===0||t.agree>0||t.revise>0)return!1;let r=Math.ceil(e/2);return t.disagree>=r}function xM(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 SM(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 _x(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 vc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function _c(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function $M(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 kM(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 yx(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function PM(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 TM(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 vx(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:_x(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 EM=/<proposals>([\s\S]*?)<\/proposals>/i,RM=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,IM=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function AM(t){let e=EM.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(RM.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp(IM.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 CM(){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 DM(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 zM(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 OM(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 MM(t){return t.map(e=>`${e.proposalId??"unparsed entry"}: ${e.reason}`)}function NM(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 jM(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 bx=18e4;function js(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${bx/1e3}s)`)),bx))])}function Sx(t){return new Rn({tools:$i(),baseDir:t})}var Rp,wx;function $x(t){return(!Rp||wx!==t)&&(Rp=new To,wx=t),Rp}var Ns;function bc(t,e){if(Ns&&Ns.registry===t&&Ns.hostKind===e)return Ns.bridge;let r=new Rn({tools:$i(),baseDir:process.cwd()}),n=Qw({registry:t,readOnlyAdapter:r,hostKind:e});return Ns={bridge:n,registry:t,hostKind:e},n}var xx=new Map;function kx(t){let e=xx.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 xx.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function Px(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=Co(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 wc(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function Tx(t,e){let r=Xa.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+=`
323
+ ${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 qM(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function Ix(t){for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function VM(t){return t==="ready-for-approval"||t==="escalated"}function BM(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 WM(t,e){if(e===0||t.agree>0||t.revise>0)return!1;let r=Math.ceil(e/2);return t.disagree>=r}function HM(t){return t.abstain>0&&t.agree===0&&t.disagree===0&&t.revise===0&&t.missing===0}function Fp(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 KM(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 Dx(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 wc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function xc(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function JM(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 GM(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 Ax(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function YM(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 XM(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 Cx(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:Dx(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 QM=/<proposals>([\s\S]*?)<\/proposals>/i,eN=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,tN=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function rN(t){let e=QM.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(eN.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp(tN.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 nN(){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(`
324
+ `)}function oN(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(`
325
+ `)}function sN(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(`
326
+ `)}function iN(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(`
327
+ `)}function aN(t){return t.map(e=>`${e.proposalId??"unparsed entry"}: ${e.reason}`)}function cN(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(`
328
+ `)}function uN(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(`
329
+ `)}var zx=18e4;function Vs(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${zx/1e3}s)`)),zx))])}function Nx(t){return new On({tools:Ti(),baseDir:t})}var Zp,Ox;function jx(t){return(!Zp||Ox!==t)&&(Zp=new Do,Ox=t),Zp}var qs;function Sc(t,e){if(qs&&qs.registry===t&&qs.hostKind===e)return qs.bridge;let r=new On({tools:Ti(),baseDir:process.cwd()}),n=px({registry:t,readOnlyAdapter:r,hostKind:e});return qs={bridge:n,registry:t,hostKind:e},n}var Mx=new Map;function Lx(t){let e=Mx.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new mo({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return Mx.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function Fx(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=jo(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 $c(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function Zx(t,e){let r=rc.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+=`
314
330
 
315
331
  Validator feedback from previous round:
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}"
332
+ ${l}`);let v=await Vs(e.readOnlyAdapter.chat(m,{prompt:g}),f);s.addTurn(i.id,f,v.text)}if(a&&c&&p+1>=u){let f=s.buildTurnTranscript(i.id),m=`Evaluate this debate against the goal: "${r.goal}"
317
333
 
318
334
  Current discussion:
319
335
  ${f}
@@ -325,12 +341,12 @@ Respond in JSON:
325
341
  "accuracy": true/false,
326
342
  "consistency": true/false,
327
343
  "feedback": "..."
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=wc(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=z(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
344
+ }`,g=await Vs(e.readOnlyAdapter.chat(c,{prompt:m}),c.id);try{let v=JSON.parse(g.text);if(v.goalAchievement&&v.completeness&&v.accuracy&&v.consistency)break;l=String(v.feedback??"")}catch{l=g.text}}}let d=$c(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=z(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
329
345
  **Session ID:** ${o.id}
330
346
  **Topic:** ${r.topic}
331
347
  **Participants:** ${r.providers.join(", ")}
332
348
 
333
- Use \`agent_debate_status\` to check progress.`}]}}async function Ex(t,e){let r=tc.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}
349
+ Use \`agent_debate_status\` to check progress.`}]}}async function Ux(t,e){let r=oc.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}
334
350
  **Type:** ${n.type}
335
351
  **Status:** ${n.status}
336
352
  **Created:** ${n.createdAt}
@@ -340,7 +356,7 @@ Use \`agent_debate_status\` to check progress.`}]}}async function Ex(t,e){let r=
340
356
 
341
357
  ---
342
358
 
343
- ${n.result}`),{content:[{type:"text",text:o}]}}async function Rx(t,e){let r=ec.parse(t),n=new Ro(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"}**
359
+ ${n.result}`),{content:[{type:"text",text:o}]}}async function qx(t,e){let r=nc.parse(t),n=new Oo(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"}**
344
360
 
345
361
  `;for(let i of o.reviews)s+=`### ${i.targetProvider} reviewed by ${i.reviewerProvider}
346
362
  `,s+=`**Result:** ${i.passed?"PASS":"FAIL"}
@@ -350,13 +366,13 @@ ${n.result}`),{content:[{type:"text",text:o}]}}async function Rx(t,e){let r=ec.p
350
366
  `;return o.conflicts.length>0&&(s+=`## Conflicts
351
367
  ${o.conflicts.map(i=>`- ${i}`).join(`
352
368
  `)}
353
- `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${z(o)}`}],isError:!0}}}async function Ix(t,e){let r=rc.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**
369
+ `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${z(o)}`}],isError:!0}}}async function Vx(t,e){let r=sc.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**
354
370
  **Debate ID:** ${e.debateEngine.create({topic:r.topic,providerIds:r.providers,goal:r.goal,documentId:n}).id}
355
371
  **Topic:** ${r.topic}
356
372
  **Participants:** ${r.providers.join(", ")}${n?`
357
- **Document ID:** ${n}`:""}`}]}}async function Ax(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};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=z(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=Co(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}
373
+ **Document ID:** ${n}`:""}`}]}}async function Bx(t,e){let r=ic.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=z(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=jo(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}
358
374
 
359
- _Quality: ${d.score.toFixed(2)}_`}]}}async function Cx(t,e){let r=oc.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}=Px(n,e.traceWriter,r.quality_scores),s=wc(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
375
+ _Quality: ${d.score.toFixed(2)}_`}]}}async function Wx(t,e){let r=ac.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}=Fx(n,e.traceWriter,r.quality_scores),s=$c(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
360
376
  **Debate ID:** ${r.debate_id}
361
377
  **Topic:** ${n.topic}
362
378
  **Turns:** ${n.turns.length}`;return n.documentId&&(i+=`
@@ -364,13 +380,13 @@ _Quality: ${d.score.toFixed(2)}_`}]}}async function Cx(t,e){let r=oc.parse(t),n=
364
380
 
365
381
  ---
366
382
 
367
- ${s}`,{content:[{type:"text",text:i}]}}async function Dx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function xc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function Sc(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
383
+ ${s}`,{content:[{type:"text",text:i}]}}async function Hx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function kc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function Pc(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
368
384
 
369
385
  **Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
370
386
 
371
387
  **Raw response:**
372
388
 
373
- ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function zx(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
389
+ ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function Kx(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
374
390
 
375
391
  Parent document: ${e}${r?`
376
392
  Debate ID: ${r}`:""}
@@ -381,27 +397,27 @@ ${n}`});let i=o.rawResponse?`
381
397
 
382
398
  **Raw response:**
383
399
 
384
- ${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${xc(o.outcome)}**
400
+ ${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${kc(o.outcome)}**
385
401
 
386
- ${Sc(o.outcome)}${i}`}),s.id}function LM(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
387
- ${hf}`}function FM(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=jw.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 Ox(t,e){let r=sc.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)),x=[];for(let v of n)if(v==="claude"||_.has(v))x.push(v);else{let P=(s.unavailableProviders??[]).find(S=>S.providerId===v);o.push({id:v,reason:P?`Marked unavailable for this debate: ${P.reason}`:"Not currently active in this debate."})}n=x}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=LM(r.review_prompt),u=[],l=n.map(async _=>{if(_==="claude")return null;let x=e.registry.get(_),v=`${c}
402
+ ${Pc(o.outcome)}${i}`}),s.id}function lN(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
403
+ ${Tf}`}function dN(t){let e=zn(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=Xw.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 Jx(t,e){let r=cc.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 y of n)if(y==="claude"||_.has(y))S.push(y);else{let x=(s.unavailableProviders??[]).find($=>$.providerId===y);o.push({id:y,reason:x?`Marked unavailable for this debate: ${x.reason}`:"Not currently active in this debate."})}n=S}let a=o.length===0?"":`
404
+ **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=lN(r.review_prompt),u=[],l=n.map(async _=>{if(_==="claude")return null;let S=e.registry.get(_),y=`${c}
389
405
 
390
406
  ---
391
407
 
392
- ${r.document}`,P,S;try{let L=await js(e.readOnlyAdapter.chat(x,{prompt:v}),_);P=L.text,S=FM(L.text)}catch(L){let Z=z(L);if(S={kind:"unavailable",reason:Z},r.debate_id&&s){let De=L instanceof me?`Provider reported unavailable: ${Z}`:`Chat failed: ${Z}`;e.debateEngine.markProviderUnavailable(r.debate_id,_,De),s=e.debateEngine.getState(r.debate_id)}}let N={provider:_,outcome:S,rawResponse:P};if(N.linkedDocumentId=await zx(e,i,r.debate_id,r.document,N),i){let L=Sc(N.outcome),Z=N.linkedDocumentId?`
408
+ ${r.document}`,x,$;try{let O=await Vs(e.readOnlyAdapter.chat(S,{prompt:y}),_);x=O.text,$=dN(O.text)}catch(O){let Y=z(O);if($={kind:"unavailable",reason:Y},r.debate_id&&s){let Pe=O instanceof de?`Provider reported unavailable: ${Y}`:`Chat failed: ${Y}`;e.debateEngine.markProviderUnavailable(r.debate_id,_,Pe),s=e.debateEngine.getState(r.debate_id)}}let M={provider:_,outcome:$,rawResponse:x};if(M.linkedDocumentId=await Kx(e,i,r.debate_id,r.document,M),i){let O=Pc(M.outcome),Y=M.linkedDocumentId?`
393
409
 
394
- **Independent review document:** ${N.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${_} (review)`,content:`**${xc(N.outcome)}**
410
+ **Independent review document:** ${M.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${_} (review)`,content:`**${kc(M.outcome)}**
395
411
 
396
- ${L}${Z}`})}return N}),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}
412
+ ${O}${Y}`})}return M}),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"),v=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
397
413
 
398
- `;for(let _ of u)y+=`### ${_.provider}: ${xc(_.outcome)}
399
- `,y+=`${Sc(_.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+=`---
414
+ `;for(let _ of u)v+=`### ${_.provider}: ${kc(_.outcome)}
415
+ `,v+=`${Pc(_.outcome)}
416
+ `,_.linkedDocumentId&&(v+=`**Independent review document:** ${_.linkedDocumentId}
417
+ `),v+=`
418
+ `;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.";v+=`---
403
419
 
404
- **Next step:** ${_}`}return await Dx(e,i,"Moderator (Review Aggregation)",y),{content:[{type:"text",text:y}]}}async function Mx(t,e){let r=ic.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:z(s)}],isError:!0}}let o=`**File Change Review**
420
+ **Next step:** ${_}`}return await Hx(e,i,"Moderator (Review Aggregation)",v),{content:[{type:"text",text:v}]}}async function Gx(t,e){let r=uc.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:z(s)}],isError:!0}}let o=`**File Change Review**
405
421
  **Task ID:** ${r.task_id}
406
422
  **Worktree:** ${n.worktreePath}
407
423
  **Branch:** ${n.branch}
@@ -415,25 +431,25 @@ ${n.diffStat}
415
431
  ### Changes
416
432
  \`\`\`diff
417
433
  ${n.fullDiff}
418
- \`\`\``,{content:[{type:"text",text:o}]}}async function Nx(t,e){let r=ac.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**
434
+ \`\`\``,{content:[{type:"text",text:o}]}}async function Yx(t,e){let r=lc.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**
419
435
  **Task ID:** ${r.task_id}
420
436
  **Merged files:** ${n.merged.length}
421
437
 
422
438
  ${n.merged.map(o=>`- ${o}`).join(`
423
- `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${z(n)}`}],isError:!0}}}async function jx(t,e){let r=cc.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:z(o)}],isError:!0}}let n=`**Changes rejected**
439
+ `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${z(n)}`}],isError:!0}}}async function Xx(t,e){let r=dc.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:z(o)}],isError:!0}}let n=`**Changes rejected**
424
440
  **Task ID:** ${r.task_id}`;return r.reason&&(n+=`
425
- **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as ZM}from"path";var UM="unknown";async function Lx(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new ao(ZM(n,mo)),s=bc(r.registry,r.sessionContext?.hostKind??UM),i=r.moderatorEngine??kx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:$x(n),readOnlyAdapter:Sx(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return Tx(e,a);case"agent_debate_status":return Ex(e,a);case"agent_cross_validate":return Rx(e,a);case"agent_debate_create":return Ix(e,a);case"agent_debate_turn":return Ax(e,a);case"agent_debate_conclude":return Cx(e,a);case"agent_debate_review":return Ox(e,a);case"agent_changes_review":return Mx(e,a);case"agent_changes_accept":return Nx(e,a);case"agent_changes_reject":return jx(e,a);case fc:return Lw(e,a);case no:return Fw(e,a);case oo:return Zw(e,a);case so:return Uw(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ap={};Ze(Ap,{getTools:()=>qM,handleTool:()=>YM});var Fx=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")}),Zx=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")}),Ux=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),qx=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")}),Vx=h.object({doc_id:h.string().describe("Document ID to read")}),Bx=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)"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider independent work) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/. Always pass an explicit kind for idea/review workflows so the workspace tree stays sorted.")}),Wx=h.object({});function qM(){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(Fx)},{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(Zx)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:V(Ux)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:V(qx)},{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(Bx)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:V(Vx)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:V(Wx)}]}async function VM(t,e){let r=Fx.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
441
+ **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as pN}from"path";var fN="unknown";async function Qx(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new fo(pN(n,_o)),s=Sc(r.registry,r.sessionContext?.hostKind??fN),i=r.moderatorEngine??Lx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:jx(n),readOnlyAdapter:Nx(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return Zx(e,a);case"agent_debate_status":return Ux(e,a);case"agent_cross_validate":return qx(e,a);case"agent_debate_create":return Vx(e,a);case"agent_debate_turn":return Bx(e,a);case"agent_debate_conclude":return Wx(e,a);case"agent_debate_review":return Jx(e,a);case"agent_changes_review":return Gx(e,a);case"agent_changes_accept":return Yx(e,a);case"agent_changes_reject":return Xx(e,a);case gc:return Qw(e,a);case co:return ex(e,a);case uo:return tx(e,a);case lo:return rx(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var qp={};Ve(qp,{getTools:()=>mN,handleTool:()=>xN});var eS=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")}),tS=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")}),rS=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),nS=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")}),oS=h.object({doc_id:h.string().describe("Document ID to read")}),sS=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)"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider independent work) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/. Always pass an explicit kind for idea/review workflows so the workspace tree stays sorted.")}),iS=h.object({});function mN(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:q(eS)},{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:q(tS)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:q(rS)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:q(nS)},{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:q(sS)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:q(oS)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:q(iS)}]}async function hN(t,e){let r=eS.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
426
442
  **Document ID:** ${n.id}
427
443
  **Path:** ${n.path}
428
444
  **Files:** ${r.files.join(", ")}
429
- **Rules:** ${r.rules.length}`}]}}async function BM(t,e){let r=Zx.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:
445
+ **Rules:** ${r.rules.length}`}]}}async function gN(t,e){let r=tS.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:
430
446
 
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=z(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)**
447
+ ${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=z(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=yu({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
432
448
  **Session ID:** ${i.id}
433
449
  **Document ID:** ${r.doc_id}
434
450
  **Providers:** ${n.join(", ")}
435
451
 
436
- Use \`workspace_review_status\` with session_id to check progress.`}]}}async function WM(t,e){let r=Ux.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**
452
+ Use \`workspace_review_status\` with session_id to check progress.`}]}}async function yN(t,e){let r=rS.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**
437
453
  `;return c+=`**Session ID:** ${n.id}
438
454
  `,c+=`**Status:** ${n.status}
439
455
  `,c+=`**Document:** ${n.config.doc_id}
@@ -443,30 +459,30 @@ Use \`workspace_review_status\` with session_id to check progress.`}]}}async fun
443
459
  `,c+=`- Failed: ${i.join(", ")||"none"}
444
460
  `,c+=`- Pending: ${a.join(", ")||"none"}
445
461
  `,n.result&&(c+=`
446
- **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function HM(t,e){let r=qx.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
462
+ **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function vN(t,e){let r=nS.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
447
463
  **Document ID:** ${r.doc_id}
448
464
  **Author:** ${r.author}
449
465
 
450
- ${r.content}`}]}}async function KM(t,e){let r=Bx.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata,kind:r.kind});return{content:[{type:"text",text:`**Document created**
466
+ ${r.content}`}]}}async function _N(t,e){let r=sS.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata,kind:r.kind});return{content:[{type:"text",text:`**Document created**
451
467
  **Document ID:** ${n.id}
452
468
  **Path:** ${n.path}
453
- **Title:** ${r.title}`}]}}async function GM(t,e){let r=Vx.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
469
+ **Title:** ${r.title}`}]}}async function bN(t,e){let r=oS.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
454
470
  **Path:** ${n.path}
455
471
 
456
- ${n.content}`}]}}async function JM(t,e){Wx.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
472
+ ${n.content}`}]}}async function wN(t,e){iS.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
457
473
 
458
474
  **Total:** ${r.length}
459
475
 
460
476
  `;for(let o of r){let s=o.content.slice(0,100).replace(/\n/g," ");n+=`- **${o.id}** \u2014 ${s}...
461
- `}return{content:[{type:"text",text:n}]}}async function YM(t,e,r){switch(t){case"workspace_create_review":return VM(e,r);case"workspace_request_review":return BM(e,r);case"workspace_review_status":return WM(e,r);case"workspace_add_comment":return HM(e,r);case"workspace_create_document":return KM(e,r);case"workspace_read":return GM(e,r);case"workspace_list":return JM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Cp={};Ze(Cp,{getTools:()=>XM,handleTool:()=>rN});function $c(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var QM=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function XM(){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 eN(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
477
+ `}return{content:[{type:"text",text:n}]}}async function xN(t,e,r){switch(t){case"workspace_create_review":return hN(e,r);case"workspace_request_review":return gN(e,r);case"workspace_review_status":return yN(e,r);case"workspace_add_comment":return vN(e,r);case"workspace_create_document":return _N(e,r);case"workspace_read":return bN(e,r);case"workspace_list":return wN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Vp={};Ve(Vp,{getTools:()=>$N,handleTool:()=>TN});function Tc(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var SN=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function $N(){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 kN(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
462
478
 
463
479
  `;t.sessionContext&&(r+=`## Host Session
464
480
  `,r+=`- **Host:** ${t.sessionContext.hostId} (${t.sessionContext.hostKind})
465
481
  `,r+=`- **Leader Provider:** ${t.sessionContext.leaderProviderId}
466
- `,r+=`- **Execution Mode:** ${$c(t.sessionContext.executionMode,t.sessionContext.hostKind)}
482
+ `,r+=`- **Execution Mode:** ${Tc(t.sessionContext.executionMode,t.sessionContext.hostKind)}
467
483
  `,r+=`- **Participants:** ${t.sessionContext.participantProviderIds.join(", ")}
468
484
 
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})
485
+ `);for(let n of e){let o=n.isAvailable(),s=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):ir(n,s),a=o?"Available":"Unavailable";r+=`## ${n.id} (${n.type})
470
486
  `,r+=`- **Status:** ${a}
471
487
  `,r+=`- **Invocation:** ${i.invocation}
472
488
  `,r+=`- **Roles:** ${i.roles.join(", ")}
@@ -481,34 +497,37 @@ ${n.content}`}]}}async function JM(t,e){Wx.parse(t);let r=await e.documentManage
481
497
  `,s.strengths.length>0&&(r+=`- **Strengths:** ${s.strengths.join(", ")}
482
498
  `),s.models.length>0&&(r+=`- **Models:** ${s.models.map(c=>c.name).join(", ")}
483
499
  `),r+=`
484
- `}return{content:[{type:"text",text:r}]}}async function tN(t,e){let r=QM.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:z(a),details:void 0,error:z(a)}}})),s=`# Health Check Results
500
+ `}return{content:[{type:"text",text:r}]}}async function PN(t,e){let r=SN.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:z(a),details:void 0,error:z(a)}}})),s=`# Health Check Results
485
501
 
486
502
  `;for(let i of o){let a=i.status==="ok"?"OK":i.status==="degraded"?"DEGRADED":"ERROR";s+=`## ${i.id} (${i.type})
487
503
  `,s+=`- **Status:** ${a}
488
504
  `,i.message&&(s+=`- **Message:** ${i.message}
489
505
  `),i.error&&(s+=`- **Error:** ${i.error}
490
506
  `),s+=`
491
- `}return{content:[{type:"text",text:s}]}}async function rN(t,e,r){switch(t){case"provider_list":return eN(r);case"provider_health":return tN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var zp={};Ze(zp,{getTools:()=>mN,handleTool:()=>yN});import{existsSync as cN,readFileSync as uN}from"fs";import{readFileSync as nN,existsSync as oN}from"fs";var sN={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 iN(t){if(!oN(t))return null;try{return JSON.parse(nN(t,"utf-8"))}catch{return null}}function aN(t){return t==="auto"?"auto":"default-only"}function Hx(t,e,r){let n=iN(t),o=new Set(r.enabledIds??[]),s=new Map((n?.providers??[]).map(d=>[d.id,d])),i=e.map(d=>{let p=sN[d.type]||{executionPolicy:Vt(d.type),config:{}},f=s.get(d.id);return s.delete(d.id),{id:d.id,type:d.type,enabled:d.available&&o.has(d.id),executionPolicy:f?.executionPolicy??p.executionPolicy,config:{...f?.config??p.config}}});for(let d of s.values())i.push({...d,enabled:o.has(d.id)?d.enabled:!1});if(i.length===0)throw new Error("No providers available to write into providers.config.json");let a={selectionPolicy:aN(r.selectionPolicy??n?.selectionPolicy),...r.locale!==void 0?{locale:r.locale}:n?.locale!==void 0?{locale:n.locale}:{},providers:i},c=n?JSON.stringify(n):null,u=JSON.stringify(a),l=c===null?"created":c===u?"unchanged":"updated";return!r.dryRun&&l!=="unchanged"&&(Cf(t),Ue(t,a)),{action:l,path:t,config:a}}function Kx(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 lN=h.object({}),dN=h.object({enabled_providers:h.array(h.string()).describe("Provider IDs to enable for Agestra workflows."),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 pN(t){if(!cN(t))return null;try{return JSON.parse(uN(t,"utf-8"))}catch{return null}}function fN(t,e){if(!t)return["Current config: not found",`Expected location: ${e}`];let r=t.providers.filter(n=>n.enabled);return[`Current config: ${r.length>0?"present":"present (no providers enabled)"}`,`Config path: ${e}`,`Enabled providers: ${r.length>0?r.map(n=>n.id).join(", "):"(none)"}`,`Locale: ${t.locale??"(default)"}`,`Selection policy: ${t.selectionPolicy}`]}function mN(){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"},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 hN(t){let e=_o(),r=pN(e),{results:n}=await uo(),o=["# Agestra Setup"];if(o.push(""),o.push(...fN(r,e)),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 gN(t,e){let r=dN.parse(t),n=_o(),{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};let a=Hx(n,o,{enabledIds:r.enabled_providers,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)"}`,`Locale: ${a.config.locale??"(default)"}`,`Selection policy: ${a.config.selectionPolicy}`].join(`
493
- `)}]}}async function yN(t,e,r){switch(t){case"setup_status":return lN.parse(e),hN(r);case"setup_apply":return gN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Op={};Ze(Op,{getTools:()=>_N,handleTool:()=>xN});var vN=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function _N(){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 Gx(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 bN(t){let r=Gx(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})
507
+ `}return{content:[{type:"text",text:s}]}}async function TN(t,e,r){switch(t){case"provider_list":return kN(r);case"provider_health":return PN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Wp={};Ve(Wp,{getTools:()=>LN,handleTool:()=>UN});import{existsSync as DN,readFileSync as zN}from"fs";import{readFileSync as EN,existsSync as RN}from"fs";var IN={ollama:{executionPolicy:"workspace-write",config:{host:vo,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Jt("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Jt("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Jt("claude-cli"),config:{timeout:12e4}}};async function ho(){let t=[{id:"ollama",type:"ollama",provider:new Gr({id:"ollama",host:vo})},{id:"gemini",type:"gemini-cli",provider:new Yr({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Xr({id:"codex"})},{id:"claude-cli",type:"claude-cli",provider:new Qr({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 AN(t){if(!RN(t))return null;try{return JSON.parse(EN(t,"utf-8"))}catch{return null}}function CN(t){return t==="auto"?"auto":"default-only"}function aS(t,e,r){let n=AN(t),o=new Set(r.enabledIds??[]),s=new Map((n?.providers??[]).map(d=>[d.id,d])),i=e.map(d=>{let p=IN[d.type]||{executionPolicy:Jt(d.type),config:{}},f=s.get(d.id);return s.delete(d.id),{id:d.id,type:d.type,enabled:d.available&&o.has(d.id),executionPolicy:f?.executionPolicy??p.executionPolicy,config:{...f?.config??p.config}}});for(let d of s.values())i.push({...d,enabled:o.has(d.id)?d.enabled:!1});if(i.length===0)throw new Error("No providers available to write into providers.config.json");let a={selectionPolicy:CN(r.selectionPolicy??n?.selectionPolicy),...r.locale!==void 0?{locale:r.locale}:n?.locale!==void 0?{locale:n.locale}:{},providers:i},c=n?JSON.stringify(n):null,u=JSON.stringify(a),l=c===null?"created":c===u?"unchanged":"updated";return!r.dryRun&&l!=="unchanged"&&(Vf(t),je(t,a)),{action:l,path:t,config:a}}function cS(t,e){Bp(t,e)}function Bp(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 ON=h.object({}),MN=h.object({enabled_providers:h.array(h.string()).describe("Provider IDs to enable for Agestra workflows."),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 NN(t){if(!DN(t))return null;try{return JSON.parse(zN(t,"utf-8"))}catch{return null}}function jN(t,e){if(!t)return["Current config: not found",`Expected location: ${e}`];let r=t.providers.filter(n=>n.enabled);return[`Current config: ${r.length>0?"present":"present (no providers enabled)"}`,`Config path: ${e}`,`Enabled providers: ${r.length>0?r.map(n=>n.id).join(", "):"(none)"}`,`Locale: ${t.locale??"(default)"}`,`Selection policy: ${t.selectionPolicy}`]}function LN(){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"},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 FN(t){let e=$o(),r=NN(e),{results:n}=await ho(),o=["# Agestra Setup"];if(o.push(""),o.push(...jN(r,e)),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(`
508
+ `)}]}}async function ZN(t,e){let r=MN.parse(t),n=$o(),{results:o}=await ho();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};let a=aS(n,o,{enabledIds:r.enabled_providers,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)"}`,`Locale: ${a.config.locale??"(default)"}`,`Selection policy: ${a.config.selectionPolicy}`].join(`
509
+ `)}]}}async function UN(t,e,r){switch(t){case"setup_status":return ON.parse(e),FN(r);case"setup_apply":return ZN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Hp={};Ve(Hp,{getTools:()=>VN,handleTool:()=>HN});var qN=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function VN(){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 uS(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 BN(t){let r=uS(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})
494
510
 
495
511
  `;for(let o of r){let s=(o.size/1e9).toFixed(1);n+=`## ${o.name}
496
512
  `,n+=`- **Size:** ${s} GB
497
513
  `,o.strengths.length>0&&(n+=`- **Strengths:** ${o.strengths.join(", ")}
498
514
  `),n+=`
499
- `}return{content:[{type:"text",text:n}]}}async function wN(t,e){let r=vN.parse(t),n=Gx(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**
515
+ `}return{content:[{type:"text",text:n}]}}async function WN(t,e){let r=qN.parse(t),n=uS(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**
500
516
  **Model:** ${r.model}
501
517
  **Error:** HTTP ${s.status}: ${a}`}],isError:!0}}let i=await s.json();return{content:[{type:"text",text:`**Model pulled successfully**
502
518
  **Model:** ${r.model}
503
519
  **Status:** ${i.status||"success"}`}]}}catch(o){let s=z(o);return{content:[{type:"text",text:`**Pull failed**
504
520
  **Model:** ${r.model}
505
- **Error:** ${s}`}],isError:!0}}}async function xN(t,e,r){switch(t){case"ollama_models":return bN(r);case"ollama_pull":return wN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Mp={};Ze(Mp,{getTools:()=>SN,handleTool:()=>PN});var Jx=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(),Yx=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function SN(){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(Jx)},{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(Yx)}]}async function $N(t,e){let r=Jx.parse(t);return{content:[{type:"text",text:`**Job submitted**
506
- **Job ID:** ${e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout})}
507
- **Provider:** ${r.provider}
521
+ **Error:** ${s}`}],isError:!0}}}async function HN(t,e,r){switch(t){case"ollama_models":return BN(r);case"ollama_pull":return WN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Kp={};Ve(Kp,{getTools:()=>JN,handleTool:()=>XN});var KN=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' / 'debate' / 'synthesis' / 'general' (default).")}).optional(),lS=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)"),save_as_document:KN.describe("If set, the job output will be saved as a workspace document on completion. Returned via cli_job_status once finalized.")}).strict(),dS=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function JN(){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:q(lS)},{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:q(dS)}]}async function GN(t,e){let r=lS.parse(t),n=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout,saveAsDocument:r.save_as_document}),o=r.save_as_document?`
522
+ **Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`**Job submitted**
523
+ **Job ID:** ${n}
524
+ **Provider:** ${r.provider}${o}
508
525
 
509
- Use \`cli_job_status\` with this job_id to check progress.`}]}}async function kN(t,e){let r=Yx.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}
526
+ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function YN(t,e){let r=dS.parse(t),n=typeof e.jobManager.getResultAwaited=="function"?await e.jobManager.getResultAwaited(r.job_id):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}
510
527
  **State:** ${n.state}`;return n.exitCode!==void 0&&(o+=`
511
- **Exit Code:** ${n.exitCode}`),n.output&&(o+=`
528
+ **Exit Code:** ${n.exitCode}`),n.savedDocumentId?o+=`
529
+ **Document ID:** ${n.savedDocumentId}`:n.saveError&&(o+=`
530
+ **Save error:** ${n.saveError}`),n.output&&(o+=`
512
531
 
513
532
  ---
514
533
 
@@ -516,10 +535,10 @@ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function kN
516
535
  ${n.output}`),n.error&&(o+=`
517
536
 
518
537
  **Stderr:**
519
- ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function PN(t,e,r){switch(t){case"cli_job_submit":return $N(e,r);case"cli_job_status":return kN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Np={};Ze(Np,{getTools:()=>TN,handleTool:()=>EN});var Qx=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)}),Xx=h.object({days_back:h.number().optional().default(30)}),eS=h.object({trace_id:h.string()});function TN(){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(Qx)},{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(Xx)},{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(eS)}]}async function EN(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 RN(e,n);case"trace_summary":return IN(e,n);case"trace_visualize":return AN(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function RN(t,e){let r=Qx.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)
538
+ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function XN(t,e,r){switch(t){case"cli_job_submit":return GN(e,r);case"cli_job_status":return YN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Jp={};Ve(Jp,{getTools:()=>QN,handleTool:()=>ej});var pS=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)}),fS=h.object({days_back:h.number().optional().default(30)}),mS=h.object({trace_id:h.string()});function QN(){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:q(pS)},{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:q(fS)},{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:q(mS)}]}async function ej(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 tj(e,n);case"trace_summary":return rj(e,n);case"trace_visualize":return nj(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function tj(t,e){let r=pS.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)
520
539
 
521
540
  `;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+=`
522
- `;return{content:[{type:"text",text:o}]}}function IN(t,e){let r=Xx.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)
541
+ `;return{content:[{type:"text",text:o}]}}function rj(t,e){let r=fS.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)
523
542
 
524
543
  `;o+=`| Provider:Task | Avg Quality | Count | Avg Latency |
525
544
  `,o+=`|---|---|---|---|
@@ -527,23 +546,23 @@ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state=
527
546
  `;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+=`
528
547
  **Provider Difficulty Qualification**
529
548
 
530
- `,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Hs.medium}) | High (>=${Hs.high}) |
549
+ `,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Ys.medium}) | High (>=${Ys.high}) |
531
550
  `,o+=`|---|---|---|---|---|---|
532
- `;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Ks(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 AN(t,e){let r=eS.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}
551
+ `;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Xs(u,d)?"YES":"no");o+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
552
+ `}return{content:[{type:"text",text:o}]}}function nj(t,e){let r=mS.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}
534
553
  `;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}]
535
554
  `;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}]
536
555
  `,a.quality&&(o+=` ${c}R --> ${c}Q[Quality: ${a.quality.score}]
537
556
  `)}return o+="```",{content:[{type:"text",text:`**Trace Visualization: ${r.trace_id}**
538
557
 
539
- ${o}`}]}}var Lp={};Ze(Lp,{getTools:()=>ON,handleTool:()=>jN,resetCache:()=>MN});import{execFile as CN}from"child_process";import{promisify as DN}from"util";var rS=DN(CN),nS=5e3;async function Ls(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await rS(e,[t],{timeout:nS,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function zN(){try{return await rS("git",["worktree","list"],{timeout:nS,encoding:"utf-8"}),!0}catch{return!1}}function ON(){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 kc=null,jp=null;function MN(){kc=null,jp=null}async function NN(t,e){let r=JSON.stringify(e.sessionContext??null);if(kc&&jp===r&&!t.force_refresh)return{content:[{type:"text",text:tS(kc)}]};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([Ls("claude"),Ls("codex"),Ls("gemini"),Ls("tmux"),Ls("git"),zN()]),y=[],_=e.registry.getAll(),x=_.find(Y=>Y.id==="ollama");if(x?.isAvailable()){let Y=x.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,P=f!==null,S=m!==null&&g,N=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",L=_.some(Y=>Y.isAvailable()&&!Y.type.endsWith("-host")&&Y.id!=="ollama"),Z=[N?"leader_only":"claude_only"];(L||y.length>0)&&Z.push("independent","debate"),v&&S&&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:x?.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:P,path:f},git:{available:m!==null,worktree_support:S}},capabilities:{can_autonomous_work:v&&S,can_tmux_visible:P,can_parallel_workers:v&&S,max_parallel_workers:v?3:0,available_modes:Z}};return kc=De,jp=r,{content:[{type:"text",text:tS(De)}]}}function tS(t){let e=`# Environment Check
558
+ ${o}`}]}}var Yp={};Ve(Yp,{getTools:()=>aj,handleTool:()=>lj,resetCache:()=>cj});import{execFile as oj}from"child_process";import{promisify as sj}from"util";var gS=sj(oj),yS=5e3;async function Bs(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await gS(e,[t],{timeout:yS,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function ij(){try{return await gS("git",["worktree","list"],{timeout:yS,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 Ec=null,Gp=null;function cj(){Ec=null,Gp=null}async function uj(t,e){let r=JSON.stringify(e.sessionContext??null);if(Ec&&Gp===r&&!t.force_refresh)return{content:[{type:"text",text:hS(Ec)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(K=>K.isAvailable()),o=n.find(K=>K.type==="claude-cli"),s=n.find(K=>K.type==="claude-host"),i=n.find(K=>K.type==="codex-cli"),a=n.find(K=>K.type==="codex-host"),c=n.find(K=>K.type==="gemini-cli"),u=n.find(K=>K.type==="gemini-host"),[l,d,p,f,m,g]=await Promise.all([Bs("claude"),Bs("codex"),Bs("gemini"),Bs("tmux"),Bs("git"),ij()]),v=[],_=e.registry.getAll(),S=_.find(K=>K.id==="ollama");if(S?.isAvailable()){let K=S.getCapabilities();for(let ot of K.models){let Re=ot.sizeGb??0;v.push({name:ot.name,size_gb:Re,tier:Zc(Re)})}}let y=i!==void 0||c!==void 0,x=f!==null,$=m!==null&&g,M=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",O=_.some(K=>K.isAvailable()&&!K.type.endsWith("-host")&&K.id!=="ollama"),Y=[M?"leader_only":"claude_only"];(O||v.length>0)&&Y.push("independent","debate"),y&&$&&Y.push("team");let Pe={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:v},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:x,path:f},git:{available:m!==null,worktree_support:$}},capabilities:{can_autonomous_work:y&&$,can_tmux_visible:x,can_parallel_workers:y&&$,max_parallel_workers:y?3:0,available_modes:Y}};return Ec=Pe,Gp=r,{content:[{type:"text",text:hS(Pe)}]}}function hS(t){let e=`# Environment Check
540
559
 
541
560
  `;t.host&&(e+=`## Host Session
542
561
 
543
562
  `,e+=`- **Host:** ${t.host.id}
544
563
  `,e+=`- **Kind:** ${t.host.kind}
545
564
  `,e+=`- **Leader Provider:** ${t.host.leader_provider}
546
- `,e+=`- **Execution Mode:** ${$c(t.host.execution_mode,t.host.kind)}
565
+ `,e+=`- **Execution Mode:** ${Tc(t.host.execution_mode,t.host.kind)}
547
566
  `,e+=`- **Participants:** ${t.host.participant_providers.join(", ")}
548
567
 
549
568
  `),e+=`## Providers
@@ -567,14 +586,14 @@ ${o}`}]}}var Lp={};Ze(Lp,{getTools:()=>ON,handleTool:()=>jN,resetCache:()=>MN});
567
586
  `,e+=`- **tmux visible:** ${t.capabilities.can_tmux_visible?"Yes":"No"}
568
587
  `,e+=`- **Parallel workers:** ${t.capabilities.can_parallel_workers?`Yes (max ${t.capabilities.max_parallel_workers})`:"No"}
569
588
  `,e+=`- **Available modes:** ${t.capabilities.available_modes.join(", ")}
570
- `,e}async function jN(t,e,r){return t==="environment_check"?NN(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Fp={};Ze(Fp,{getTools:()=>LN,handleTool:()=>KN});var oS=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(),sS=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),iS=h.object({worker_id:h.string().trim().min(1)}).strict(),aS=h.object({worker_id:h.string().trim().min(1)}).strict();function LN(){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(oS)},{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(sS)},{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(iS)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:V(aS)}]}function Pc(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 FN(t){let e=`# Worker Spawned
589
+ `,e}async function lj(t,e,r){return t==="environment_check"?uj(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Xp={};Ve(Xp,{getTools:()=>dj,handleTool:()=>bj});var vS=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(),_S=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),bS=h.object({worker_id:h.string().trim().min(1)}).strict(),wS=h.object({worker_id:h.string().trim().min(1)}).strict();function dj(){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:q(vS)},{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:q(_S)},{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:q(bS)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:q(wS)}]}function Rc(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function Rt(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function pj(t){let e=`# Worker Spawned
571
590
 
572
591
  `;return e+=`- **Worker ID:** ${t.workerId}
573
592
  `,e+=`- **Provider:** ${t.provider}
574
593
  `,e+=`- **State:** ${t.state}
575
594
  `,e+=`- **PID:** ${t.pid??"N/A"}
576
595
  `,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
577
- `),e}function ZN(t){let e=`# Worker Status
596
+ `),e}function fj(t){let e=`# Worker Status
578
597
 
579
598
  `;return e+=`- **Worker ID:** ${t.workerId}
580
599
  `,e+=`- **Provider:** ${t.provider}
@@ -589,12 +608,12 @@ ${o}`}]}}var Lp={};Ze(Lp,{getTools:()=>ON,handleTool:()=>jN,resetCache:()=>MN});
589
608
  \`\`\`
590
609
  ${t.outputTail}
591
610
  \`\`\`
592
- `),e}function UN(t){if(t.length===0)return`# Workers
611
+ `),e}function mj(t){if(t.length===0)return`# Workers
593
612
 
594
613
  No tracked workers.`;let e=`# Workers (${t.length})
595
614
 
596
615
  `;for(let r of t)e+=`- **${r.workerId}** \u2014 ${r.provider} \u2014 ${r.state}`,r.pid&&(e+=` (PID ${r.pid})`),e+=`
597
- `;return e}function qN(t){let e=`# Worker Results
616
+ `;return e}function hj(t){let e=`# Worker Results
598
617
 
599
618
  `;if(e+=`- **Worker ID:** ${t.workerId}
600
619
  `,e+=`- **State:** ${t.state}
@@ -616,7 +635,7 @@ ${t.gitDiff}
616
635
  \`\`\`
617
636
  ${t.outputFull}
618
637
  \`\`\`
619
- `),e}async function VN(t,e){let r=Pc(e),n=oS.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(FN(i))}catch(i){let a=z(i);return $t(`Error spawning worker: ${a}`,!0)}}async function BN(t,e){let r=Pc(e),n=sS.parse(t);if(!n.worker_id){let s=r.listAll();return $t(UN(s))}let o=r.getStatus(n.worker_id);return o?$t(ZN(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function WN(t,e){let r=Pc(e),n=iS.parse(t),o=r.collect(n.worker_id);return o?$t(qN(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function HN(t,e){let r=Pc(e),n=aS.parse(t);return r.stop(n.worker_id),$t(`Stop signal sent to worker: ${n.worker_id}`)}async function KN(t,e,r){try{switch(t){case"cli_worker_spawn":return await VN(e??{},r);case"cli_worker_status":return await BN(e??{},r);case"cli_worker_collect":return await WN(e??{},r);case"cli_worker_stop":return await HN(e??{},r);default:return $t(`Unknown tool: ${t}`,!0)}}catch(n){let o=z(n);return $t(`Error: ${o}`,!0)}}var Zp={};Ze(Zp,{getTools:()=>GN,handleTool:()=>YN});var cS=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 GN(){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(cS)}]}function JN(t){let e=`# Auto QA
638
+ `),e}async function gj(t,e){let r=Rc(e),n=vS.parse(t),o=r.knownProviders();if(!o.includes(n.provider))return Rt(`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 Rt(pj(i))}catch(i){let a=z(i);return Rt(`Error spawning worker: ${a}`,!0)}}async function yj(t,e){let r=Rc(e),n=_S.parse(t);if(!n.worker_id){let s=r.listAll();return Rt(mj(s))}let o=r.getStatus(n.worker_id);return o?Rt(fj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function vj(t,e){let r=Rc(e),n=bS.parse(t),o=r.collect(n.worker_id);return o?Rt(hj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function _j(t,e){let r=Rc(e),n=wS.parse(t);return r.stop(n.worker_id),Rt(`Stop signal sent to worker: ${n.worker_id}`)}async function bj(t,e,r){try{switch(t){case"cli_worker_spawn":return await gj(e??{},r);case"cli_worker_status":return await yj(e??{},r);case"cli_worker_collect":return await vj(e??{},r);case"cli_worker_stop":return await _j(e??{},r);default:return Rt(`Unknown tool: ${t}`,!0)}}catch(n){let o=z(n);return Rt(`Error: ${o}`,!0)}}var Qp={};Ve(Qp,{getTools:()=>wj,handleTool:()=>Sj});var xS=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 wj(){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:q(xS)}]}function xj(t){let e=`# Auto QA
620
639
 
621
640
  ${t.summary}
622
641
  `;return t.designDoc&&(e+=`
@@ -633,12 +652,12 @@ ${t.buildOutput||"(no output)"}
633
652
  \`\`\`
634
653
  ${t.testOutput||"(no output)"}
635
654
  \`\`\`
636
- `,e}async function YN(t,e,r){if(t==="qa_run"){let n=cS.parse(e??{}),s=await new Ao(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:JN(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var dS=[hp,Ip,Ap,Cp,zp,Op,Mp,Np,Lp,Fp,Zp];function pS(){let t=[];for(let e of dS)t.push(...e.getTools());return t}var lS=new Map;function XN(t){return t.sessionId??"__default__"}function ej(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return QN(e.uri)}catch{}}async function tj(t,e,r){let n=XN(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=ej(o.roots);if(s)return lS.set(n,s),s}catch{}return lS.get(n)??e.workspaceBaseDir??process.cwd()}function rj(t,e){return t.filter(r=>fS(r.name,e))}function nj(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 ti(n)}function fS(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>nj(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 oj(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 sj(){if(Up)return Up;let t=new Map;for(let e of dS)for(let r of e.getTools())t.set(r.name,e);return Up=t,t}function mS(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:oj(r.text,51200)+`
655
+ `,e}async function Sj(t,e,r){if(t==="qa_run"){let n=xS.parse(e??{}),s=await new No(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:xj(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var kS=[Tp,Up,qp,Vp,Wp,Hp,Kp,Jp,Yp,Xp,Qp];function PS(){let t=[];for(let e of kS)t.push(...e.getTools());return t}var $S=new Map;function kj(t){return t.sessionId??"__default__"}function Pj(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return $j(e.uri)}catch{}}async function Tj(t,e,r){let n=kj(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=Pj(o.roots);if(s)return $S.set(n,s),s}catch{}return $S.get(n)??e.workspaceBaseDir??process.cwd()}function Ej(t,e){return t.filter(r=>TS(r.name,e))}function Rj(t,e){let r=ir(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return si(n)}function TS(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>Rj(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 Ij(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 ef=null;function Aj(){if(ef)return ef;let t=new Map;for(let e of kS)for(let r of e.getTools())t.set(r.name,e);return ef=t,t}function ES(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:Ij(r.text,51200)+`
637
656
 
638
- ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function hS(t,e,r){let o=sj().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!fS(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 mS(i)}function qp(t){let e=new Ja({name:"agestra",version:Yp},{capabilities:{tools:{}}});return e.setRequestHandler(pl,async()=>({tools:rj(pS(),t)})),e.setRequestHandler(ns,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await tj(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await hS(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${z(i)}`}],isError:!0}}}),e}async function Vp(t){let e=new Qa;await t.connect(e)}function gS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function ij(t){return Array.isArray(t)?t.filter(gS).map(e=>e.text).join(`
657
+ ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function RS(t,e,r){let o=Aj().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!TS(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 ES(i)}function tf(t){let e=new Qa({name:"agestra",version:lf},{capabilities:{tools:{}}});return e.setRequestHandler($l,async()=>({tools:Ej(PS(),t)})),e.setRequestHandler(us,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await Tj(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await RS(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${z(i)}`}],isError:!0}}}),e}async function rf(t){let e=new tc;await t.connect(e)}function IS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function Cj(t){return Array.isArray(t)?t.filter(IS).map(e=>e.text).join(`
639
658
 
640
- `).trim():gS(t)?t.text:""}function yS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function vS(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:yS(o.metadata,"maxTokens")??4096,temperature:yS(o.metadata,"temperature"),modelPreferences:vS(o.metadata,"model")?{hints:[{name:vS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=ij(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 Tc(t,e="claude"){return Bp(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Ec(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 Rc(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 aj=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new gi({id:e,bridge:Tc(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new yi({id:e,bridge:Ec(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new vi({id:e,bridge:Rc(t,e)})}];function po(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function cj(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function uj(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 lj(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=()=>cj(r()),o=()=>uj(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 Tc(t,s)}case"codex-cli":{let s=po(e,"codex-host","codex-host");return Ec(t,s)}case"gemini-cli":{let s=po(e,"gemini-host","gemini-host");return Rc(t,s)}default:return null}},createHostProviders(){let s=r();return aj.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:lj(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 _S}from"fs";import{dirname as xS,join as bS,resolve as SS}from"path";import{fileURLToPath as dj}from"url";function pj(t){return _S(bS(t,"package.json"))&&_S(bS(t,"AGENTS.md"))}function wS(t){let e=SS(t);for(;;){if(pj(e))return e;let r=xS(e);if(r===e)return null;e=r}}function fj(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return SS(t);let e=xS(dj(import.meta.url));return wS(process.cwd())??wS(e)??process.cwd()}function $S(){let t=fj();return process.cwd()!==t&&process.chdir(t),t}var gj={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 yj(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}):(Kx(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): ${z(n)}`),{detected:0}}}async function vj(){let t=v=>process.stderr.write(`[mcp-server] ${v}
641
- `),e=$S(),r=_o(),n;try{let v=mj(r,"utf-8");n=JSON.parse(v)}catch(v){t(`Warning: Could not load ${r}: ${z(v)}`),t("Starting with empty provider registry."),n=null}let o=new Gs,s=null;if(n)try{s=Rf(n)}catch(v){t(`Warning: Invalid provider config in ${r}: ${z(v)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}if(s){let v=s.enabledProviders.map(S=>{let N=gj[S.type];if(!N)return t(`Unknown provider type: ${S.type} (id: ${S.id}), skipping`),null;let L=N(S);return{pc:S,provider:L}}).filter(S=>S!==null),P=await Promise.allSettled(v.map(async({pc:S,provider:N})=>(await N.initialize(),{pc:S,provider:N})));for(let S of P)if(S.status==="fulfilled"){let{pc:N,provider:L}=S.value;o.register(L),t(`Registered provider: ${N.id} (${N.type})`)}else t(`Failed to initialize provider: ${z(S.reason)}`)}if(await yj(o,e,t),s){let v=new Set(s.providers.filter(S=>!S.enabled).map(S=>S.id)),P=new Set(s.providers.filter(S=>!S.enabled).map(S=>S.type));try{let{providers:S}=await uo(),N=Dp(S,o,{excludeIds:v,excludeTypes:P});for(let L of N)t(`Registered newly detected provider: ${L.id} (${L.type})`)}catch(S){t(`Supplemental provider detection failed (non-fatal): ${z(S)}`)}}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=hm(s?.locale);t(`Localization active: ${c.locale}`);let u=new Map,l=()=>"unknown",d=async v=>{let P=u.get(v);if(P)return P;let S=new Eo(Gp(v,rf)),N=new Oo(Gp(v,mo)),L=new ai(v),Z=new ci(v);Z.cleanup(30);let De=new fi(Z,{ttlMs:6e4}),Y=new ko(v,{providerPolicies:a}),kt=new ao(Gp(v,mo));try{await kt.hydrateFromDisk()}catch(kS){t(`Structured session registry hydrate failed for ${v}: ${z(kS)}`)}let wr=bc(o,l()),Fs=new co({bridge:wr,documentManager:N,registry:kt,i18n:c,traceWriter:Z}),Zs={sessionManager:S,documentManager:N,jobManager:L,traceWriter:Z,qualityStatsProvider:De,cliWorkerManager:Y,structuredSessionRegistry:kt,moderatorEngine:Fs};return u.set(v,Zs),Zs},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 P=await v.structuredSessionRegistry.sweepTimeouts();P.length>0&&await v.moderatorEngine.handleTimedOutSnapshots(P)}catch(P){t(`Session sweep failed: ${z(P)}`)}})()},ff);y.unref?.();let _=!1,x=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",()=>{x().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{x().finally(()=>process.exit(0))}),process.on("uncaughtException",v=>{for(let P of u.values())P.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 _j=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=hj(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();_j&&vj().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
643
- `),process.exit(1)});export{yj as autoDetectIfNeeded,pS as collectTools,Vp as connectStdio,Tc as createClaudeLeaderBridge,Ec as createCodexLeaderBridge,Rc as createGeminiLeaderBridge,Wp as createRuntimeHostAdapter,qp as createServer,hS as dispatch,lo as inferHostKindFromClientName,Hp as registerHostBackedProviders,Kp as resolveSessionContext,mS as truncateResponse};
659
+ `).trim():IS(t)?t.text:""}function AS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function CS(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function go(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function nf(t,e,r){let n=()=>go(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:AS(o.metadata,"maxTokens")??4096,temperature:AS(o.metadata,"temperature"),modelPreferences:CS(o.metadata,"model")?{hints:[{name:CS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=Cj(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 Ic(t,e="claude"){return nf(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Ac(t,e="codex-host"){return nf(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Cc(t,e="gemini-host"){return nf(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var Dj=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new _i({id:e,bridge:Ic(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new bi({id:e,bridge:Ac(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new wi({id:e,bridge:Cc(t,e)})}];function yo(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function zj(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function Oj(t,e){switch(t){case"claude-code":return yo(e,"claude-host","claude");case"codex-cli":return yo(e,"codex-host","codex-host");case"gemini-cli":return yo(e,"gemini-host","gemini-host");default:return}}function Mj(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 of(t,e){let r=()=>go(t.getClientVersion()?.name),n=()=>zj(r()),o=()=>Oj(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=yo(e,"claude-host","claude");return Ic(t,s)}case"codex-cli":{let s=yo(e,"codex-host","codex-host");return Ac(t,s)}case"gemini-cli":{let s=yo(e,"gemini-host","gemini-host");return Cc(t,s)}default:return null}},createHostProviders(){let s=r();return Dj.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??Jt(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:Mj(i,c.id)}}}}async function sf(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 af(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 DS}from"fs";import{dirname as MS,join as zS,resolve as NS}from"path";import{fileURLToPath as Nj}from"url";function jj(t){return DS(zS(t,"package.json"))&&DS(zS(t,"AGENTS.md"))}function OS(t){let e=NS(t);for(;;){if(jj(e))return e;let r=MS(e);if(r===e)return null;e=r}}function Lj(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return NS(t);let e=MS(Nj(import.meta.url));return OS(process.cwd())??OS(e)??process.cwd()}function jS(){let t=Lj();return process.cwd()!==t&&process.chdir(t),t}var Uj={ollama:t=>new Gr({id:t.id,host:t.config?.host||vo}),"gemini-cli":t=>new Yr({id:t.id,timeout:t.config?.timeout}),"codex-cli":t=>new Xr({id:t.id,timeout:t.config?.timeout}),"claude-cli":t=>new Qr({id:t.id,timeout:t.config?.timeout})};async function qj(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 ho(),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(cS(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): ${z(n)}`),{detected:0}}}async function Vj(){let t=y=>process.stderr.write(`[mcp-server] ${y}
660
+ `),e=jS(),r=$o(),n;try{let y=Fj(r,"utf-8");n=JSON.parse(y)}catch(y){t(`Warning: Could not load ${r}: ${z(y)}`),t("Starting with empty provider registry."),n=null}let o=new Qs,s=null;if(n)try{s=Zf(n)}catch(y){t(`Warning: Invalid provider config in ${r}: ${z(y)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}if(s){let y=s.enabledProviders.map($=>{let M=Uj[$.type];if(!M)return t(`Unknown provider type: ${$.type} (id: ${$.id}), skipping`),null;let O=M($);return{pc:$,provider:O}}).filter($=>$!==null),x=await Promise.allSettled(y.map(async({pc:$,provider:M})=>(await M.initialize(),{pc:$,provider:M})));for(let $ of x)if($.status==="fulfilled"){let{pc:M,provider:O}=$.value;o.register(O),t(`Registered provider: ${M.id} (${M.type})`)}else t(`Failed to initialize provider: ${z($.reason)}`)}if(await qj(o,e,t),s){let y=new Set(s.providers.filter($=>!$.enabled).map($=>$.id)),x=new Set(s.providers.filter($=>!$.enabled).map($=>$.type));try{let{providers:$}=await ho(),M=Bp($,o,{excludeIds:y,excludeTypes:x});for(let O of M)t(`Registered newly detected provider: ${O.id} (${O.type})`)}catch($){t(`Supplemental provider detection failed (non-fatal): ${z($)}`)}}let i=new Map(s?.providers.map(y=>[y.id,y.executionPolicy])??[]),a=new Map(o.getAll().map(y=>[y.id,i.get(y.id)??Jt(y.type)])),c;try{c=lu(s?.locale)}catch(y){let x=y instanceof Error?y.message:String(y);t(`[i18n] failed to load requested locale (${s?.locale??"default"}): ${x}. Retrying with default bundle.`),c=lu(void 0)}t(`Localization active: ${c.locale}`);let u=new Map,l=()=>"unknown",d=async y=>{let x=u.get(y);if(x)return x;let $=new zo(cf(y,hf)),M=new Zo(cf(y,_o)),O=new li(y,{completionHandler:async({descriptor:It,result:Dc,saveAsDocument:zc})=>!Dc.output||Dc.output.trim().length===0?null:{documentId:(await M.createDocument({title:zc.title,content:Dc.output,metadata:{...zc.metadata,Provider:It.provider,Model:It.provider,JobId:It.id},kind:zc.kind})).id}});try{let It=O.reconcileOrphans();It>0&&t(`Reconciled ${It} orphaned job(s) in ${y}`)}catch(It){t(`Job orphan reconcile failed for ${y}: ${z(It)}`)}let Y=new di(y);Y.cleanup(30);let Pe=new gi(Y,{ttlMs:6e4}),K=new Ao(y,{providerPolicies:a}),ot=new fo(cf(y,_o));try{await ot.hydrateFromDisk()}catch(It){t(`Structured session registry hydrate failed for ${y}: ${z(It)}`)}let Re=Sc(o,l()),Pr=new mo({bridge:Re,documentManager:M,registry:ot,i18n:c,traceWriter:Y}),Tr={sessionManager:$,documentManager:M,jobManager:O,traceWriter:Y,qualityStatsProvider:Pe,cliWorkerManager:K,structuredSessionRegistry:ot,moderatorEngine:Pr};return u.set(y,Tr),Tr},p=await d(e),f={registry:o,...p,providerPolicies:a,workspaceBaseDir:e,resolveWorkspaceServices:async y=>d(y),i18n:c},m=tf(f),g=of(m,s);l=()=>go(m.getClientVersion()?.name),await sf(g,o,a,t),f.resolveSessionContext=()=>af(g,o);let v=setInterval(()=>{(async()=>{for(let y of u.values())try{let x=await y.structuredSessionRegistry.sweepTimeouts();x.length>0&&await y.moderatorEngine.handleTimedOutSnapshots(x)}catch(x){t(`Session sweep failed: ${z(x)}`)}})()},kf);v.unref?.();let _=!1,S=async()=>{if(!_){_=!0,t("Shutting down..."),clearInterval(v);for(let y of u.values())y.traceWriter.shutdown();for(let y of o.getAll())if(y.shutdown)try{await y.shutdown()}catch{}}};process.on("SIGTERM",()=>{S().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{S().finally(()=>process.exit(0))}),process.on("uncaughtException",y=>{for(let x of u.values())x.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${y}
661
+ `),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await rf(m),t("MCP server connected via stdio.")}var Bj=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=Zj(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();Bj&&Vj().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
662
+ `),process.exit(1)});export{qj as autoDetectIfNeeded,PS as collectTools,rf as connectStdio,Ic as createClaudeLeaderBridge,Ac as createCodexLeaderBridge,Cc as createGeminiLeaderBridge,of as createRuntimeHostAdapter,tf as createServer,RS as dispatch,go as inferHostKindFromClientName,sf as registerHostBackedProviders,af as resolveSessionContext,ES as truncateResponse};
644
663
  //# sourceMappingURL=bundle.js.map