agestra 4.8.4 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -1,59 +1,59 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as ___cr } from 'module';import { fileURLToPath as ___fu } from 'url';import { dirname as ___dn } from 'path';const __filename = ___fu(import.meta.url);const __dirname = ___dn(__filename);const require = ___cr(import.meta.url);
3
- var gS=Object.create;var Tc=Object.defineProperty;var yS=Object.getOwnPropertyDescriptor;var vS=Object.getOwnPropertyNames;var _S=Object.getPrototypeOf,bS=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),Be=(t,e)=>{for(var r in e)Tc(t,r,{get:e[r],enumerable:!0})},wS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vS(e))!bS.call(t,o)&&o!==r&&Tc(t,o,{get:()=>e[o],enumerable:!(n=yS(e,o))||n.enumerable});return t};var Vp=(t,e,r)=>(r=t!=null?gS(_S(t)):{},wS(e||!t||!t.__esModule?Tc(r,"default",{value:t,enumerable:!0}):r,t));var Bp,po,Wp,Hp,Kp,Gp,Jp,fo,Qp,Zs,Yp,Xp,ef,tf,rf,nf,Us,Ec,Rc,WN,of,ln,Ic,Ac,sf,af,qs,xr,Cc,cf,uf,dn,jt=an(()=>{"use strict";Bp="4.8.4",po="http://localhost:11434",Wp="llama3",Hp=".agestra/.jobs",Kp=".agestra/traces",Gp=".agestra/worktrees",Jp=".agestra/sessions",fo=".agestra/workspace",Qp="individual",Zs="debates",Yp="synthesis",Xp="issue",ef=".agestra/workers",tf=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),rf=2,nf=6e4,Us=20,Ec=5e4,Rc=10,WN=Object.freeze([3,5,10]),of=Object.freeze(["agree","disagree","abstain","revise"]),ln="votes",Ic=2,Ac=2,sf=1440*60*1e3,af=3600*1e3,qs=Object.freeze(["ko","zh","ja","en"]),xr="ko",Cc="en",cf="[REDACTED]",uf=["","--- 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 xS}from"child_process";function pn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return xS("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 Xt(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 mo=an(()=>{"use strict"});import{execFileSync as SS,spawn as $S}from"child_process";import{existsSync as kS}from"fs";function TS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:PS.has(t.toLowerCase())}function ES(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 RS(t){let e=t.toLowerCase();if(fn.has(e))return fn.get(e)??null;try{let n=SS("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(kS(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(!TS(t))return{command:t,args:e};let r=RS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>ES(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=$S(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,v=!1,x=null,_=!1,P=()=>{!_&&g+y>a&&(v=!0,_=!0,Xt(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(),!_&&c){let Q=c(De);Q&&(x=Q,_=!0,Xt(p))}}),i&&p.stdin&&(p.stdin.write(i),p.stdin.end());let S=()=>{Xt(p),l(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`))},z=setTimeout(S,n),O=()=>{clearTimeout(z),z=setTimeout(S,n)};p.stdout.on("data",O),p.stderr.on("data",O),p.on("close",Z=>{if(clearTimeout(z),x){l(x);return}u({stdout:f,stderr:m,exitCode:Z??1,truncated:v})}),p.on("error",Z=>{clearTimeout(z),l(new Error(`CLI spawn error: ${Z.message}`))})})}var PS,fn,mn=an(()=>{"use strict";mo();PS=new Set(["codex","gemini","npm","npx"]),fn=new Map});import{writeFileSync as G$,mkdirSync as vo,openSync as Nc,writeSync as jc,fsyncSync as $f,closeSync as Lc,renameSync as J$,unlinkSync as Q$,appendFileSync as Y$}from"fs";import{dirname as _o,join as X$}from"path";import{randomUUID as ek}from"crypto";function se(t,e){let r=_o(t);vo(r,{recursive:!0});let n=X$(r,`.tmp-${ek().slice(0,8)}`);try{G$(n,e,"utf-8"),J$(n,t)}catch(o){try{Q$(n)}catch{}throw o}}function Ge(t,e){se(t,JSON.stringify(e,null,2))}function ti(t,e){let r=_o(t);vo(r,{recursive:!0});let n=Nc(t,"a");try{jc(n,e),$f(n)}finally{Lc(n)}}var ei,ri=an(()=>{"use strict";ei=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)ti(e,r);else{let s=_o(e);vo(s,{recursive:!0}),Y$(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=_o(e);vo(n,{recursive:!0});let o=Nc(e,"a");try{jc(o,r.join("")),$f(o)}finally{Lc(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=_o(e);vo(n,{recursive:!0});let o=Nc(e,"a");try{jc(o,r.join(""))}finally{Lc(o)}this.buffer.delete(e)}}});import{existsSync as kf,realpathSync as tk}from"fs";import{basename as rk,dirname as nk,isAbsolute as Ef,join as ok,normalize as sk,resolve as Fc,relative as ik}from"path";function ak(t){return t===""||!t.startsWith("..")&&!Ef(t)}function Pf(t){let e=[],r=Fc(t);for(;!kf(r);){let o=nk(r);if(o===r)break;e.unshift(rk(r)),r=o}let n=kf(r)?tk(r):r;return e.reduce((o,s)=>ok(o,s),n)}function Rf(t,e){let r=Pf(e),n=Pf(t),o=ik(r,n);return ak(o)}function Zc(t,e){let r=Fc(e,t);return Rf(r,e)}function ht(t,e){let r=Fc(e,t);if(!Rf(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 Vt(t,e){if(Ef(t)){let r=sk(t);if(!Zc(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return ht(t,e)}function ni(t){return ck.test(t)}function oi(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(!Tf.has(t))throw new tt(t,`command is not in the allowlist (${[...Tf].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(uk.has(r))throw new tt(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var ck,Tf,uk,tt,bo=an(()=>{"use strict";ck=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Tf=new Set(["gemini","codex","npx","node","npm","tsc"]),uk=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 Cf={};Be(Cf,{CLI_PROVIDERS:()=>If,resolveCliConfig:()=>Af});import{readFileSync as Uc}from"fs";import{join as rt}from"path";import{spawn as lk}from"child_process";function Af(t){let e=dk[t.provider]??t.provider;return If[e]??null}function Fr(t,e){let r=rt(t,"status.json"),n=JSON.parse(Uc(r,"utf-8"));Ge(r,{...n,...e})}async function pk(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(Uc(rt(t,"job.json"),"utf-8"))}catch{try{Ge(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=Af(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=Uc(rt(t,"prompt.txt"),"utf-8"),i=o(s);try{oi(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=lk(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(()=>{Xt(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 v=d.trim().length>0;Fr(t,{state:y===0||v?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()}),c()}),l.on("error",y=>{clearTimeout(g);let v=y.code==="ENOENT"?"missing_cli":"error";se(rt(t,"error.txt"),y.message),Fr(t,{state:v,completedAt:new Date().toISOString()}),c()})})}var dk,If,fk,Df=an(()=>{"use strict";ri();mo();bo();mn();dk={"gemini-cli":"gemini","codex-cli":"codex"},If={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--full-auto","--ephemeral",t]}};fk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");fk&&pk().catch(()=>process.exit(1))});var is=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 os=class{};ne._CodeOrName=os;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Jr=class extends os{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 os{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 Dv(t,...e){let r=[t[0]],n=0;for(;n<e.length;)wl(r,e[n]),r.push(t[++n]);return new lt(r)}ne._=Dv;var bl=new lt("+");function zv(t,...e){let r=[ss(t[0])],n=0;for(;n<e.length;)r.push(bl),wl(r,e[n]),r.push(bl,ss(t[++n]));return lR(r),new lt(r)}ne.str=zv;function wl(t,e){e instanceof lt?t.push(...e._items):e instanceof Jr?t.push(e):t.push(fR(e))}ne.addCodeArg=wl;function lR(t){let e=1;for(;e<t.length-1;){if(t[e]===bl){let r=dR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function dR(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 pR(t,e){return e.emptyStr()?t:t.emptyStr()?e:zv`${t}${e}`}ne.strConcat=pR;function fR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ss(Array.isArray(t)?t.join(","):t)}function mR(t){return new lt(ss(t))}ne.stringify=mR;function ss(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ne.safeStringify=ss;function hR(t){return typeof t=="string"&&ne.IDENTIFIER.test(t)?new lt(`.${t}`):Dv`[${t}]`}ne.getProperty=hR;function gR(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=gR;function yR(t){return new lt(t.toString())}ne.regexpCode=yR});var $l=E(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.ValueScope=Ye.ValueScopeName=Ye.Scope=Ye.varKinds=Ye.UsedValueState=void 0;var Qe=is(),xl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},la;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(la||(Ye.UsedValueState=la={}));Ye.varKinds={const:new Qe.Name("const"),let:new Qe.Name("let"),var:new Qe.Name("var")};var da=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Qe.Name?e:this.name(e)}name(e){return new Qe.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}}};Ye.Scope=da;var pa=class extends Qe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Qe._)`.${new Qe.Name(r)}[${n}]`}};Ye.ValueScopeName=pa;var vR=(0,Qe._)`\n`,Sl=class extends da{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?vR:Qe.nil}}get(){return this._scope}name(e){return new pa(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,Qe._)`${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=Qe.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,la.Started);let l=r(u);if(l){let d=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const;s=(0,Qe._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Qe._)`${s}${l}${this.opts._n}`;else throw new xl(u);c.set(u,la.Completed)})}return s}};Ye.ValueScope=Sl});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=is(),_t=$l(),fr=is();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 ga=$l();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return ga.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return ga.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return ga.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return ga.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 Ht=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},kl=class extends Ht{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:{}}},fa=class extends Ht{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 ha(e,this.rhs)}},Pl=class extends fa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Tl=class extends Ht{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},El=class extends Ht{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Rl=class extends Ht{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Il=class extends Ht{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:{}}},as=class extends Ht{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)||(_R(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),{})}},Kt=class extends as{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Al=class extends as{},Zn=class extends Kt{};Zn.kind="else";var Qr=class t extends Kt{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(Ov(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 ha(e,this.condition),this.else&&Xr(e,this.else.names),e}};Qr.kind="if";var Yr=class extends Kt{};Yr.kind="for";var Cl=class extends Yr{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)}},Dl=class extends Yr{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=ha(super.names,this.from);return ha(e,this.to)}},ma=class extends Yr{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)}},cs=class extends Kt{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)}};cs.kind="func";var us=class extends as{render(e){return"return "+super.render(e)}};us.kind="return";var zl=class extends Kt{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}},ls=class extends Kt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ls.kind="catch";var ds=class extends Kt{render(e){return"finally"+super.render(e)}};ds.kind="finally";var Ol=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 Al]}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 kl(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 fa(e,r,n))}add(e,r){return this._leafNode(new Pl(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Il(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 Qr(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 Qr(e))}else(){return this._elseNode(new Zn)}endIf(){return this._endBlockNode(Qr,Zn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Cl(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 Dl(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 ma("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 ma("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Yr)}label(e){return this._leafNode(new Tl(e))}break(e){return this._leafNode(new El(e))}return(e){let r=new us;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(us)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new zl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ls(s),r(s)}return n&&(this._currNode=o.finally=new ds,this.code(n)),this._endBlockNode(ls,ds)}throw(e){return this._leafNode(new Rl(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 cs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(cs)}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 Qr))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=Ol;function Xr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ha(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 _R(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ov(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${Ml(t)}`}K.not=Ov;var bR=Mv(K.operators.AND);function wR(...t){return t.reduce(bR)}K.and=wR;var xR=Mv(K.operators.OR);function SR(...t){return t.reduce(xR)}K.or=SR;function Mv(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${Ml(e)} ${t} ${Ml(r)}`}function Ml(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(),$R=is();function kR(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=kR;function PR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Lv(t,e),!Fv(e,t.self.RULES.all))}G.alwaysValidSchema=PR;function Lv(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=Lv;function Fv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=Fv;function TR(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=TR;function ER({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=ER;function RR(t){return Zv(decodeURIComponent(t))}G.unescapeFragment=RR;function IR(t){return encodeURIComponent(jl(t))}G.escapeFragment=IR;function jl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=jl;function Zv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=Zv;function AR(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=AR;function Nv({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:Nv({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} || {}`),Ll(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Uv}),items:Nv({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 Uv(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&Ll(t,r,e),r}G.evaluatedPropsToName=Uv;function Ll(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}G.setEvaluated=Ll;var jv={};function CR(t,e){return t.scopeValue("func",{ref:e,code:jv[e.code]||(jv[e.code]=new $R._Code(e.code))})}G.useFunc=CR;var Nl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Nl||(G.Type=Nl={}));function DR(t,e,r){if(t instanceof le.Name){let n=e===Nl.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():"/"+jl(t)}G.getErrorPath=DR;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 Gt=E(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var je=H(),zR={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")};Fl.default=zR});var ps=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(),ya=oe(),qe=Gt();Le.keywordError={message:({keyword:t})=>(0,re.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,re.str)`"${t}" keyword must be ${e} ($data)`:(0,re.str)`"${t}" keyword is invalid ($data)`};function OR(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Wv(t,e,r);n??(i||a)?Vv(s,c):Bv(o,(0,re._)`[${c}]`)}Le.reportError=OR;function MR(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Wv(t,e,r);Vv(o,a),s||i||Bv(n,qe.default.vErrors)}Le.reportExtraError=MR;function NR(t,e){t.assign(qe.default.errors,e),t.if((0,re._)`${qe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,re._)`${qe.default.vErrors}.length`,e),()=>t.assign(qe.default.vErrors,null)))}Le.resetErrorsCount=NR;function jR({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,qe.default.errors,a=>{t.const(i,(0,re._)`${qe.default.vErrors}[${a}]`),t.if((0,re._)`${i}.instancePath === undefined`,()=>t.assign((0,re._)`${i}.instancePath`,(0,re.strConcat)(qe.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=jR;function Vv(t,e){let r=t.const("err",e);t.if((0,re._)`${qe.default.vErrors} === null`,()=>t.assign(qe.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${qe.default.vErrors}.push(${r})`),t.code((0,re._)`${qe.default.errors}++`)}function Bv(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 Wv(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:LR(t,e,r)}function LR(t,e,r={}){let{gen:n,it:o}=t,s=[FR(o,r),ZR(t,r)];return UR(t,e,s),n.object(...s)}function FR({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,ya.getErrorPath)(e,ya.Type.Str)}`:t;return[qe.default.instancePath,(0,re.strConcat)(qe.default.instancePath,r)]}function ZR({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,ya.getErrorPath)(r,ya.Type.Str)}`),[en.schemaPath,o]}function UR(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}`],[qe.default.data,s]),u&&n.push([en.propertyName,u])}});var Kv=E(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.boolOrEmptySchema=qn.topBoolOrEmptySchema=void 0;var qR=ps(),VR=H(),BR=Gt(),WR={message:"boolean schema is false"};function HR(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Hv(t,!1):typeof r=="object"&&r.$async===!0?e.return(BR.default.data):(e.assign((0,VR._)`${n}.errors`,null),e.return(!0))}qn.topBoolOrEmptySchema=HR;function KR(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Hv(t)):r.var(e,!0)}qn.boolOrEmptySchema=KR;function Hv(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,qR.reportError)(o,WR,void 0,e)}});var Zl=E(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.getRules=Vn.isJSONType=void 0;var GR=["string","number","integer","boolean","null","object","array"],JR=new Set(GR);function QR(t){return typeof t=="string"&&JR.has(t)}Vn.isJSONType=QR;function YR(){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=YR});var Ul=E(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.shouldUseRule=mr.shouldUseGroup=mr.schemaHasRulesForType=void 0;function XR({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Gv(t,n)}mr.schemaHasRulesForType=XR;function Gv(t,e){return e.rules.some(r=>Jv(t,r))}mr.shouldUseGroup=Gv;function Jv(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=Jv});var fs=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 eI=Zl(),tI=Ul(),rI=ps(),q=H(),Qv=oe(),Bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bn||(Fe.DataType=Bn={}));function nI(t){let e=Yv(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=nI;function Yv(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(eI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=Yv;function oI(t,e){let{gen:r,data:n,opts:o}=t,s=sI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,tI.schemaHasRulesForType)(t,e[0]));if(i){let a=Vl(e,n,o.strictNumbers,Bn.Wrong);r.if(a,()=>{s.length?iI(t,e,s):Bl(t)})}return i}Fe.coerceAndCheckDataType=oI;var Xv=new Set(["string","number","integer","boolean","null"]);function sI(t,e){return e?t.filter(r=>Xv.has(r)||e==="array"&&r==="array"):[]}function iI(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(Vl(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(Xv.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Bl(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),aI(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
3
+ var SS=Object.create;var Ic=Object.defineProperty;var $S=Object.getOwnPropertyDescriptor;var kS=Object.getOwnPropertyNames;var PS=Object.getPrototypeOf,TS=Object.prototype.hasOwnProperty;var an=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ze=(t,e)=>{for(var r in e)Ic(t,r,{get:e[r],enumerable:!0})},ES=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kS(e))!TS.call(t,o)&&o!==r&&Ic(t,o,{get:()=>e[o],enumerable:!(n=$S(e,o))||n.enumerable});return t};var Jp=(t,e,r)=>(r=t!=null?SS(PS(t)):{},ES(e||!t||!t.__esModule?Ic(r,"default",{value:t,enumerable:!0}):r,t));var Gp,fo,Yp,Qp,Xp,ef,tf,mo,rf,Us,nf,of,sf,af,cf,uf,qs,Ac,Cc,yN,lf,ln,Dc,zc,df,pf,Vs,xr,Oc,ff,mf,dn,Nt=an(()=>{"use strict";Gp="4.9.0",fo="http://localhost:11434",Yp="llama3",Qp=".agestra/.jobs",Xp=".agestra/traces",ef=".agestra/worktrees",tf=".agestra/sessions",mo=".agestra/workspace",rf="individual",Us="debates",nf="synthesis",of="issue",sf=".agestra/workers",af=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),cf=2,uf=6e4,qs=20,Ac=5e4,Cc=10,yN=Object.freeze([3,5,10]),lf=Object.freeze(["agree","disagree","abstain","revise"]),ln="votes",Dc=2,zc=2,df=1440*60*1e3,pf=3600*1e3,Vs=Object.freeze(["ko","zh","ja","en"]),xr="ko",Oc="en",ff="[REDACTED]",mf=["","--- REQUIRED RESPONSE FORMAT ---","Respond with JSON only, matching exactly this shape:",'{ "agrees": true | false, "feedback": "specific issues or why you agree", "suggestions": "concrete changes if you disagree (optional, may be omitted)" }',"No prose, markdown, or explanation outside the JSON object. The JSON must be the entire response or wrapped in a single ```json code fence.","-------------------------------"].join(`
4
+ `),dn=Object.freeze({auto:Object.freeze({name:"auto",description:"Auto-detect build profile from project structure (package.json scripts, tsconfig, vitest config, etc.).",command:"npx",args:Object.freeze([])}),tsc:Object.freeze({name:"tsc",description:"TypeScript project-references build via `npx tsc -b --noEmit`.",command:"npx",args:Object.freeze(["tsc","-b","--noEmit"])}),vitest:Object.freeze({name:"vitest",description:"Run the Vitest unit-test suite in CI mode.",command:"npx",args:Object.freeze(["vitest","run","--reporter=dot"])}),"npm-build":Object.freeze({name:"npm-build",description:"Run the project's `npm run build` script.",command:"npm",args:Object.freeze(["run","build"])}),"npm-test":Object.freeze({name:"npm-test",description:"Run the project's `npm test` script.",command:"npm",args:Object.freeze(["test","--","--run"])})})});import{execFileSync as RS}from"child_process";function pn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return RS("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0}),{delivered:!0}}catch{try{return process.kill(t),{delivered:!0}}catch{return{delivered:!1}}}try{return process.kill(-t,"SIGTERM"),{delivered:!0}}catch{try{return process.kill(t,"SIGTERM"),{delivered:!0}}catch{return{delivered:!1}}}}function er(t,e=3e3){let r=t.pid;if(r)pn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e)}var ho=an(()=>{"use strict"});import{execFileSync as IS,spawn as AS}from"child_process";import{existsSync as CS}from"fs";function zS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:DS.has(t.toLowerCase())}function OS(t){if(t.includes("\0"))throw new Error(`Windows shim arg contains null byte: ${JSON.stringify(t)}`);if(t.includes("%"))throw new Error(`Windows shim arg contains '%' which would trigger cmd.exe env expansion: ${JSON.stringify(t)}`);return/[\s"&^<>|()!]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function MS(t){let e=t.toLowerCase();if(fn.has(e))return fn.get(e)??null;try{let n=IS("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return fn.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return fn.set(e,a),a}let i=`${n[0]}.ps1`;if(CS(i)){let a={type:"powershell",path:i};return fn.set(e,a),a}}catch{}return fn.set(e,null),null}function Lt(t,e){if(!zS(t))return{command:t,args:e};let r=MS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>OS(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function ze(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c}=t;return new Promise((u,l)=>{let d=Lt(e,r),p=AS(d.command,d.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),f="",m="",g=0,y=0,_=!1,S=null,v=!1,k=()=>{!v&&g+y>a&&(_=!0,v=!0,er(p))};p.stdout.on("data",Z=>{g+=Z.length,g<=a&&(f+=Z.toString()),k()}),p.stderr.on("data",Z=>{y+=Z.length;let De=Z.toString();if(y<=a&&(m+=De),k(),!v&&c){let Y=c(De);Y&&(S=Y,v=!0,er(p))}}),i&&p.stdin&&(p.stdin.write(i),p.stdin.end());let x=()=>{er(p),l(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`))},z=setTimeout(x,n),O=()=>{clearTimeout(z),z=setTimeout(x,n)};p.stdout.on("data",O),p.stderr.on("data",O),p.on("close",Z=>{if(clearTimeout(z),S){l(S);return}u({stdout:f,stderr:m,exitCode:Z??1,truncated:_})}),p.on("error",Z=>{clearTimeout(z),l(new Error(`CLI spawn error: ${Z.message}`))})})}var DS,fn,mn=an(()=>{"use strict";ho();DS=new Set(["codex","gemini","npm","npx"]),fn=new Map});import{writeFileSync as rk,mkdirSync as _o,openSync as Fc,writeSync as Zc,fsyncSync as Rf,closeSync as Uc,renameSync as nk,unlinkSync as ok,appendFileSync as sk}from"fs";import{dirname as bo,join as ik}from"path";import{randomUUID as ak}from"crypto";function se(t,e){let r=bo(t);_o(r,{recursive:!0});let n=ik(r,`.tmp-${ak().slice(0,8)}`);try{rk(n,e,"utf-8"),nk(n,t)}catch(o){try{ok(n)}catch{}throw o}}function Ue(t,e){se(t,JSON.stringify(e,null,2))}function ri(t,e){let r=bo(t);_o(r,{recursive:!0});let n=Fc(t,"a");try{Zc(n,e),Rf(n)}finally{Uc(n)}}var ti,ni=an(()=>{"use strict";ti=class{buffer=new Map;flushTimer=null;flushIntervalMs;maxBufferSize;auditFsync;destroyed=!1;constructor(e){this.flushIntervalMs=e?.flushIntervalMs??2e3,this.maxBufferSize=e?.maxBufferSize??100,this.auditFsync=e?.auditFsync??!0,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer&&typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}append(e,r,n){if(this.destroyed)throw new Error("DurableAppendWriter has been destroyed");if(n==="audit"){if(this.auditFsync)ri(e,r);else{let s=bo(e);_o(s,{recursive:!0}),sk(e,r)}return}let o=this.buffer.get(e);o||(o=[],this.buffer.set(e,o)),o.push(r),o.length>=this.maxBufferSize&&this.flushFile(e),this.flushIntervalMs===0&&this.flushFile(e)}flush(){for(let e of this.buffer.keys())this.flushFile(e)}panicFlush(){for(let[e,r]of this.buffer)if(r.length!==0)try{let n=bo(e);_o(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join("")),Rf(o)}finally{Uc(o)}}catch{}this.buffer.clear()}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush())}flushFile(e){let r=this.buffer.get(e);if(!r||r.length===0)return;let n=bo(e);_o(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join(""))}finally{Uc(o)}this.buffer.delete(e)}}});import{existsSync as If,realpathSync as ck}from"fs";import{basename as uk,dirname as lk,isAbsolute as Df,join as dk,normalize as pk,resolve as qc,relative as fk}from"path";function mk(t){return t===""||!t.startsWith("..")&&!Df(t)}function Af(t){let e=[],r=qc(t);for(;!If(r);){let o=lk(r);if(o===r)break;e.unshift(uk(r)),r=o}let n=If(r)?ck(r):r;return e.reduce((o,s)=>dk(o,s),n)}function zf(t,e){let r=Af(e),n=Af(t),o=fk(r,n);return mk(o)}function Vc(t,e){let r=qc(e,t);return zf(r,e)}function ht(t,e){let r=qc(e,t);if(!zf(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Me(t,e){if(t.length===0)throw new Error("Filename must not be empty");if(t.includes("\0"))throw new Error(`Filename contains null byte: ${JSON.stringify(t)}`);if(t.includes("/")||t.includes("\\"))throw new Error(`Filename must not contain path separators: ${JSON.stringify(t)}`);if(t.includes(".."))throw new Error(`Filename must not contain '..': ${JSON.stringify(t)}`);return ht(t,e)}function Bt(t,e){if(Df(t)){let r=pk(t);if(!Vc(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return ht(t,e)}function oi(t){return hk.test(t)}function si(t,e){if(!t||typeof t!="string")throw new tt(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new tt(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new tt(t,"command must not contain path separators");if(!Cf.has(t))throw new tt(t,`command is not in the allowlist (${[...Cf].join(", ")})`);for(let r of e){if(typeof r!="string")throw new tt(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new tt(t,`arg contains null byte: ${JSON.stringify(r)}`);if(gk.has(r))throw new tt(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var hk,Cf,gk,tt,wo=an(()=>{"use strict";hk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Cf=new Set(["gemini","codex","npx","node","npm","tsc"]),gk=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),tt=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});var jf={};Ze(jf,{CLI_PROVIDERS:()=>Of,resolveCliConfig:()=>Mf});import{readFileSync as Bc}from"fs";import{join as rt}from"path";import{spawn as yk}from"child_process";function Mf(t){let e=vk[t.provider]??t.provider;return Of[e]??null}function Fr(t,e){let r=rt(t,"status.json"),n=JSON.parse(Bc(r,"utf-8"));Ue(r,{...n,...e})}async function _k(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(Bc(rt(t,"job.json"),"utf-8"))}catch{try{Ue(rt(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Mf(e);r||(Fr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Fr(t,{state:"running",startedAt:new Date().toISOString()});let s=Bc(rt(t,"prompt.txt"),"utf-8"),i=o(s);try{si(n,i)}catch(c){let u=c instanceof tt?c.message:`Argv rejected: ${c.message}`;Fr(t,{state:"error",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),u);return}let a;if(e.cwd)try{a=ht(e.cwd,process.cwd())}catch(c){Fr(t,{state:"error",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Lt(n,i),l=yk(u.command,u.args,{cwd:a,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",y=>{f+=y.length,f<=10485760&&(d+=y.toString())}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let g=setTimeout(()=>{er(l),se(rt(t,"output.txt"),d),se(rt(t,"error.txt"),p),Fr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",y=>{clearTimeout(g),se(rt(t,"output.txt"),d),se(rt(t,"error.txt"),p);let _=d.trim().length>0;Fr(t,{state:y===0||_?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()}),c()}),l.on("error",y=>{clearTimeout(g);let _=y.code==="ENOENT"?"missing_cli":"error";se(rt(t,"error.txt"),y.message),Fr(t,{state:_,completedAt:new Date().toISOString()}),c()})})}var vk,Of,bk,Nf=an(()=>{"use strict";ni();ho();wo();mn();vk={"gemini-cli":"gemini","codex-cli":"codex"},Of={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--full-auto","--ephemeral",t]}};bk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");bk&&_k().catch(()=>process.exit(1))});var as=E(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.regexpCode=ne.getEsmExportName=ne.getProperty=ne.safeStringify=ne.stringify=ne.strConcat=ne.addCodeArg=ne.str=ne._=ne.nil=ne._Code=ne.Name=ne.IDENTIFIER=ne._CodeOrName=void 0;var ss=class{};ne._CodeOrName=ss;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gr=class extends ss{constructor(e){if(super(),!ne.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ne.Name=Gr;var lt=class extends ss{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Gr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ne._Code=lt;ne.nil=new lt("");function Nv(t,...e){let r=[t[0]],n=0;for(;n<e.length;)$l(r,e[n]),r.push(t[++n]);return new lt(r)}ne._=Nv;var Sl=new lt("+");function Lv(t,...e){let r=[is(t[0])],n=0;for(;n<e.length;)r.push(Sl),$l(r,e[n]),r.push(Sl,is(t[++n]));return yR(r),new lt(r)}ne.str=Lv;function $l(t,e){e instanceof lt?t.push(...e._items):e instanceof Gr?t.push(e):t.push(bR(e))}ne.addCodeArg=$l;function yR(t){let e=1;for(;e<t.length-1;){if(t[e]===Sl){let r=vR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function vR(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Gr||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Gr))return`"${t}${e.slice(1)}`}function _R(t,e){return e.emptyStr()?t:t.emptyStr()?e:Lv`${t}${e}`}ne.strConcat=_R;function bR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:is(Array.isArray(t)?t.join(","):t)}function wR(t){return new lt(is(t))}ne.stringify=wR;function is(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ne.safeStringify=is;function xR(t){return typeof t=="string"&&ne.IDENTIFIER.test(t)?new lt(`.${t}`):Nv`[${t}]`}ne.getProperty=xR;function SR(t){if(typeof t=="string"&&ne.IDENTIFIER.test(t))return new lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ne.getEsmExportName=SR;function $R(t){return new lt(t.toString())}ne.regexpCode=$R});var Tl=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ye=as(),kl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},da;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(da||(Qe.UsedValueState=da={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var pa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=pa;var fa=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Qe.ValueScopeName=fa;var kR=(0,Ye._)`\n`,Pl=class extends pa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?kR:Ye.nil}}get(){return this._scope}name(e){return new fa(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,da.Started);let l=r(u);if(l){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ye._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ye._)`${s}${l}${this.opts._n}`;else throw new kl(u);c.set(u,da.Completed)})}return s}};Qe.ValueScope=Pl});var H=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var te=as(),_t=Tl(),fr=as();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return fr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return fr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return fr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return fr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return fr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return fr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return fr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return fr.Name}});var ya=Tl();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return ya.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return ya.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return ya.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return ya.varKinds}});K.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Kt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},El=class extends Kt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?_t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Un(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},ma=class extends Kt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Un(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return ga(e,this.rhs)}},Rl=class extends ma{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Il=class extends Kt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Al=class extends Kt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Cl=class extends Kt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Dl=class extends Kt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Un(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},cs=class extends Kt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(PR(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Xr(e,r.names),{})}},Jt=class extends cs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zl=class extends cs{},Zn=class extends Jt{};Zn.kind="else";var Yr=class t extends Jt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Zn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Fv(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Un(this.condition,e,r),this}get names(){let e=super.names;return ga(e,this.condition),this.else&&Xr(e,this.else.names),e}};Yr.kind="if";var Qr=class extends Jt{};Qr.kind="for";var Ol=class extends Qr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Un(this.iteration,e,r),this}get names(){return Xr(super.names,this.iteration.names)}},Ml=class extends Qr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?_t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ga(super.names,this.from);return ga(e,this.to)}},ha=class extends Qr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Un(this.iterable,e,r),this}get names(){return Xr(super.names,this.iterable.names)}},us=class extends Jt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};us.kind="func";var ls=class extends cs{render(e){return"return "+super.render(e)}};ls.kind="return";var jl=class extends Jt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Xr(e,this.catch.names),this.finally&&Xr(e,this.finally.names),e}},ds=class extends Jt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ds.kind="catch";var ps=class extends Jt{render(e){return"finally"+super.render(e)}};ps.kind="finally";var Nl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
5
+ `:""},this._extScope=e,this._scope=new _t.Scope({parent:e}),this._nodes=[new zl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new El(e,s,n)),s}const(e,r,n){return this._def(_t.varKinds.const,e,r,n)}let(e,r,n){return this._def(_t.varKinds.let,e,r,n)}var(e,r,n){return this._def(_t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ma(e,r,n))}add(e,r){return this._leafNode(new Rl(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Dl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new Yr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Yr(e))}else(){return this._elseNode(new Zn)}endIf(){return this._endBlockNode(Yr,Zn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ol(e),r)}forRange(e,r,n,o,s=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let i=this._scope.toName(e);return this._for(new Ml(s,i,r,n),()=>o(i))}forOf(e,r,n,o=_t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new ha("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new ha("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Qr)}label(e){return this._leafNode(new Il(e))}break(e){return this._leafNode(new Al(e))}return(e){let r=new ls;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ls)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new jl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ds(s),r(s)}return n&&(this._currNode=o.finally=new ps,this.code(n)),this._endBlockNode(ds,ps)}throw(e){return this._leafNode(new Cl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=te.nil,n,o){return this._blockNode(new us(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(us)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Yr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=Nl;function Xr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ga(t,e){return e instanceof te._CodeOrName?Xr(t,e.names):t}function Un(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function PR(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Fv(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${Ll(t)}`}K.not=Fv;var TR=Zv(K.operators.AND);function ER(...t){return t.reduce(TR)}K.and=ER;var RR=Zv(K.operators.OR);function IR(...t){return t.reduce(RR)}K.or=IR;function Zv(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${Ll(e)} ${t} ${Ll(r)}`}function Ll(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var oe=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var le=H(),AR=as();function CR(t){let e={};for(let r of t)e[r]=!0;return e}J.toHash=CR;function DR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vv(t,e),!Bv(e,t.self.RULES.all))}J.alwaysValidSchema=DR;function Vv(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Kv(t,`unknown keyword: "${s}"`)}J.checkUnknownRules=Vv;function Bv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}J.schemaHasRules=Bv;function zR(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}J.schemaHasRulesButRef=zR;function OR({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}J.schemaRefOrVal=OR;function MR(t){return Wv(decodeURIComponent(t))}J.unescapeFragment=MR;function jR(t){return encodeURIComponent(Zl(t))}J.escapeFragment=jR;function Zl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=Zl;function Wv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=Wv;function NR(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}J.eachItem=NR;function Uv({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}J.mergeEvaluated={props:Uv({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),Ul(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Hv}),items:Uv({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Hv(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&Ul(t,r,e),r}J.evaluatedPropsToName=Hv;function Ul(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}J.setEvaluated=Ul;var qv={};function LR(t,e){return t.scopeValue("func",{ref:e,code:qv[e.code]||(qv[e.code]=new AR._Code(e.code))})}J.useFunc=LR;var Fl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Fl||(J.Type=Fl={}));function FR(t,e,r){if(t instanceof le.Name){let n=e===Fl.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+Zl(t)}J.getErrorPath=FR;function Kv(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}J.checkStrictMode=Kv});var Gt=E(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var Ne=H(),ZR={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};ql.default=ZR});var fs=E(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var re=H(),va=oe(),Be=Gt();Le.keywordError={message:({keyword:t})=>(0,re.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,re.str)`"${t}" keyword must be ${e} ($data)`:(0,re.str)`"${t}" keyword is invalid ($data)`};function UR(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Yv(t,e,r);n??(i||a)?Jv(s,c):Gv(o,(0,re._)`[${c}]`)}Le.reportError=UR;function qR(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Yv(t,e,r);Jv(o,a),s||i||Gv(n,Be.default.vErrors)}Le.reportExtraError=qR;function VR(t,e){t.assign(Be.default.errors,e),t.if((0,re._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,re._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Le.resetErrorsCount=VR;function BR({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Be.default.errors,a=>{t.const(i,(0,re._)`${Be.default.vErrors}[${a}]`),t.if((0,re._)`${i}.instancePath === undefined`,()=>t.assign((0,re._)`${i}.instancePath`,(0,re.strConcat)(Be.default.instancePath,s.errorPath))),t.assign((0,re._)`${i}.schemaPath`,(0,re.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,re._)`${i}.schema`,r),t.assign((0,re._)`${i}.data`,n))})}Le.extendErrors=BR;function Jv(t,e){let r=t.const("err",e);t.if((0,re._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Be.default.vErrors}.push(${r})`),t.code((0,re._)`${Be.default.errors}++`)}function Gv(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,re._)`new ${t.ValidationError}(${e})`):(r.assign((0,re._)`${n}.errors`,e),r.return(!1))}var en={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function Yv(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:WR(t,e,r)}function WR(t,e,r={}){let{gen:n,it:o}=t,s=[HR(o,r),KR(t,r)];return JR(t,e,s),n.object(...s)}function HR({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,va.getErrorPath)(e,va.Type.Str)}`:t;return[Be.default.instancePath,(0,re.strConcat)(Be.default.instancePath,r)]}function KR({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,re.str)`${e}/${t}`;return r&&(o=(0,re.str)`${o}${(0,va.getErrorPath)(r,va.Type.Str)}`),[en.schemaPath,o]}function JR(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([en.keyword,o],[en.params,typeof e=="function"?e(t):e||(0,re._)`{}`]),c.messages&&n.push([en.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([en.schema,i],[en.parentSchema,(0,re._)`${l}${d}`],[Be.default.data,s]),u&&n.push([en.propertyName,u])}});var Xv=E(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.boolOrEmptySchema=qn.topBoolOrEmptySchema=void 0;var GR=fs(),YR=H(),QR=Gt(),XR={message:"boolean schema is false"};function eI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Qv(t,!1):typeof r=="object"&&r.$async===!0?e.return(QR.default.data):(e.assign((0,YR._)`${n}.errors`,null),e.return(!0))}qn.topBoolOrEmptySchema=eI;function tI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Qv(t)):r.var(e,!0)}qn.boolOrEmptySchema=tI;function Qv(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,GR.reportError)(o,XR,void 0,e)}});var Vl=E(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.getRules=Vn.isJSONType=void 0;var rI=["string","number","integer","boolean","null","object","array"],nI=new Set(rI);function oI(t){return typeof t=="string"&&nI.has(t)}Vn.isJSONType=oI;function sI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Vn.getRules=sI});var Bl=E(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.shouldUseRule=mr.shouldUseGroup=mr.schemaHasRulesForType=void 0;function iI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&e_(t,n)}mr.schemaHasRulesForType=iI;function e_(t,e){return e.rules.some(r=>t_(t,r))}mr.shouldUseGroup=e_;function t_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}mr.shouldUseRule=t_});var ms=E(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.reportTypeError=Fe.checkDataTypes=Fe.checkDataType=Fe.coerceAndCheckDataType=Fe.getJSONTypes=Fe.getSchemaTypes=Fe.DataType=void 0;var aI=Vl(),cI=Bl(),uI=fs(),q=H(),r_=oe(),Bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bn||(Fe.DataType=Bn={}));function lI(t){let e=n_(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Fe.getSchemaTypes=lI;function n_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(aI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=n_;function dI(t,e){let{gen:r,data:n,opts:o}=t,s=pI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,cI.schemaHasRulesForType)(t,e[0]));if(i){let a=Hl(e,n,o.strictNumbers,Bn.Wrong);r.if(a,()=>{s.length?fI(t,e,s):Kl(t)})}return i}Fe.coerceAndCheckDataType=dI;var o_=new Set(["string","number","integer","boolean","null"]);function pI(t,e){return e?t.filter(r=>o_.has(r)||e==="array"&&r==="array"):[]}function fI(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(Hl(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(o_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Kl(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),mI(t,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
6
6
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,q._)`+${o}`);return;case"integer":n.elseIf((0,q._)`${i} === "boolean" || ${o} === null
7
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 aI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function ql(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=ql;function Vl(t,e,r,n){if(t.length===1)return ql(t[0],e,r,n);let o,s=(0,Qv.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,ql(i,e,r,n));return o}Fe.checkDataTypes=Vl;var cI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function Bl(t){let e=uI(t);(0,rI.reportError)(e,cI)}Fe.reportTypeError=Bl;function uI(t){let{gen:e,data:r,schema:n}=t,o=(0,Qv.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var t_=E(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.assignDefaults=void 0;var Wn=H(),lI=oe();function dI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)e_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>e_(t,s,o.default))}va.assignDefaults=dI;function e_(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,lI.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(),Wl=oe(),hr=Gt(),pI=oe();function fI(t,e){let{gen:r,data:n,it:o}=t;r.if(Kl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=fI;function mI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Kl(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=mI;function hI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=hI;function r_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=r_;function Hl(t,e,r){return(0,ge._)`${r_(t)}.call(${e}, ${r})`}ue.isOwnProperty=Hl;function gI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Hl(t,e,r)}`:o}ue.propertyInData=gI;function Kl(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Hl(t,e,r))):o}ue.noPropertyInData=Kl;function n_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=n_;function yI(t,e){return n_(e).filter(r=>!(0,Wl.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=yI;function vI({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=vI;var _I=(0,ge._)`new RegExp`;function bI({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"?_I:(0,pI.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=bI;function wI(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:Wl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=wI;function xI(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,Wl.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=xI});var i_=E(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;var Ve=H(),tn=Gt(),SI=dt(),$I=ps();function kI(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=s_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ct.macroKeywordCode=kI;function PI(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;EI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=s_(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&&o_(t),y(()=>t.error());else{let v=e.async?f():m();e.modifying&&o_(t),y(()=>TI(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>g((0,Ve._)`await `),x=>n.assign(d,!1).if((0,Ve._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Ve._)`${x}.errors`),()=>n.throw(x))),v}function m(){let v=(0,Ve._)`${l}.errors`;return n.assign(v,null),g(Ve.nil),v}function g(v=e.async?(0,Ve._)`await `:Ve.nil){let x=c.opts.passContext?tn.default.this:tn.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ve._)`${v}${(0,SI.callValidateCode)(t,l,x,_)}`,e.modifying)}function y(v){var x;n.if((0,Ve.not)((x=e.valid)!==null&&x!==void 0?x:d),v)}}Ct.funcKeywordCode=PI;function o_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function TI(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(tn.default.vErrors,(0,Ve._)`${tn.default.vErrors} === null ? ${e} : ${tn.default.vErrors}.concat(${e})`).assign(tn.default.errors,(0,Ve._)`${tn.default.vErrors}.length`),(0,$I.extendErrors)(t)},()=>t.error())}function EI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function s_(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function RI(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=RI;function II({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=II});var c_=E(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.extendSubschemaMode=gr.extendSubschemaData=gr.getSubschema=void 0;var Dt=H(),a_=oe();function AI(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,a_.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=AI;function CI(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,a_.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=CI;function DI(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=DI});var Gl=E((YV,u_)=>{"use strict";u_.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((XV,l_)=>{"use strict";var yr=l_.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)};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 _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 yr.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 yr.propsKeywords){if(d&&typeof d=="object")for(var f in d)_a(t,e,r,d[f],o+"/"+l+"/"+zI(f),s,o,l,n,f)}else(l in yr.keywords||t.allKeys&&!(l in yr.skipKeywords))&&_a(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function zI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ms=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 OI=oe(),MI=Gl(),NI=d_(),jI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function LI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Jl(t):e?p_(t)<=e:!1}Xe.inlineRef=LI;var FI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Jl(t){for(let e in t){if(FI.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Jl)||typeof r=="object"&&Jl(r))return!0}return!1}function p_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!jI.has(r)&&(typeof t[r]=="object"&&(0,OI.eachItem)(t[r],n=>e+=p_(n)),e===1/0))return 1/0}return e}function f_(t,e="",r){r!==!1&&(e=Hn(e));let n=t.parse(e);return m_(t,n)}Xe.getFullPath=f_;function m_(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=m_;var ZI=/#\/?$/;function Hn(t){return t?t.replace(ZI,""):""}Xe.normalizeId=Hn;function UI(t,e,r){return r=Hn(r),t.resolve(e,r)}Xe.resolveUrl=UI;var qI=/^[a-z_][-a-z0-9._]*$/i;function VI(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Hn(t[r]||e),s={"":o},i=f_(n,o,!1),a={},c=new Set;return NI(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,y=s[m];typeof d[r]=="string"&&(y=v.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(_=Hn(y?P(y,_):_),c.has(_))throw l(_);c.add(_);let S=this.refs[_];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(d,S.schema,_):_!==Hn(g)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=g),_}function x(_){if(typeof _=="string"){if(!qI.test(_))throw new Error(`invalid anchor "${_}"`);v.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!MI(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Xe.getSchemaRefs=VI});var ys=E(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.getData=vr.KeywordCxt=vr.validateFunctionCode=void 0;var __=Kv(),h_=fs(),Yl=Ul(),ba=fs(),BI=t_(),gs=i_(),Ql=c_(),D=H(),F=Gt(),WI=ms(),Jt=oe(),hs=ps();function HI(t){if(x_(t)&&(S_(t),w_(t))){JI(t);return}b_(t,()=>(0,__.topBoolOrEmptySchema)(t))}vr.validateFunctionCode=HI;function b_({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"; ${g_(r,o)}`),GI(t,o),t.code(s)}):t.func(e,(0,D._)`${F.default.data}, ${KI(o)}`,n.$async,()=>t.code(g_(r,o)).code(s))}function KI(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 GI(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 JI(t){let{schema:e,opts:r,gen:n}=t;b_(t,()=>{r.$comment&&e.$comment&&k_(t),tA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&QI(t),$_(t),oA(t)})}function QI(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 g_(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 YI(t,e){if(x_(t)&&(S_(t),w_(t))){XI(t,e);return}(0,__.boolOrEmptySchema)(t,e)}function w_({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 x_(t){return typeof t.schema!="boolean"}function XI(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&k_(t),rA(t),nA(t);let s=n.const("_errs",F.default.errors);$_(t,s),n.var(e,(0,D._)`${s} === ${F.default.errors}`)}function S_(t){(0,Jt.checkUnknownRules)(t),eA(t)}function $_(t,e){if(t.opts.jtd)return y_(t,[],!1,e);let r=(0,h_.getSchemaTypes)(t.schema),n=(0,h_.coerceAndCheckDataType)(t,r);y_(t,r,!n,e)}function eA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Jt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function tA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Jt.checkStrictMode)(t,"default is ignored in the schema root")}function rA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,WI.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function nA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function k_({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 oA(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&&sA(t),e.return((0,D._)`${F.default.errors} === 0`))}function sA({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 y_(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,Jt.schemaHasRulesButRef)(s,l))){o.block(()=>T_(t,"$ref",l.all.$ref.definition));return}c.jtd||iA(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Yl.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ba.checkDataType)(p.type,i,c.strictNumbers)),v_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,ba.reportTypeError)(t)),o.endIf()):v_(t,p),a||o.if((0,D._)`${F.default.errors} === ${n||0}`))}}function v_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,BI.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Yl.shouldUseRule)(n,s)&&T_(t,s.keyword,s.definition,e.type)})}function iA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(aA(t,e),t.opts.allowUnionTypes||cA(t,e),uA(t,t.dataTypes))}function aA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{P_(t.dataTypes,r)||Xl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),dA(t,e)}}function cA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Xl(t,"use allowUnionTypes to allow union type keyword")}function uA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Yl.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>lA(e,i))&&Xl(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function lA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function P_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function dA(t,e){let r=[];for(let n of t.dataTypes)P_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Xl(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Jt.checkStrictMode)(t,e,t.opts.strictTypes)}var wa=class{constructor(e,r,n){if((0,gs.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,Jt.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",E_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,gs.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?hs.reportExtraError:hs.reportError)(this,this.def.error,r)}$dataError(){(0,hs.reportError)(this,this.def.$dataError||hs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,hs.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,ba.checkDataTypes)(c,r,s.opts.strictNumbers,ba.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,Ql.getSubschema)(this.it,e);(0,Ql.extendSubschemaData)(n,this.it,e),(0,Ql.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return YI(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Jt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Jt.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=wa;function T_(t,e,r,n){let o=new wa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,gs.funcKeywordCode)(o,r):"macro"in r?(0,gs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,gs.funcKeywordCode)(o,r)}var pA=/^\/(?:[^~]|~0|~1)*$/,fA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function E_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!pA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=fA.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,Jt.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=E_});var xa=E(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ed=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};td.default=ed});var vs=E(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var rd=ms(),nd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,rd.resolveUrl)(e,r,n),this.missingSchema=(0,rd.normalizeId)((0,rd.getFullPath)(e,this.missingRef))}};od.default=nd});var $a=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(),mA=xa(),rn=Gt(),wt=ms(),R_=oe(),hA=ys(),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 id(t){let e=I_.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:mA.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,hA.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=id;function gA(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=_A.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]=yA.call(this,s)}pt.resolveRef=gA;function yA(t){return(0,wt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:id.call(this,t)}function I_(t){for(let e of this._compilations)if(vA(e,t))return e}pt.getCompilingSchema=I_;function vA(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function _A(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Sa.call(this,t,e)}function Sa(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 sd.call(this,r,t);let s=(0,wt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Sa.call(this,t,i);return typeof a?.schema!="object"?void 0:sd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||id.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 sd.call(this,r,i)}}pt.resolveSchema=Sa;var bA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function sd(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,R_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!bA.has(a)&&u&&(e=(0,wt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,R_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,wt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Sa.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 A_=E((s4,wA)=>{wA.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 cd=E((i4,O_)=>{"use strict";var xA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),D_=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 ad(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 SA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function C_(t){return t.length=0,!0}function $A(t,e,r){if(t.length){let n=ad(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function kA(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=$A;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=C_}else{o.push(u);continue}}return o.length&&(a===C_?r.zone=o.join(""):i?n.push(o.join("")):n.push(ad(o))),r.address=n.join(""),r}function z_(t){if(PA(t,":")<2)return{host:t,isIPV6:!1};let e=kA(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 PA(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function TA(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 EA(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 RA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!D_(r)){let n=z_(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}O_.exports={nonSimpleDomain:SA,recomposeAuthority:RA,normalizeComponentEncoding:EA,removeDotSegments:TA,isIPv4:D_,isUUID:xA,normalizeIPv6:z_,stringArrayToHexStripped:ad}});var F_=E((a4,L_)=>{"use strict";var{isUUID:IA}=cd(),AA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,CA=["http","https","ws","wss","urn","urn:uuid"];function DA(t){return CA.indexOf(t)!==-1}function ud(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 M_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function N_(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function zA(t){return t.secure=ud(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function OA(t){if((t.port===(ud(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 MA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(AA);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=ld(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function NA(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=ld(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 jA(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!IA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function LA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var j_={scheme:"http",domainHost:!0,parse:M_,serialize:N_},FA={scheme:"https",domainHost:j_.domainHost,parse:M_,serialize:N_},ka={scheme:"ws",domainHost:!0,parse:zA,serialize:OA},ZA={scheme:"wss",domainHost:ka.domainHost,parse:ka.parse,serialize:ka.serialize},UA={scheme:"urn",parse:MA,serialize:NA,skipNormalize:!0},qA={scheme:"urn:uuid",parse:jA,serialize:LA,skipNormalize:!0},Pa={http:j_,https:FA,ws:ka,wss:ZA,urn:UA,"urn:uuid":qA};Object.setPrototypeOf(Pa,null);function ld(t){return t&&(Pa[t]||Pa[t.toLowerCase()])||void 0}L_.exports={wsIsSecure:ud,SCHEMES:Pa,isValidSchemeName:DA,getSchemeHandler:ld}});var q_=E((c4,Ea)=>{"use strict";var{normalizeIPv6:VA,removeDotSegments:_s,recomposeAuthority:BA,normalizeComponentEncoding:Ta,isIPv4:WA,nonSimpleDomain:HA}=cd(),{SCHEMES:KA,getSchemeHandler:Z_}=F_();function GA(t,e){return typeof t=="string"?t=zt(Qt(t,e),e):typeof t=="object"&&(t=Qt(zt(t,e),e)),t}function JA(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=U_(Qt(t,n),Qt(e,n),n,!0);return n.skipEscape=!0,zt(o,n)}function U_(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=_s(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=_s(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=_s(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=_s(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 QA(t,e,r){return typeof t=="string"?(t=unescape(t),t=zt(Ta(Qt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=zt(Ta(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=zt(Ta(Qt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=zt(Ta(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=Z_(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=BA(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=_s(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 YA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\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(YA);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(WA(n.host)===!1){let c=VA(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=Z_(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&HA(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 dd={SCHEMES:KA,normalize:GA,resolve:JA,resolveComponent:U_,equal:QA,serialize:zt,parse:Qt};Ea.exports=dd;Ea.exports.default=dd;Ea.exports.fastUri=dd});var B_=E(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var V_=q_();V_.code='require("ajv/dist/runtime/uri").default';pd.default=V_});var X_=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 XA=ys();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return XA.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 eC=xa(),J_=vs(),tC=Zl(),bs=$a(),rC=H(),ws=ms(),Ra=fs(),md=oe(),W_=A_(),nC=B_(),Q_=(t,e)=>new RegExp(t,e);Q_.code="new RegExp";var oC=["removeAdditional","useDefaults","coerceTypes"],sC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),iC={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."},aC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},H_=200;function cC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,y,v,x,_,P,S,z,O,Z,De;let Q=t.strict,kt=(e=t.code)===null||e===void 0?void 0:e.optimize,wr=kt===!0||kt===void 0?1:kt||0,js=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Q_,Ls=(o=t.uriResolver)!==null&&o!==void 0?o:nC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Q)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Q)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Q)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Q)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:Q)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:wr,regExp:js}:{optimize:wr,regExp:js},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:H_,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:H_,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(z=t.validateSchema)!==null&&z!==void 0?z:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(Z=t.unicodeRegExp)!==null&&Z!==void 0?Z:!0,int32range:(De=t.int32range)!==null&&De!==void 0?De:!0,uriResolver:Ls}}var xs=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...cC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new rC.ValueScope({scope:{},prefixes:sC,es5:r,lines:n}),this.logger=mC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,tC.getRules)(),K_.call(this,iC,e,"NOT SUPPORTED"),K_.call(this,aC,e,"DEPRECATED","warn"),this._metaOpts=pC.call(this),e.formats&&lC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&dC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),uC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=W_;n==="id"&&(o={...W_},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 J_.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,ws.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=G_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new bs.SchemaEnv({schema:{},schemaId:n});if(r=bs.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=G_.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,ws.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(gC.call(this,n,r),!r)return(0,md.eachItem)(n,s=>fd.call(this,s)),this;vC.call(this,r);let o={...r,type:(0,Ra.getJSONTypes)(r.type),schemaType:(0,Ra.getJSONTypes)(r.schemaType)};return(0,md.eachItem)(n,o.type.length===0?s=>fd.call(this,s,o):s=>o.type.forEach(i=>fd.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]=Y_(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,ws.normalizeId)(i||n);let u=ws.getSchemaRefs.call(this,e,n);return c=new bs.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):bs.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{bs.compileSchema.call(this,e)}finally{this.opts=r}}};xs.ValidationError=eC.default;xs.MissingRefError=J_.default;Ae.default=xs;function K_(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 G_(t){return t=(0,ws.normalizeId)(t),this.schemas[t]||this.refs[t]}function uC(){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 lC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function dC(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 pC(){let t={...this.opts};for(let e of oC)delete t[e];return t}var fC={log(){},warn(){},error(){}};function mC(t){if(t===!1)return fC;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 hC=/^[a-z_$][a-z0-9_$:-]*$/i;function gC(t,e){let{RULES:r}=this;if((0,md.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!hC.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 fd(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,Ra.getJSONTypes)(e.type),schemaType:(0,Ra.getJSONTypes)(e.schemaType)}};e.before?yC.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 yC(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 vC(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Y_(e)),t.validateSchema=this.compile(e,!0))}var _C={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Y_(t){return{anyOf:[t,_C]}}});var eb=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var bC={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};hd.default=bC});var ob=E(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.callRef=nn.getValidate=void 0;var wC=vs(),tb=dt(),et=H(),Jn=Gt(),rb=$a(),Ia=oe(),xC={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=rb.resolveRef.call(c,u,o,r);if(l===void 0)throw new wC.default(n.opts.uriResolver,o,r);if(l instanceof rb.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Aa(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Aa(t,(0,et._)`${m}.validate`,u,u.$async)}function p(m){let g=nb(t,m);Aa(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"),v=t.subschema({schema:m,dataTypes:[],schemaPath:et.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function nb(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=nb;function Aa(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,tb.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,tb.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=Ia.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,et._)`${m}.evaluated.props`);s.props=Ia.mergeEvaluated.props(o,v,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ia.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,et._)`${m}.evaluated.items`);s.items=Ia.mergeEvaluated.items(o,v,s.items,et.Name)}}}nn.callRef=Aa;nn.default=xC});var sb=E(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var SC=eb(),$C=ob(),kC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",SC.default,$C.default];gd.default=kC});var ib=E(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var Ca=H(),_r=Ca.operators,Da={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}},PC={message:({keyword:t,schemaCode:e})=>(0,Ca.str)`must be ${Da[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ca._)`{comparison: ${Da[t].okStr}, limit: ${e}}`},TC={keyword:Object.keys(Da),type:"number",schemaType:"number",$data:!0,error:PC,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ca._)`${r} ${Da[e].fail} ${n} || isNaN(${r})`)}};yd.default=TC});var ab=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var Ss=H(),EC={message:({schemaCode:t})=>(0,Ss.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ss._)`{multipleOf: ${t}}`},RC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:EC,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ss._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ss._)`${i} !== parseInt(${i})`;t.fail$data((0,Ss._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};vd.default=RC});var ub=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});function cb(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}_d.default=cb;cb.code='require("ajv/dist/runtime/ucs2length").default'});var lb=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var on=H(),IC=oe(),AC=ub(),CC={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}}`},DC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:CC,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,IC.useFunc)(t.gen,AC.default)}(${r})`;t.fail$data((0,on._)`${i} ${s} ${n}`)}};bd.default=DC});var db=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var zC=dt(),za=H(),OC={message:({schemaCode:t})=>(0,za.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,za._)`{pattern: ${t}}`},MC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:OC,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,za._)`(new RegExp(${o}, ${i}))`:(0,zC.usePattern)(t,n);t.fail$data((0,za._)`!${a}.test(${e})`)}};wd.default=MC});var pb=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var $s=H(),NC={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,$s.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,$s._)`{limit: ${t}}`},jC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:NC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?$s.operators.GT:$s.operators.LT;t.fail$data((0,$s._)`Object.keys(${r}).length ${o} ${n}`)}};xd.default=jC});var fb=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var ks=dt(),Ps=H(),LC=oe(),FC={message:({params:{missingProperty:t}})=>(0,Ps.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ps._)`{missingProperty: ${t}}`},ZC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:FC,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,v=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,LC.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ps.nil,d);else for(let f of r)(0,ks.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,ks.checkMissingProp)(t,r,f)),(0,ks.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,ks.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,ks.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Ps.not)(m),()=>{t.error(),e.break()})},Ps.nil)}}};Sd.default=ZC});var mb=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Ts=H(),UC={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ts.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ts._)`{limit: ${t}}`},qC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ts.operators.GT:Ts.operators.LT;t.fail$data((0,Ts._)`${r}.length ${o} ${n}`)}};$d.default=qC});var Oa=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var hb=Gl();hb.code='require("ajv/dist/runtime/equal").default';kd.default=hb});var gb=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Pd=fs(),Ce=H(),VC=oe(),BC=Oa(),WC={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}}`},HC={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:WC,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,Pd.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"),v=(0,Pd.checkDataTypes)(u,y,a.opts.strictNumbers,Pd.DataType.Wrong),x=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${m}--;`,()=>{e.let(y,(0,Ce._)`${r}[${m}]`),e.if(v,(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,VC.useFunc)(e,BC.default),v=e.name("outer");e.label(v).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(v)})))}}};Td.default=HC});var yb=E(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var Ed=H(),KC=oe(),GC=Oa(),JC={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ed._)`{allowedValue: ${t}}`},QC={keyword:"const",$data:!0,error:JC,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ed._)`!${(0,KC.useFunc)(e,GC.default)}(${r}, ${o})`):t.fail((0,Ed._)`${s} !== ${r}`)}};Rd.default=QC});var vb=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var Es=H(),YC=oe(),XC=Oa(),eD={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Es._)`{allowedValues: ${t}}`},tD={keyword:"enum",schemaType:"array",$data:!0,error:eD,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,YC.useFunc)(e,XC.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,Es.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,Es._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Es._)`${u()}(${r}, ${f}[${m}])`:(0,Es._)`${r} === ${g}`}}};Id.default=tD});var _b=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var rD=ib(),nD=ab(),oD=lb(),sD=db(),iD=pb(),aD=fb(),cD=mb(),uD=gb(),lD=yb(),dD=vb(),pD=[rD.default,nD.default,oD.default,sD.default,iD.default,aD.default,cD.default,uD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},lD.default,dD.default];Ad.default=pD});var Dd=E(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.validateAdditionalItems=void 0;var sn=H(),Cd=oe(),fD={message:({params:{len:t}})=>(0,sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sn._)`{limit: ${t}}`},mD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:fD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Cd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}bb(t,n)}};function bb(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,Cd.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:Cd.Type.Num},u),i.allErrors||r.if((0,sn.not)(u),()=>r.break())})}}Rs.validateAdditionalItems=bb;Rs.default=mD});var zd=E(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.validateTuple=void 0;var wb=H(),Ma=oe(),hD=dt(),gD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return xb(t,"additionalItems",e);r.items=!0,!(0,Ma.alwaysValidSchema)(r,e)&&t.ok((0,hD.validateArray)(t))}};function xb(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=Ma.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,wb._)`${s}.length`);r.forEach((d,p)=>{(0,Ma.alwaysValidSchema)(a,d)||(n.if((0,wb._)`${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,Ma.checkStrictMode)(a,y,p.strictTuples)}}}Is.validateTuple=xb;Is.default=gD});var Sb=E(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var yD=zd(),vD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,yD.validateTuple)(t,"items")};Od.default=vD});var kb=E(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var $b=H(),_D=oe(),bD=dt(),wD=Dd(),xD={message:({params:{len:t}})=>(0,$b.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$b._)`{limit: ${t}}`},SD={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xD,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,_D.alwaysValidSchema)(n,e)&&(o?(0,wD.validateAdditionalItems)(t,o):t.ok((0,bD.validateArray)(t)))}};Md.default=SD});var Pb=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var ft=H(),Na=oe(),$D={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}}`},kD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:$D,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Na.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Na.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Na.alwaysValidSchema)(s,r)){let g=(0,ft._)`${l} >= ${i}`;a!==void 0&&(g=(0,ft._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ft._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),y=e.let("count",0);f(g,()=>e.if(g,()=>m(y)))}function f(g,y){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Na.Type.Num,compositeRule:!0},g),y()})}function m(g){e.code((0,ft._)`${g}++`),a===void 0?e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ft._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Nd.default=kD});var Rb=E(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var jd=H(),PD=oe(),As=dt();Ot.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,jd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,jd._)`{property: ${t},
8
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function mI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function Wl(t,e,r,n=Bn.Correct){let o=n===Bn.Correct?q.operators.EQ:q.operators.NEQ,s;switch(t){case"null":return(0,q._)`${e} ${o} null`;case"array":s=(0,q._)`Array.isArray(${e})`;break;case"object":s=(0,q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${e} ${o} ${t}`}return n===Bn.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${e} == "number"`,a,r?(0,q._)`isFinite(${e})`:q.nil)}}Fe.checkDataType=Wl;function Hl(t,e,r,n){if(t.length===1)return Wl(t[0],e,r,n);let o,s=(0,r_.toHash)(t);if(s.array&&s.object){let i=(0,q._)`typeof ${e} != "object"`;o=s.null?i:(0,q._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,Wl(i,e,r,n));return o}Fe.checkDataTypes=Hl;var hI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function Kl(t){let e=gI(t);(0,uI.reportError)(e,hI)}Fe.reportTypeError=Kl;function gI(t){let{gen:e,data:r,schema:n}=t,o=(0,r_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var i_=E(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.assignDefaults=void 0;var Wn=H(),yI=oe();function vI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)s_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>s_(t,s,o.default))}_a.assignDefaults=vI;function s_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Wn._)`${s}${(0,Wn.getProperty)(e)}`;if(o){(0,yI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Wn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Wn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Wn._)`${a} = ${(0,Wn.stringify)(r)}`)}});var dt=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),Jl=oe(),hr=Gt(),_I=oe();function bI(t,e){let{gen:r,data:n,it:o}=t;r.if(Yl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=bI;function wI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Yl(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=wI;function xI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=xI;function a_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=a_;function Gl(t,e,r){return(0,ge._)`${a_(t)}.call(${e}, ${r})`}ue.isOwnProperty=Gl;function SI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Gl(t,e,r)}`:o}ue.propertyInData=SI;function Yl(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Gl(t,e,r))):o}ue.noPropertyInData=Yl;function c_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=c_;function $I(t,e){return c_(e).filter(r=>!(0,Jl.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=$I;function kI({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[hr.default.instancePath,(0,ge.strConcat)(hr.default.instancePath,s)],[hr.default.parentData,i.parentData],[hr.default.parentDataProperty,i.parentDataProperty],[hr.default.rootData,hr.default.rootData]];i.opts.dynamicRef&&d.push([hr.default.dynamicAnchors,hr.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=kI;var PI=(0,ge._)`new RegExp`;function TI({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?PI:(0,_I.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=TI;function EI(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Jl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=EI;function RI(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Jl.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=RI});var d_=E(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;var We=H(),tn=Gt(),II=dt(),AI=fs();function CI(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=l_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ct.macroKeywordCode=CI;function DI(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;OI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=l_(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&u_(t),y(()=>t.error());else{let _=e.async?f():m();e.modifying&&u_(t),y(()=>zI(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,We._)`await `),S=>n.assign(d,!1).if((0,We._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,We._)`${S}.errors`),()=>n.throw(S))),_}function m(){let _=(0,We._)`${l}.errors`;return n.assign(_,null),g(We.nil),_}function g(_=e.async?(0,We._)`await `:We.nil){let S=c.opts.passContext?tn.default.this:tn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${_}${(0,II.callValidateCode)(t,l,S,v)}`,e.modifying)}function y(_){var S;n.if((0,We.not)((S=e.valid)!==null&&S!==void 0?S:d),_)}}Ct.funcKeywordCode=DI;function u_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function zI(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(tn.default.vErrors,(0,We._)`${tn.default.vErrors} === null ? ${e} : ${tn.default.vErrors}.concat(${e})`).assign(tn.default.errors,(0,We._)`${tn.default.vErrors}.length`),(0,AI.extendErrors)(t)},()=>t.error())}function OI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function l_(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,We.stringify)(r)})}function MI(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ct.validSchemaType=MI;function jI({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ct.validateKeywordUsage=jI});var f_=E(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.extendSubschemaMode=gr.extendSubschemaData=gr.getSubschema=void 0;var Dt=H(),p_=oe();function NI(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Dt._)`${t.schemaPath}${(0,Dt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Dt._)`${t.schemaPath}${(0,Dt.getProperty)(e)}${(0,Dt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,p_.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}gr.getSubschema=NI;function LI(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Dt._)`${e.data}${(0,Dt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Dt.str)`${u}${(0,p_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Dt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Dt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}gr.extendSubschemaData=LI;function FI(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}gr.extendSubschemaMode=FI});var Ql=E((S4,m_)=>{"use strict";m_.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var g_=E(($4,h_)=>{"use strict";var yr=h_.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};ba(e,n,o,t,"",t)};yr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ba(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in yr.arrayKeywords)for(var p=0;p<d.length;p++)ba(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in yr.propsKeywords){if(d&&typeof d=="object")for(var f in d)ba(t,e,r,d[f],o+"/"+l+"/"+ZI(f),s,o,l,n,f)}else(l in yr.keywords||t.allKeys&&!(l in yr.skipKeywords))&&ba(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function ZI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var hs=E(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var UI=oe(),qI=Ql(),VI=g_(),BI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function WI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Xl(t):e?y_(t)<=e:!1}Xe.inlineRef=WI;var HI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Xl(t){for(let e in t){if(HI.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Xl)||typeof r=="object"&&Xl(r))return!0}return!1}function y_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!BI.has(r)&&(typeof t[r]=="object"&&(0,UI.eachItem)(t[r],n=>e+=y_(n)),e===1/0))return 1/0}return e}function v_(t,e="",r){r!==!1&&(e=Hn(e));let n=t.parse(e);return __(t,n)}Xe.getFullPath=v_;function __(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=__;var KI=/#\/?$/;function Hn(t){return t?t.replace(KI,""):""}Xe.normalizeId=Hn;function JI(t,e,r){return r=Hn(r),t.resolve(e,r)}Xe.resolveUrl=JI;var GI=/^[a-z_][-a-z0-9._]*$/i;function YI(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Hn(t[r]||e),s={"":o},i=v_(n,o,!1),a={},c=new Set;return VI(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,y=s[m];typeof d[r]=="string"&&(y=_.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[p]=y;function _(v){let k=this.opts.uriResolver.resolve;if(v=Hn(y?k(y,v):v),c.has(v))throw l(v);c.add(v);let x=this.refs[v];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,v):v!==Hn(g)&&(v[0]==="#"?(u(d,a[v],v),a[v]=d):this.refs[v]=g),v}function S(v){if(typeof v=="string"){if(!GI.test(v))throw new Error(`invalid anchor "${v}"`);_.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!qI(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Xe.getSchemaRefs=YI});var vs=E(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.getData=vr.KeywordCxt=vr.validateFunctionCode=void 0;var $_=Xv(),b_=ms(),td=Bl(),wa=ms(),QI=i_(),ys=d_(),ed=f_(),D=H(),F=Gt(),XI=hs(),Yt=oe(),gs=fs();function eA(t){if(T_(t)&&(E_(t),P_(t))){nA(t);return}k_(t,()=>(0,$_.topBoolOrEmptySchema)(t))}vr.validateFunctionCode=eA;function k_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,D._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,D._)`"use strict"; ${w_(r,o)}`),rA(t,o),t.code(s)}):t.func(e,(0,D._)`${F.default.data}, ${tA(o)}`,n.$async,()=>t.code(w_(r,o)).code(s))}function tA(t){return(0,D._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,D._)`, ${F.default.dynamicAnchors}={}`:D.nil}}={}`}function rA(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,D._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,D._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,D._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,D._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,D._)`""`),t.var(F.default.parentData,(0,D._)`undefined`),t.var(F.default.parentDataProperty,(0,D._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`{}`)})}function nA(t){let{schema:e,opts:r,gen:n}=t;k_(t,()=>{r.$comment&&e.$comment&&I_(t),cA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&oA(t),R_(t),dA(t)})}function oA(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,D._)`${r}.evaluated`),e.if((0,D._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,D._)`${t.evaluated}.props`,(0,D._)`undefined`)),e.if((0,D._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,D._)`${t.evaluated}.items`,(0,D._)`undefined`))}function w_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function sA(t,e){if(T_(t)&&(E_(t),P_(t))){iA(t,e);return}(0,$_.boolOrEmptySchema)(t,e)}function P_({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function T_(t){return typeof t.schema!="boolean"}function iA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&I_(t),uA(t),lA(t);let s=n.const("_errs",F.default.errors);R_(t,s),n.var(e,(0,D._)`${s} === ${F.default.errors}`)}function E_(t){(0,Yt.checkUnknownRules)(t),aA(t)}function R_(t,e){if(t.opts.jtd)return x_(t,[],!1,e);let r=(0,b_.getSchemaTypes)(t.schema),n=(0,b_.coerceAndCheckDataType)(t,r);x_(t,r,!n,e)}function aA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Yt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function cA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Yt.checkStrictMode)(t,"default is ignored in the schema root")}function uA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,XI.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function lA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function I_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,D._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,D.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,D._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function dA(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,D._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,D._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,D._)`${n}.errors`,F.default.vErrors),s.unevaluated&&pA(t),e.return((0,D._)`${F.default.errors} === 0`))}function pA({gen:t,evaluated:e,props:r,items:n}){r instanceof D.Name&&t.assign((0,D._)`${e}.props`,r),n instanceof D.Name&&t.assign((0,D._)`${e}.items`,n)}function x_(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Yt.schemaHasRulesButRef)(s,l))){o.block(()=>C_(t,"$ref",l.all.$ref.definition));return}c.jtd||fA(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,td.shouldUseGroup)(s,p)&&(p.type?(o.if((0,wa.checkDataType)(p.type,i,c.strictNumbers)),S_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,wa.reportTypeError)(t)),o.endIf()):S_(t,p),a||o.if((0,D._)`${F.default.errors} === ${n||0}`))}}function S_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,QI.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,td.shouldUseRule)(n,s)&&C_(t,s.keyword,s.definition,e.type)})}function fA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(mA(t,e),t.opts.allowUnionTypes||hA(t,e),gA(t,t.dataTypes))}function mA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{A_(t.dataTypes,r)||rd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),vA(t,e)}}function hA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&rd(t,"use allowUnionTypes to allow union type keyword")}function gA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,td.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>yA(e,i))&&rd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function yA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function A_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function vA(t,e){let r=[];for(let n of t.dataTypes)A_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function rd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Yt.checkStrictMode)(t,e,t.opts.strictTypes)}var xa=class{constructor(e,r,n){if((0,ys.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Yt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",D_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ys.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",F.default.errors))}result(e,r,n){this.failResult((0,D.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,D.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?gs.reportExtraError:gs.reportError)(this,this.def.error,r)}$dataError(){(0,gs.reportError)(this,this.def.$dataError||gs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,gs.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=D.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,D.or)((0,D._)`${o} === undefined`,r)),e!==D.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==D.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,D.or)(i(),a());function i(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,wa.checkDataTypes)(c,r,s.opts.strictNumbers,wa.DataType.Wrong)}`}return D.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(e,r){let n=(0,ed.getSubschema)(this.it,e);(0,ed.extendSubschemaData)(n,this.it,e),(0,ed.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return sA(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Yt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Yt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,D.Name)),!0}};vr.KeywordCxt=xa;function C_(t,e,r,n){let o=new xa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ys.funcKeywordCode)(o,r):"macro"in r?(0,ys.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ys.funcKeywordCode)(o,r)}var _A=/^\/(?:[^~]|~0|~1)*$/,bA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function D_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!_A.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=bA.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,D._)`${s}${(0,D.getProperty)((0,Yt.unescapeJsonPointer)(u))}`,i=(0,D._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}vr.getData=D_});var Sa=E(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var nd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};od.default=nd});var _s=E(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var sd=hs(),id=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,sd.resolveUrl)(e,r,n),this.missingSchema=(0,sd.normalizeId)((0,sd.getFullPath)(e,this.missingRef))}};ad.default=id});var ka=E(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.resolveSchema=pt.getCompilingSchema=pt.resolveRef=pt.compileSchema=pt.SchemaEnv=void 0;var bt=H(),wA=Sa(),rn=Gt(),wt=hs(),z_=oe(),xA=vs(),Kn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,wt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};pt.SchemaEnv=Kn;function ud(t){let e=O_.call(this,t);if(e)return e;let r=(0,wt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new bt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:wA.default,code:(0,bt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:rn.default.data,parentData:rn.default.parentData,parentDataProperty:rn.default.parentDataProperty,dataNames:[rn.default.data],dataPathArr:[bt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,bt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:bt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,bt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,xA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(rn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${rn.default.self}`,`${rn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof bt.Name?void 0:m,items:g instanceof bt.Name?void 0:g,dynamicProps:m instanceof bt.Name,dynamicItems:g instanceof bt.Name},f.source&&(f.source.evaluated=(0,bt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}pt.compileSchema=ud;function SA(t,e,r){var n;r=(0,wt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=PA.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Kn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=$A.call(this,s)}pt.resolveRef=SA;function $A(t){return(0,wt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ud.call(this,t)}function O_(t){for(let e of this._compilations)if(kA(e,t))return e}pt.getCompilingSchema=O_;function kA(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function PA(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||$a.call(this,t,e)}function $a(t,e){let r=this.opts.uriResolver.parse(e),n=(0,wt._getFullPath)(this.opts.uriResolver,r),o=(0,wt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return cd.call(this,r,t);let s=(0,wt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=$a.call(this,t,i);return typeof a?.schema!="object"?void 0:cd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ud.call(this,i),s===(0,wt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,wt.resolveUrl)(this.opts.uriResolver,o,u)),new Kn({schema:a,schemaId:c,root:t,baseId:o})}return cd.call(this,r,i)}}pt.resolveSchema=$a;var TA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function cd(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,z_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!TA.has(a)&&u&&(e=(0,wt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,z_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,wt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=$a.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Kn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var M_=E((I4,EA)=>{EA.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var dd=E((A4,F_)=>{"use strict";var RA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),N_=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function ld(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var IA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function j_(t){return t.length=0,!0}function AA(t,e,r){if(t.length){let n=ld(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function CA(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=AA;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=j_}else{o.push(u);continue}}return o.length&&(a===j_?r.zone=o.join(""):i?n.push(o.join("")):n.push(ld(o))),r.address=n.join(""),r}function L_(t){if(DA(t,":")<2)return{host:t,isIPV6:!1};let e=CA(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function DA(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function zA(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function OA(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function MA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!N_(r)){let n=L_(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}F_.exports={nonSimpleDomain:IA,recomposeAuthority:MA,normalizeComponentEncoding:OA,removeDotSegments:zA,isIPv4:N_,isUUID:RA,normalizeIPv6:L_,stringArrayToHexStripped:ld}});var B_=E((C4,V_)=>{"use strict";var{isUUID:jA}=dd(),NA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,LA=["http","https","ws","wss","urn","urn:uuid"];function FA(t){return LA.indexOf(t)!==-1}function pd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Z_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function U_(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ZA(t){return t.secure=pd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function UA(t){if((t.port===(pd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function qA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(NA);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=fd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function VA(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=fd(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function BA(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!jA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function WA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var q_={scheme:"http",domainHost:!0,parse:Z_,serialize:U_},HA={scheme:"https",domainHost:q_.domainHost,parse:Z_,serialize:U_},Pa={scheme:"ws",domainHost:!0,parse:ZA,serialize:UA},KA={scheme:"wss",domainHost:Pa.domainHost,parse:Pa.parse,serialize:Pa.serialize},JA={scheme:"urn",parse:qA,serialize:VA,skipNormalize:!0},GA={scheme:"urn:uuid",parse:BA,serialize:WA,skipNormalize:!0},Ta={http:q_,https:HA,ws:Pa,wss:KA,urn:JA,"urn:uuid":GA};Object.setPrototypeOf(Ta,null);function fd(t){return t&&(Ta[t]||Ta[t.toLowerCase()])||void 0}V_.exports={wsIsSecure:pd,SCHEMES:Ta,isValidSchemeName:FA,getSchemeHandler:fd}});var K_=E((D4,Ra)=>{"use strict";var{normalizeIPv6:YA,removeDotSegments:bs,recomposeAuthority:QA,normalizeComponentEncoding:Ea,isIPv4:XA,nonSimpleDomain:eC}=dd(),{SCHEMES:tC,getSchemeHandler:W_}=B_();function rC(t,e){return typeof t=="string"?t=zt(Qt(t,e),e):typeof t=="object"&&(t=Qt(zt(t,e),e)),t}function nC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=H_(Qt(t,n),Qt(e,n),n,!0);return n.skipEscape=!0,zt(o,n)}function H_(t,e,r,n){let o={};return n||(t=Qt(zt(t,r),r),e=Qt(zt(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=bs(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=bs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=bs(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=bs(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function oC(t,e,r){return typeof t=="string"?(t=unescape(t),t=zt(Ea(Qt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=zt(Ea(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=zt(Ea(Qt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=zt(Ea(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function zt(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=W_(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=QA(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=bs(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var sC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Qt(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(sC);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(XA(n.host)===!1){let c=YA(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=W_(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&eC(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var md={SCHEMES:tC,normalize:rC,resolve:nC,resolveComponent:H_,equal:oC,serialize:zt,parse:Qt};Ra.exports=md;Ra.exports.default=md;Ra.exports.fastUri=md});var G_=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var J_=K_();J_.code='require("ajv/dist/runtime/uri").default';hd.default=J_});var ob=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var iC=vs();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return iC.KeywordCxt}});var Jn=H();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Jn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Jn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Jn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Jn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Jn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Jn.CodeGen}});var aC=Sa(),tb=_s(),cC=Vl(),ws=ka(),uC=H(),xs=hs(),Ia=ms(),yd=oe(),Y_=M_(),lC=G_(),rb=(t,e)=>new RegExp(t,e);rb.code="new RegExp";var dC=["removeAdditional","useDefaults","coerceTypes"],pC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),fC={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},mC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Q_=200;function hC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,y,_,S,v,k,x,z,O,Z,De;let Y=t.strict,kt=(e=t.code)===null||e===void 0?void 0:e.optimize,wr=kt===!0||kt===void 0?1:kt||0,Ls=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:rb,Fs=(o=t.uriResolver)!==null&&o!==void 0?o:lC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Y)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Y)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Y)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Y)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:Y)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:wr,regExp:Ls}:{optimize:wr,regExp:Ls},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Q_,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Q_,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(v=t.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(z=t.validateSchema)!==null&&z!==void 0?z:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(Z=t.unicodeRegExp)!==null&&Z!==void 0?Z:!0,int32range:(De=t.int32range)!==null&&De!==void 0?De:!0,uriResolver:Fs}}var Ss=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...hC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new uC.ValueScope({scope:{},prefixes:pC,es5:r,lines:n}),this.logger=wC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,cC.getRules)(),X_.call(this,fC,e,"NOT SUPPORTED"),X_.call(this,mC,e,"DEPRECATED","warn"),this._metaOpts=_C.call(this),e.formats&&yC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&vC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),gC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Y_;n==="id"&&(o={...Y_},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof tb.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,xs.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=eb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ws.SchemaEnv({schema:{},schemaId:n});if(r=ws.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=eb.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,xs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(SC.call(this,n,r),!r)return(0,yd.eachItem)(n,s=>gd.call(this,s)),this;kC.call(this,r);let o={...r,type:(0,Ia.getJSONTypes)(r.type),schemaType:(0,Ia.getJSONTypes)(r.schemaType)};return(0,yd.eachItem)(n,o.type.length===0?s=>gd.call(this,s,o):s=>o.type.forEach(i=>gd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=nb(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,xs.normalizeId)(i||n);let u=xs.getSchemaRefs.call(this,e,n);return c=new ws.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ws.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{ws.compileSchema.call(this,e)}finally{this.opts=r}}};Ss.ValidationError=aC.default;Ss.MissingRefError=tb.default;Ae.default=Ss;function X_(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function eb(t){return t=(0,xs.normalizeId)(t),this.schemas[t]||this.refs[t]}function gC(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function yC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function vC(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function _C(){let t={...this.opts};for(let e of dC)delete t[e];return t}var bC={log(){},warn(){},error(){}};function wC(t){if(t===!1)return bC;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var xC=/^[a-z_$][a-z0-9_$:-]*$/i;function SC(t,e){let{RULES:r}=this;if((0,yd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!xC.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function gd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Ia.getJSONTypes)(e.type),schemaType:(0,Ia.getJSONTypes)(e.schemaType)}};e.before?$C.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function $C(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function kC(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=nb(e)),t.validateSchema=this.compile(e,!0))}var PC={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function nb(t){return{anyOf:[t,PC]}}});var sb=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var TC={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vd.default=TC});var ub=E(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.callRef=nn.getValidate=void 0;var EC=_s(),ib=dt(),et=H(),Gn=Gt(),ab=ka(),Aa=oe(),RC={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=ab.resolveRef.call(c,u,o,r);if(l===void 0)throw new EC.default(n.opts.uriResolver,o,r);if(l instanceof ab.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Ca(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Ca(t,(0,et._)`${m}.validate`,u,u.$async)}function p(m){let g=cb(t,m);Ca(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,et.stringify)(m)}:{ref:m}),y=e.name("valid"),_=t.subschema({schema:m,dataTypes:[],schemaPath:et.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function cb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}nn.getValidate=cb;function Ca(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Gn.default.this:et.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,ib.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,et._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,ib.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,et._)`${m}.errors`;o.assign(Gn.default.vErrors,(0,et._)`${Gn.default.vErrors} === null ? ${g} : ${Gn.default.vErrors}.concat(${g})`),o.assign(Gn.default.errors,(0,et._)`${Gn.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Aa.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,et._)`${m}.evaluated.props`);s.props=Aa.mergeEvaluated.props(o,_,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Aa.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,et._)`${m}.evaluated.items`);s.items=Aa.mergeEvaluated.items(o,_,s.items,et.Name)}}}nn.callRef=Ca;nn.default=RC});var lb=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var IC=sb(),AC=ub(),CC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",IC.default,AC.default];_d.default=CC});var db=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Da=H(),_r=Da.operators,za={maximum:{okStr:"<=",ok:_r.LTE,fail:_r.GT},minimum:{okStr:">=",ok:_r.GTE,fail:_r.LT},exclusiveMaximum:{okStr:"<",ok:_r.LT,fail:_r.GTE},exclusiveMinimum:{okStr:">",ok:_r.GT,fail:_r.LTE}},DC={message:({keyword:t,schemaCode:e})=>(0,Da.str)`must be ${za[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Da._)`{comparison: ${za[t].okStr}, limit: ${e}}`},zC={keyword:Object.keys(za),type:"number",schemaType:"number",$data:!0,error:DC,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Da._)`${r} ${za[e].fail} ${n} || isNaN(${r})`)}};bd.default=zC});var pb=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var $s=H(),OC={message:({schemaCode:t})=>(0,$s.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$s._)`{multipleOf: ${t}}`},MC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:OC,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,$s._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,$s._)`${i} !== parseInt(${i})`;t.fail$data((0,$s._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wd.default=MC});var mb=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});function fb(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}xd.default=fb;fb.code='require("ajv/dist/runtime/ucs2length").default'});var hb=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var on=H(),jC=oe(),NC=mb(),LC={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,on.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,on._)`{limit: ${t}}`},FC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:LC,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?on.operators.GT:on.operators.LT,i=o.opts.unicode===!1?(0,on._)`${r}.length`:(0,on._)`${(0,jC.useFunc)(t.gen,NC.default)}(${r})`;t.fail$data((0,on._)`${i} ${s} ${n}`)}};Sd.default=FC});var gb=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var ZC=dt(),Oa=H(),UC={message:({schemaCode:t})=>(0,Oa.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Oa._)`{pattern: ${t}}`},qC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:UC,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,Oa._)`(new RegExp(${o}, ${i}))`:(0,ZC.usePattern)(t,n);t.fail$data((0,Oa._)`!${a}.test(${e})`)}};$d.default=qC});var yb=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var ks=H(),VC={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ks.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ks._)`{limit: ${t}}`},BC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:VC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ks.operators.GT:ks.operators.LT;t.fail$data((0,ks._)`Object.keys(${r}).length ${o} ${n}`)}};kd.default=BC});var vb=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Ps=dt(),Ts=H(),WC=oe(),HC={message:({params:{missingProperty:t}})=>(0,Ts.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ts._)`{missingProperty: ${t}}`},KC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:HC,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(f?.[g]===void 0&&!m.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,WC.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ts.nil,d);else for(let f of r)(0,Ps.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Ps.checkMissingProp)(t,r,f)),(0,Ps.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ps.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ps.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Ts.not)(m),()=>{t.error(),e.break()})},Ts.nil)}}};Pd.default=KC});var _b=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Es=H(),JC={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Es.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Es._)`{limit: ${t}}`},GC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:JC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Es.operators.GT:Es.operators.LT;t.fail$data((0,Es._)`${r}.length ${o} ${n}`)}};Td.default=GC});var Ma=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var bb=Ql();bb.code='require("ajv/dist/runtime/equal").default';Ed.default=bb});var wb=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var Rd=ms(),Ce=H(),YC=oe(),QC=Ma(),XC={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},eD={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:XC,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Rd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ce._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Ce._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Ce._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let y=e.name("item"),_=(0,Rd.checkDataTypes)(u,y,a.opts.strictNumbers,Rd.DataType.Wrong),S=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${m}--;`,()=>{e.let(y,(0,Ce._)`${r}[${m}]`),e.if(_,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${y} == "string"`,(0,Ce._)`${y} += "_"`),e.if((0,Ce._)`typeof ${S}[${y}] == "number"`,()=>{e.assign(g,(0,Ce._)`${S}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ce._)`${S}[${y}] = ${m}`)})}function f(m,g){let y=(0,YC.useFunc)(e,QC.default),_=e.name("outer");e.label(_).for((0,Ce._)`;${m}--;`,()=>e.for((0,Ce._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Ce._)`${y}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Id.default=eD});var xb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Ad=H(),tD=oe(),rD=Ma(),nD={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ad._)`{allowedValue: ${t}}`},oD={keyword:"const",$data:!0,error:nD,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ad._)`!${(0,tD.useFunc)(e,rD.default)}(${r}, ${o})`):t.fail((0,Ad._)`${s} !== ${r}`)}};Cd.default=oD});var Sb=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Rs=H(),sD=oe(),iD=Ma(),aD={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Rs._)`{allowedValues: ${t}}`},cD={keyword:"enum",schemaType:"array",$data:!0,error:aD,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,sD.useFunc)(e,iD.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Rs.or)(...o.map((m,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Rs._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Rs._)`${u()}(${r}, ${f}[${m}])`:(0,Rs._)`${r} === ${g}`}}};Dd.default=cD});var $b=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var uD=db(),lD=pb(),dD=hb(),pD=gb(),fD=yb(),mD=vb(),hD=_b(),gD=wb(),yD=xb(),vD=Sb(),_D=[uD.default,lD.default,dD.default,pD.default,fD.default,mD.default,hD.default,gD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yD.default,vD.default];zd.default=_D});var Md=E(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.validateAdditionalItems=void 0;var sn=H(),Od=oe(),bD={message:({params:{len:t}})=>(0,sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sn._)`{limit: ${t}}`},wD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:bD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Od.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}kb(t,n)}};function kb(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,sn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Od.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,sn._)`${a} <= ${e.length}`);r.if((0,sn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Od.Type.Num},u),i.allErrors||r.if((0,sn.not)(u),()=>r.break())})}}Is.validateAdditionalItems=kb;Is.default=wD});var jd=E(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.validateTuple=void 0;var Pb=H(),ja=oe(),xD=dt(),SD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Tb(t,"additionalItems",e);r.items=!0,!(0,ja.alwaysValidSchema)(r,e)&&t.ok((0,xD.validateArray)(t))}};function Tb(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ja.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Pb._)`${s}.length`);r.forEach((d,p)=>{(0,ja.alwaysValidSchema)(a,d)||(n.if((0,Pb._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,g=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ja.checkStrictMode)(a,y,p.strictTuples)}}}As.validateTuple=Tb;As.default=SD});var Eb=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var $D=jd(),kD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,$D.validateTuple)(t,"items")};Nd.default=kD});var Ib=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Rb=H(),PD=oe(),TD=dt(),ED=Md(),RD={message:({params:{len:t}})=>(0,Rb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Rb._)`{limit: ${t}}`},ID={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:RD,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,PD.alwaysValidSchema)(n,e)&&(o?(0,ED.validateAdditionalItems)(t,o):t.ok((0,TD.validateArray)(t)))}};Ld.default=ID});var Ab=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var ft=H(),Na=oe(),AD={message:({params:{min:t,max:e}})=>e===void 0?(0,ft.str)`must contain at least ${t} valid item(s)`:(0,ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ft._)`{minContains: ${t}}`:(0,ft._)`{minContains: ${t}, maxContains: ${e}}`},CD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:AD,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Na.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Na.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Na.alwaysValidSchema)(s,r)){let g=(0,ft._)`${l} >= ${i}`;a!==void 0&&(g=(0,ft._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ft._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),y=e.let("count",0);f(g,()=>e.if(g,()=>m(y)))}function f(g,y){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Na.Type.Num,compositeRule:!0},g),y()})}function m(g){e.code((0,ft._)`${g}++`),a===void 0?e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ft._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Fd.default=CD});var zb=E(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var Zd=H(),DD=oe(),Cs=dt();Ot.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zd._)`{property: ${t},
9
9
  missingProperty: ${n},
10
10
  depsCount: ${e},
11
- deps: ${r}}`};var TD={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=ED(t);Tb(t,e),Eb(t,r)}};function ED({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 Tb(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,As.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,As.checkReportMissingProp)(t,u)}):(r.if((0,jd._)`${c} && (${(0,As.checkMissingProp)(t,a,s)})`),(0,As.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=Tb;function Eb(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,PD.alwaysValidSchema)(s,e[a])||(r.if((0,As.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=Eb;Ot.default=TD});var Ab=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Ib=H(),RD=oe(),ID={message:"property name must be valid",params:({params:t})=>(0,Ib._)`{propertyName: ${t.propertyName}}`},AD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ID,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,RD.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,Ib.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ld.default=AD});var Zd=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var ja=dt(),xt=H(),CD=Gt(),La=oe(),DD={message:"must NOT have additional properties",params:({params:t})=>(0,xt._)`{additionalProperty: ${t.additionalProperty}}`},zD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:DD,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,La.alwaysValidSchema)(i,r))return;let u=(0,ja.allSchemaProperties)(n.properties),l=(0,ja.allSchemaProperties)(n.patternProperties);d(),t.ok((0,xt._)`${s} === ${CD.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 v;if(u.length>8){let x=(0,La.schemaRefOrVal)(i,n.properties,"properties");v=(0,ja.isOwnProperty)(e,x,y)}else u.length?v=(0,xt.or)(...u.map(x=>(0,xt._)`${y} === ${x}`)):v=xt.nil;return l.length&&(v=(0,xt.or)(v,...l.map(x=>(0,xt._)`${(0,ja.usePattern)(t,x)}.test(${y})`))),(0,xt.not)(v)}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,La.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(g(y,v,!1),e.if((0,xt.not)(v),()=>{t.reset(),f(y)})):(g(y,v),a||e.if((0,xt.not)(v),()=>e.break()))}}function g(y,v,x){let _={keyword:"additionalProperties",dataProp:y,dataPropType:La.Type.Str};x===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,v)}}};Fd.default=zD});var zb=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var OD=ys(),Cb=dt(),Ud=oe(),Db=Zd(),MD={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&&Db.default.code(new OD.KeywordCxt(s,Db.default,"additionalProperties"));let i=(0,Cb.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ud.mergeEvaluated.props(e,(0,Ud.toHash)(i),s.props));let a=i.filter(d=>!(0,Ud.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,Cb.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)}}};qd.default=MD});var jb=E(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Ob=dt(),Fa=H(),Mb=oe(),Nb=oe(),ND={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,Ob.allSchemaProperties)(r),c=a.filter(g=>(0,Mb.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 Fa.Name)&&(s.props=(0,Nb.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,Mb.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,Fa._)`${(0,Ob.usePattern)(t,g)}.test(${y})`,()=>{let v=c.includes(g);v||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Nb.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Fa._)`${d}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Fa.not)(l),()=>e.break())})})}}};Vd.default=ND});var Lb=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var jD=oe(),LD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,jD.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"}};Bd.default=LD});var Fb=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var FD=dt(),ZD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:FD.validateUnion,error:{message:"must match a schema in anyOf"}};Wd.default=ZD});var Zb=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Za=H(),UD=oe(),qD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Za._)`{passingSchemas: ${t.passing}}`},VD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qD,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,UD.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Za._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Za._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Za.Name)})})}}};Hd.default=VD});var Ub=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var BD=oe(),WD={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,BD.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Kd.default=WD});var Bb=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var Ua=H(),Vb=oe(),HD={message:({params:t})=>(0,Ua.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ua._)`{failingKeyword: ${t.ifClause}}`},KD={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:HD,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Vb.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,Ua.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,Ua._)`${l}`):t.setParams({ifClause:l})}}}};function qb(t,e){let r=t.schema[e];return r!==void 0&&!(0,Vb.alwaysValidSchema)(t,r)}Gd.default=KD});var Wb=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var GD=oe(),JD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,GD.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Jd.default=JD});var Hb=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var QD=Dd(),YD=Sb(),XD=zd(),ez=kb(),tz=Pb(),rz=Rb(),nz=Ab(),oz=Zd(),sz=zb(),iz=jb(),az=Lb(),cz=Fb(),uz=Zb(),lz=Ub(),dz=Bb(),pz=Wb();function fz(t=!1){let e=[az.default,cz.default,uz.default,lz.default,dz.default,pz.default,nz.default,oz.default,rz.default,sz.default,iz.default];return t?e.push(YD.default,ez.default):e.push(QD.default,XD.default),e.push(tz.default),e}Qd.default=fz});var Kb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var ke=H(),mz={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},hz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mz,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"),v=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${g}.type || "string"`).assign(v,(0,ke._)`${g}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(v,g)),t.fail$data((0,ke.or)(x(),_()));function x(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${v}`}function _(){let P=l.$async?(0,ke._)`(${g}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ke._)`${v}(${n})`,S=(0,ke._)`(typeof ${v} == "function" ? ${P} : ${v}.test(${n}))`;return(0,ke._)`${v} && ${v} !== 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 _(S){let z=S instanceof RegExp?(0,ke.regexpCode)(S):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:S,code:z});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,ke._)`${O}.validate`]:["string",S,O]}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 ${v}(${n})`}return typeof y=="function"?(0,ke._)`${v}(${n})`:(0,ke._)`${v}.test(${n})`}}}};Yd.default=hz});var Gb=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var gz=Kb(),yz=[gz.default];Xd.default=yz});var Jb=E(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.contentVocabulary=Qn.metadataVocabulary=void 0;Qn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Qn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Yb=E(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var vz=sb(),_z=_b(),bz=Hb(),wz=Gb(),Qb=Jb(),xz=[vz.default,_z.default,(0,bz.default)(),wz.default,Qb.metadataVocabulary,Qb.contentVocabulary];ep.default=xz});var ew=E(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.DiscrError=void 0;var Xb;(function(t){t.Tag="tag",t.Mapping="mapping"})(Xb||(qa.DiscrError=Xb={}))});var rw=E(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var Yn=H(),tp=ew(),tw=$a(),Sz=vs(),$z=oe(),kz={message:({params:{discrError:t,tagName:e}})=>t===tp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Yn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Pz={keyword:"discriminator",type:"object",schemaType:"object",error:kz,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,Yn._)`${r}${(0,Yn.getProperty)(a)}`);e.if((0,Yn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:tp.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,Yn._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:tp.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,Yn.Name),m}function p(){var f;let m={},g=v(o),y=!0;for(let P=0;P<i.length;P++){let S=i[P];if(S?.$ref&&!(0,$z.schemaHasRulesButRef)(S,s.self.RULES)){let O=S.$ref;if(S=tw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),S instanceof tw.SchemaEnv&&(S=S.schema),S===void 0)throw new Sz.default(s.opts.uriResolver,s.baseId,O)}let z=(f=S?.properties)===null||f===void 0?void 0:f[a];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||v(S)),x(z,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:P}){return Array.isArray(P)&&P.includes(a)}function x(P,S){if(P.const)_(P.const,S);else if(P.enum)for(let z of P.enum)_(z,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(P,S){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=S}}}};rp.default=Pz});var nw=E((J4,Tz)=>{Tz.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 op=E((ye,np)=>{"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 Ez=X_(),Rz=Yb(),Iz=rw(),ow=nw(),Az=["/properties"],Va="http://json-schema.org/draft-07/schema",Xn=class extends Ez.default{_addVocabularies(){super._addVocabularies(),Rz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Iz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ow,Az):ow;this.addMetaSchema(e,Va,!1),this.refs["http://json-schema.org/schema"]=Va}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Va)?Va:void 0)}};ye.Ajv=Xn;np.exports=ye=Xn;np.exports.Ajv=Xn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Xn;var Cz=ys();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return Cz.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 Dz=xa();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return Dz.default}});var zz=vs();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return zz.default}})});var pw=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(cw,cp),time:Mt(ip(!0),up),"date-time":Mt(sw(!0),lw),"iso-time":Mt(ip(),uw),"iso-date-time":Mt(sw(),dw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Fz,"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:Hz,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:Zz,int32:{type:"number",validate:Vz},int64:{type:"number",validate:Bz},float:{type:"number",validate:aw},double:{type:"number",validate:aw},password:!0,binary:!0};Nt.fastFormats={...Nt.fullFormats,date:Mt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,cp),time:Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,up),"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,lw),"iso-time":Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,uw),"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,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};Nt.formatNames=Object.keys(Nt.fullFormats);function Oz(t){return t%4===0&&(t%100!==0||t%400===0)}var Mz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Nz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function cw(t){let e=Mz.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&&Oz(r)?29:Nz[n])}function cp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var sp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ip(t){return function(r){let n=sp.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 up(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 uw(t,e){if(!(t&&e))return;let r=sp.exec(t),n=sp.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 ap=/t|\s/i;function sw(t){let e=ip(t);return function(n){let o=n.split(ap);return o.length===2&&cw(o[0])&&e(o[1])}}function lw(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(ap),[o,s]=e.split(ap),i=cp(r,o);if(i!==void 0)return i||up(n,s)}var jz=/\/|:/,Lz=/^(?:[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 Fz(t){return jz.test(t)&&Lz.test(t)}var iw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Zz(t){return iw.lastIndex=0,iw.test(t)}var Uz=-(2**31),qz=2**31-1;function Vz(t){return Number.isInteger(t)&&t<=qz&&t>=Uz}function Bz(t){return Number.isInteger(t)}function aw(){return!0}var Wz=/[^\\]\\Z/;function Hz(t){if(Wz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var fw=E(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.formatLimitDefinition=void 0;var Kz=op(),St=H(),br=St.operators,Ba={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}},Gz={message:({keyword:t,schemaCode:e})=>(0,St.str)`should be ${Ba[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,St._)`{comparison: ${Ba[t].okStr}, limit: ${e}}`};to.formatLimitDefinition={keyword:Object.keys(Ba),type:"string",schemaType:"string",$data:!0,error:Gz,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 Kz.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}) ${Ba[o].fail} 0`}},dependencies:["format"]};var Jz=t=>(t.addKeyword(to.formatLimitDefinition),t);to.default=Jz});var yw=E((Cs,gw)=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var ro=pw(),Qz=fw(),lp=H(),mw=new lp.Name("fullFormats"),Yz=new lp.Name("fastFormats"),dp=(t,e={keywords:!0})=>{if(Array.isArray(e))return hw(t,e,ro.fullFormats,mw),t;let[r,n]=e.mode==="fast"?[ro.fastFormats,Yz]:[ro.fullFormats,mw],o=e.formats||ro.formatNames;return hw(t,o,r,n),e.keywords&&(0,Qz.default)(t),t};dp.get=(t,e="full")=>{let n=(e==="fast"?ro.fastFormats:ro.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function hw(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,lp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}gw.exports=Cs=dp;Object.defineProperty(Cs,"__esModule",{value:!0});Cs.default=dp});import{readFileSync as LN}from"fs";import{join as Pc}from"path";import{fileURLToPath as FN}from"url";var cn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Fs=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}},We=class extends cn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var lf={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"}},IS={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 Dc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Vs(t,e,r,n=t){let o=lf[n]??lf[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Dc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function er(t,e){let r=IS[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 Bs={low:0,medium:.5,high:.7},AS={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 df(t,e){return e?.[t]??AS[t]??"low"}function Ws(t,e,r=Bs){return t>=r[e]}var Hs=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 Fs(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 Vs(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??er(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??df(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 Ws(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={};Be(h,{BRAND:()=>n$,DIRTY:()=>$r,EMPTY_PATH:()=>OS,INVALID:()=>N,NEVER:()=>Z$,OK:()=>Oe,ParseStatus:()=>Te,Schema:()=>B,ZodAny:()=>nr,ZodArray:()=>qt,ZodBigInt:()=>Pr,ZodBoolean:()=>Tr,ZodBranded:()=>go,ZodCatch:()=>jr,ZodDate:()=>Er,ZodDefault:()=>Nr,ZodDiscriminatedUnion:()=>Js,ZodEffects:()=>it,ZodEnum:()=>Or,ZodError:()=>He,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>Ys,ZodIntersection:()=>Cr,ZodIssueCode:()=>$,ZodLazy:()=>Dr,ZodLiteral:()=>zr,ZodMap:()=>bn,ZodNaN:()=>xn,ZodNativeEnum:()=>Mr,ZodNever:()=>mt,ZodNull:()=>Ir,ZodNullable:()=>Et,ZodNumber:()=>kr,ZodObject:()=>Ke,ZodOptional:()=>ot,ZodParsedType:()=>R,ZodPipeline:()=>yo,ZodPromise:()=>or,ZodReadonly:()=>Lr,ZodRecord:()=>Qs,ZodSchema:()=>B,ZodSet:()=>wn,ZodString:()=>rr,ZodSymbol:()=>vn,ZodTransformer:()=>it,ZodTuple:()=>Tt,ZodType:()=>B,ZodUndefined:()=>Rr,ZodUnion:()=>Ar,ZodUnknown:()=>Ut,ZodVoid:()=>_n,addIssueToContext:()=>T,any:()=>p$,array:()=>g$,bigint:()=>a$,boolean:()=>xf,coerce:()=>F$,custom:()=>_f,date:()=>c$,datetimeRegex:()=>yf,defaultErrorMap:()=>Ft,discriminatedUnion:()=>b$,effect:()=>C$,enum:()=>R$,function:()=>P$,getErrorMap:()=>hn,getParsedType:()=>Pt,instanceof:()=>s$,intersection:()=>w$,isAborted:()=>Ks,isAsync:()=>gn,isDirty:()=>Gs,isValid:()=>tr,late:()=>o$,lazy:()=>T$,literal:()=>E$,makeIssue:()=>ho,map:()=>$$,nan:()=>i$,nativeEnum:()=>I$,never:()=>m$,null:()=>d$,nullable:()=>z$,number:()=>wf,object:()=>y$,objectUtil:()=>zc,oboolean:()=>L$,onumber:()=>j$,optional:()=>D$,ostring:()=>N$,pipeline:()=>M$,preprocess:()=>O$,promise:()=>A$,quotelessJson:()=>CS,record:()=>S$,set:()=>k$,setErrorMap:()=>zS,strictObject:()=>v$,string:()=>bf,symbol:()=>u$,transformer:()=>C$,tuple:()=>x$,undefined:()=>l$,union:()=>_$,unknown:()=>f$,util:()=>J,void:()=>h$});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 zc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(zc||(zc={}));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"]),CS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),He=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,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()}};He.create=t=>new He(t);var DS=(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=DS;var pf=Ft;function zS(t){pf=t}function hn(){return pf}var ho=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}},OS=[];function T(t,e){let r=hn(),n=ho({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 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"}),$r=t=>({status:"dirty",value:t}),Oe=t=>({status:"valid",value:t}),Ks=t=>t.status==="aborted",Gs=t=>t.status==="dirty",tr=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}},ff=(t,e)=>{if(tr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new He(t.common.issues);return this._error=r,this._error}}};function 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 ff(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 tr(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=>tr(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 ff(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 or.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 go({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 yo.create(this,e)}readonly(){return Lr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},MS=/^c[^\s-]{8,}$/i,NS=/^[0-9a-z]+$/,jS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,LS=/^[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,FS=/^[a-z0-9_-]{21}$/i,ZS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,US=/^[-+]?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)?)??$/,qS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,VS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Oc,BS=/^(?:(?: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])$/,WS=/^(?:(?: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])$/,HS=/^(([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]))$/,KS=/^(([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])$/,GS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,JS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hf="((\\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])))",QS=new RegExp(`^${hf}$`);function gf(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 YS(t){return new RegExp(`^${gf(t)}$`)}function yf(t){let e=`${hf}T${gf(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 XS(t,e){return!!((e==="v4"||!e)&&BS.test(t)||(e==="v6"||!e)&&HS.test(t))}function e$(t,e){if(!ZS.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$(t,e){return!!((e==="v4"||!e)&&WS.test(t)||(e==="v6"||!e)&&KS.test(t))}var rr=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}),N}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")qS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Oc||(Oc=new RegExp(VS,"u")),Oc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")LS.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")FS.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")MS.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")NS.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")jS.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"?yf(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?QS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?YS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?US.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?XS(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?e$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?t$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?GS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?JS.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}};rr.create=t=>new rr({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...U(t)});function r$(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}),N}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"?r$(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}),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}};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}),N}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}),N}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_date}),N}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}),N}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}),N}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}),N}return Oe(e.data)}};Ir.create=t=>new Ir({typeName:k.ZodNull,...U(t)});var nr=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}};nr.create=t=>new nr({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}),N}};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}),N}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}),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?$.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 Ke){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ot.create(yn(n))}return new Ke({...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 Ke=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}),N}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 vf(J.objectKeys(this.shape))}};Ke.create=(t,e)=>new Ke({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:k.ZodObject,...U(e)});Ke.strictCreate=(t,e)=>new Ke({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:k.ZodObject,...U(e)});Ke.lazycreate=(t,e)=>new Ke({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 He(a.ctx.common.issues));return T(r,{code:$.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 He(c));return T(r,{code:$.invalid_union,unionErrors:a}),N}}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 go||t instanceof Lr?Zt(t.unwrap()):t instanceof jr?Zt(t._def.innerType):[],Js=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}),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:$.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=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 Mc(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=Mc(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=Mc(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(Ks(s)||Ks(i))return N;let a=Mc(s.value,i.value);return a.valid?((Gs(s)||Gs(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:$.invalid_intersection_types}),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}))}};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}),N;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"}),N;!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 Qs=class t extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:$.invalid_type,expected:R.object,received:n.parsedType}),N;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:rr.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}),N;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 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}}}};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}),N;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 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 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 Ys=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}),N;function n(a,c){return ho({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 ho({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 or){let a=this;return Oe(async function(...c){let u=new He([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Oe(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new He([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new He([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Tt.create(e).rest(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}),N}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 vf(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}),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:$.invalid_enum_value,options:n}),N}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=vf;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}),N}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}),N}return Oe(e.data)}get enum(){return this._def.values}};Mr.create=(t,e)=>new Mr({values:t,typeName:k.ZodNativeEnum,...U(e)});var or=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}),N;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})))}};or.create=(t,e)=>new or({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 N;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?N:c.status==="dirty"?$r(c.value):r.value==="dirty"?$r(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"?$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"?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(!tr(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=>tr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):N);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 He(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new He(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};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}),N}return{status:"valid",value:e.data}}};xn.create=t=>new xn({typeName:k.ZodNaN,...U(t)});var n$=Symbol("zod_brand"),go=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}},yo=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"?N: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"?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:k.ZodPipeline})}},Lr=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(tr(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 mf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function _f(t,e={},r){return t?nr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=mf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=mf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):nr.create()}var o$={object:Ke.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 s$=(t,e={message:`Input not instance of ${t.name}`})=>_f(r=>r instanceof t,e),bf=rr.create,wf=kr.create,i$=xn.create,a$=Pr.create,xf=Tr.create,c$=Er.create,u$=vn.create,l$=Rr.create,d$=Ir.create,p$=nr.create,f$=Ut.create,m$=mt.create,h$=_n.create,g$=qt.create,y$=Ke.create,v$=Ke.strictCreate,_$=Ar.create,b$=Js.create,w$=Cr.create,x$=Tt.create,S$=Qs.create,$$=bn.create,k$=wn.create,P$=Ys.create,T$=Dr.create,E$=zr.create,R$=Or.create,I$=Mr.create,A$=or.create,C$=it.create,D$=ot.create,z$=Et.create,O$=it.createWithPreprocess,M$=yo.create,N$=()=>bf().optional(),j$=()=>wf().optional(),L$=()=>xf().optional(),F$={string:(t=>rr.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 Z$=N;jt();var U$=h.enum(["read-only","workspace-write","full-auto"]),q$=U$.default("read-only"),V$=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:q$,config:h.record(h.unknown()).default({})}),B$=h.enum(["default-only","auto"]).default("default-only"),W$=h.object({defaultProvider:h.string().optional(),selectionPolicy:B$,locale:h.string().optional(),providers:h.array(V$).min(1,"At least one provider required")});function sr(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":return"workspace-write";default:return"read-only"}}function Xs(t){return t==="workspace-write"||t==="full-auto"}function H$(t){return qs.includes(t)}function K$(t){if(t!==void 0)return H$(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${xr}`),xr)}function Sf(t){let e=W$.parse(t);return{defaultProvider:e.defaultProvider,selectionPolicy:e.selectionPolicy,locale:K$(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}ri();bo();mo();mn();jt();import{mkdirSync as zf,readFileSync as Rt,readdirSync as qc,existsSync as ir,unlinkSync as vk,rmdirSync as _k}from"fs";import{join as ce}from"path";import{spawn as Of}from"child_process";import{randomUUID as bk}from"crypto";function Zr(t,e){let r=ce(t,"status.json"),n=JSON.parse(Rt(r,"utf-8"));Ge(r,{...n,...e})}var si=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;constructor(e=process.cwd(),r){this.jobsDir=ce(e,Hp),zf(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7}submit(e){let r=`${e.provider}-${Date.now()}-${bk().slice(0,6)}`,n=ce(this.jobsDir,r);zf(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 Ge(ce(n,"job.json"),o),Ge(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(!ni(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 Ge(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(!ni(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=qc(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(!ni(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 Ge(ce(n,"status.json"),o),this.statusCache.set(e,o),!0}cleanup(){if(!ir(this.jobsDir))return 0;let e=qc(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=qc(f);for(let g of m)vk(ce(f,g));_k(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=Of(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(()=>(Df(),Cf)).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=Of(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(()=>{Xt(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 v=d.trim().length>0;Zr(e,{state:y===0||v?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()})}),l.on("error",y=>{clearTimeout(g);let v=y.code==="ENOENT"?"missing_cli":"error";se(ce(e,"error.txt"),y.message),Zr(e,{state:v,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{}})}};ri();jt();import{mkdirSync as wk,readdirSync as Mf,readFileSync as xk,unlinkSync as Sk}from"fs";import{join as wo}from"path";function Nf(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 $k(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function kk(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var ii=class{tracesDir;writer;constructor(e,r){this.tracesDir=wo(e,Kp),wk(this.tracesDir,{recursive:!0}),this.writer=new ei(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Nf(new Date(r.timestamp)),o=wo(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=xk(i,"utf-8").split(`
13
- `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);kk(u)?o.push(u):$k(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=Nf(o),a=wo(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=Mf(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&&(Sk(wo(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=Mf(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=>wo(this.tracesDir,n))}};var Pk=/[;|&`$(){}!><\n\r\\]/,ai=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),Tk=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 jf(t){if(Pk.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(!ai.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...ai].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(Tk.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}jt();var Lf=[{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"}],Ff=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function Zf(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 Lf){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!Ff.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 Vc(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 Lf){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>Ff.some(a=>a.test(i))?i:cf)}e[r]=n}return e.join(`
17
- `)}jt();import{execFileSync as Ek}from"child_process";import{existsSync as Uf,rmSync as Rk,mkdirSync as Ik}from"fs";import{join as qf}from"path";var ci=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=qf(e,Gp)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=qf(this.worktreeBaseDir,r);Ik(this.worktreeBaseDir,{recursive:!0}),Uf(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&&(Uf(e)&&Rk(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return Ek("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var Ak=["npm","node","git","tsc"];function Vf(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:[...Ak]},timeout_minutes:t.timeoutMinutes??10}}function Bf(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 ui=10,Bc=2e4;import{spawn as Nk}from"child_process";import{writeFileSync as Hc,mkdirSync as jk,readFileSync as Gf,existsSync as Jf}from"fs";import{isAbsolute as Qf,join as xo,resolve as Yf}from"path";import{randomBytes as Lk}from"crypto";import{execFileSync as Fk}from"child_process";jt();mn();mo();bo();bo();import{readFileSync as Wf}from"fs";var Wc=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 Ck(t,e,r){let n=Hf(t,e,r);return{command:"codex",args:["exec","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function Dk(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",Hf(t,e,r)]}}function Hf(t,e,r){let n=Wf(t,"utf-8"),o=zk(r,e);return["You are an autonomous coding worker operating in the current workspace.","Execute the task manifest below without asking for confirmation.","Stay within the workspace, respect read-only vs read-write boundaries, and summarize changes plus verification at the end.","",n,o].join(`
19
- `)}function Kf(){let t=new Wc;return t.register("codex",Ck),t.register("gemini",Dk),t}function zk(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!Zc(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,ui))try{let s=Wf(o,"utf-8"),i=s.length>Bc?`${s.slice(0,Bc)}
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>ui&&(n.push(`...[${r.length-ui} additional read-only files omitted]`),n.push("")),n.join(`
21
- `)}var So=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=xo(e,ef),this.worktreeManager=new ci(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??Kf()}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=Zf(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=Lk(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=xo(this.workersBaseDir,c);jk(u,{recursive:!0});let l=Vf({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=Bf(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=xo(u,"task-manifest.json");Hc(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=xo(u,"stdout.log"),g=xo(u,"stderr.log"),y=f?.path??r,v=this.cliBuilderRegistry.build(e.provider,p,y,n),x=Lt(v.command,v.args),_=Nk(x.command,x.args,{cwd:y,env:t.buildWorkerEnv(),detached:!0,stdio:[v.stdin?"pipe":"ignore","pipe","pipe"]}),P=[],S=[];_.stdout?.on("data",Z=>P.push(Z)),_.stderr?.on("data",Z=>S.push(Z)),v.stdin!==void 0&&_.stdin?.end(v.stdin),_.unref();let z={workerId:c,provider:e.provider,state:$e.RUNNING,pid:_.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},O={info:z,process:_,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,O),e.timeoutMinutes){let Z=e.timeoutMinutes*6e4;setTimeout(()=>{if(O.info.state===$e.RUNNING){O.info.state=$e.TIMEOUT,O.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let Q=O.process?.pid;Q&&pn(Q)}},Z).unref()}return _.on("close",Z=>{O.info.exitCode=Z;try{Hc(m,Buffer.concat(P).toString("utf-8")),Hc(g,Buffer.concat(S).toString("utf-8"))}catch{}O.info.state===$e.CANCELLING?O.info.state=$e.CANCELLED:Z===0?O.info.state=$e.COLLECTING:(O.info.state=$e.FAILED,O.info.error=`Process exited with code ${Z}`)}),z}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{Jf(r.outputPath)&&(o=Gf(r.outputPath,"utf-8").split(`
11
+ deps: ${r}}`};var zD={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=OD(t);Cb(t,e),Db(t,r)}};function OD({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Cb(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Cs.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Cs.checkReportMissingProp)(t,u)}):(r.if((0,Zd._)`${c} && (${(0,Cs.checkMissingProp)(t,a,s)})`),(0,Cs.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=Cb;function Db(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,DD.alwaysValidSchema)(s,e[a])||(r.if((0,Cs.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ot.validateSchemaDeps=Db;Ot.default=zD});var Mb=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Ob=H(),MD=oe(),jD={message:"property name must be valid",params:({params:t})=>(0,Ob._)`{propertyName: ${t.propertyName}}`},ND={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jD,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,MD.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Ob.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ud.default=ND});var Vd=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var La=dt(),xt=H(),LD=Gt(),Fa=oe(),FD={message:"must NOT have additional properties",params:({params:t})=>(0,xt._)`{additionalProperty: ${t.additionalProperty}}`},ZD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:FD,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Fa.alwaysValidSchema)(i,r))return;let u=(0,La.allSchemaProperties)(n.properties),l=(0,La.allSchemaProperties)(n.patternProperties);d(),t.ok((0,xt._)`${s} === ${LD.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let _;if(u.length>8){let S=(0,Fa.schemaRefOrVal)(i,n.properties,"properties");_=(0,La.isOwnProperty)(e,S,y)}else u.length?_=(0,xt.or)(...u.map(S=>(0,xt._)`${y} === ${S}`)):_=xt.nil;return l.length&&(_=(0,xt.or)(_,...l.map(S=>(0,xt._)`${(0,La.usePattern)(t,S)}.test(${y})`))),(0,xt.not)(_)}function f(y){e.code((0,xt._)`delete ${o}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Fa.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(y,_,!1),e.if((0,xt.not)(_),()=>{t.reset(),f(y)})):(g(y,_),a||e.if((0,xt.not)(_),()=>e.break()))}}function g(y,_,S){let v={keyword:"additionalProperties",dataProp:y,dataPropType:Fa.Type.Str};S===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(v,_)}}};qd.default=ZD});var Lb=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var UD=vs(),jb=dt(),Bd=oe(),Nb=Vd(),qD={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Nb.default.code(new UD.KeywordCxt(s,Nb.default,"additionalProperties"));let i=(0,jb.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Bd.mergeEvaluated.props(e,(0,Bd.toHash)(i),s.props));let a=i.filter(d=>!(0,Bd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,jb.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Wd.default=qD});var qb=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Fb=dt(),Za=H(),Zb=oe(),Ub=oe(),VD={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Fb.allSchemaProperties)(r),c=a.filter(g=>(0,Zb.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Za.Name)&&(s.props=(0,Ub.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?m(g):(e.var(l,!0),m(g),e.if(l))}function f(g){for(let y in u)new RegExp(g).test(y)&&(0,Zb.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,Za._)`${(0,Fb.usePattern)(t,g)}.test(${y})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Ub.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Za._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Za.not)(l),()=>e.break())})})}}};Hd.default=VD});var Vb=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var BD=oe(),WD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,BD.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Kd.default=WD});var Bb=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var HD=dt(),KD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:HD.validateUnion,error:{message:"must match a schema in anyOf"}};Jd.default=KD});var Wb=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var Ua=H(),JD=oe(),GD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ua._)`{passingSchemas: ${t.passing}}`},YD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:GD,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,JD.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ua._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ua._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ua.Name)})})}}};Gd.default=YD});var Hb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var QD=oe(),XD={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,QD.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Yd.default=XD});var Gb=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var qa=H(),Jb=oe(),ez={message:({params:t})=>(0,qa.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,qa._)`{failingKeyword: ${t.ifClause}}`},tz={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ez,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Jb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Kb(n,"then"),s=Kb(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,qa.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,qa._)`${l}`):t.setParams({ifClause:l})}}}};function Kb(t,e){let r=t.schema[e];return r!==void 0&&!(0,Jb.alwaysValidSchema)(t,r)}Qd.default=tz});var Yb=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var rz=oe(),nz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,rz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Xd.default=nz});var Qb=E(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var oz=Md(),sz=Eb(),iz=jd(),az=Ib(),cz=Ab(),uz=zb(),lz=Mb(),dz=Vd(),pz=Lb(),fz=qb(),mz=Vb(),hz=Bb(),gz=Wb(),yz=Hb(),vz=Gb(),_z=Yb();function bz(t=!1){let e=[mz.default,hz.default,gz.default,yz.default,vz.default,_z.default,lz.default,dz.default,uz.default,pz.default,fz.default];return t?e.push(sz.default,az.default):e.push(oz.default,iz.default),e.push(cz.default),e}ep.default=bz});var Xb=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ke=H(),wz={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},xz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:wz,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ke._)`${m}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(S(),v()));function S(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function v(){let k=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,x=(0,ke._)`(typeof ${_} == "function" ? ${k} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[g,y,_]=v(m);g===e&&t.pass(k());function S(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(x){let z=x instanceof RegExp?(0,ke.regexpCode)(x):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:x,code:z});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,ke._)`${O}.validate`]:["string",x,O]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof y=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};tp.default=xz});var ew=E(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var Sz=Xb(),$z=[Sz.default];rp.default=$z});var tw=E(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.contentVocabulary=Yn.metadataVocabulary=void 0;Yn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Yn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var nw=E(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var kz=lb(),Pz=$b(),Tz=Qb(),Ez=ew(),rw=tw(),Rz=[kz.default,Pz.default,(0,Tz.default)(),Ez.default,rw.metadataVocabulary,rw.contentVocabulary];np.default=Rz});var sw=E(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.DiscrError=void 0;var ow;(function(t){t.Tag="tag",t.Mapping="mapping"})(ow||(Va.DiscrError=ow={}))});var aw=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var Qn=H(),op=sw(),iw=ka(),Iz=_s(),Az=oe(),Cz={message:({params:{discrError:t,tagName:e}})=>t===op.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Qn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Dz={keyword:"discriminator",type:"object",schemaType:"object",error:Cz,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Qn._)`${r}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:op.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,Qn._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:op.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,Qn.Name),m}function p(){var f;let m={},g=_(o),y=!0;for(let k=0;k<i.length;k++){let x=i[k];if(x?.$ref&&!(0,Az.schemaHasRulesButRef)(x,s.self.RULES)){let O=x.$ref;if(x=iw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),x instanceof iw.SchemaEnv&&(x=x.schema),x===void 0)throw new Iz.default(s.opts.uriResolver,s.baseId,O)}let z=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||_(x)),S(z,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:k}){return Array.isArray(k)&&k.includes(a)}function S(k,x){if(k.const)v(k.const,x);else if(k.enum)for(let z of k.enum)v(z,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(k,x){if(typeof k!="string"||k in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[k]=x}}}};sp.default=Dz});var cw=E((wB,zz)=>{zz.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ap=E((ye,ip)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var Oz=ob(),Mz=nw(),jz=aw(),uw=cw(),Nz=["/properties"],Ba="http://json-schema.org/draft-07/schema",Xn=class extends Oz.default{_addVocabularies(){super._addVocabularies(),Mz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(jz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(uw,Nz):uw;this.addMetaSchema(e,Ba,!1),this.refs["http://json-schema.org/schema"]=Ba}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ba)?Ba:void 0)}};ye.Ajv=Xn;ip.exports=ye=Xn;ip.exports.Ajv=Xn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Xn;var Lz=vs();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return Lz.KeywordCxt}});var eo=H();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return eo._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return eo.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return eo.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return eo.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return eo.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return eo.CodeGen}});var Fz=Sa();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return Fz.default}});var Zz=_s();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return Zz.default}})});var yw=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.formatNames=jt.fastFormats=jt.fullFormats=void 0;function Mt(t,e){return{validate:t,compare:e}}jt.fullFormats={date:Mt(fw,dp),time:Mt(up(!0),pp),"date-time":Mt(lw(!0),hw),"iso-time":Mt(up(),mw),"iso-date-time":Mt(lw(),gw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Hz,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:eO,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:Kz,int32:{type:"number",validate:Yz},int64:{type:"number",validate:Qz},float:{type:"number",validate:pw},double:{type:"number",validate:pw},password:!0,binary:!0};jt.fastFormats={...jt.fullFormats,date:Mt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,dp),time:Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pp),"date-time":Mt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,hw),"iso-time":Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mw),"iso-date-time":Mt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gw),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};jt.formatNames=Object.keys(jt.fullFormats);function Uz(t){return t%4===0&&(t%100!==0||t%400===0)}var qz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Vz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fw(t){let e=qz.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Uz(r)?29:Vz[n])}function dp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var cp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function up(t){return function(r){let n=cp.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function pp(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function mw(t,e){if(!(t&&e))return;let r=cp.exec(t),n=cp.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var lp=/t|\s/i;function lw(t){let e=up(t);return function(n){let o=n.split(lp);return o.length===2&&fw(o[0])&&e(o[1])}}function hw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function gw(t,e){if(!(t&&e))return;let[r,n]=t.split(lp),[o,s]=e.split(lp),i=dp(r,o);if(i!==void 0)return i||pp(n,s)}var Bz=/\/|:/,Wz=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Hz(t){return Bz.test(t)&&Wz.test(t)}var dw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Kz(t){return dw.lastIndex=0,dw.test(t)}var Jz=-(2**31),Gz=2**31-1;function Yz(t){return Number.isInteger(t)&&t<=Gz&&t>=Jz}function Qz(t){return Number.isInteger(t)}function pw(){return!0}var Xz=/[^\\]\\Z/;function eO(t){if(Xz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var vw=E(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.formatLimitDefinition=void 0;var tO=ap(),St=H(),br=St.operators,Wa={formatMaximum:{okStr:"<=",ok:br.LTE,fail:br.GT},formatMinimum:{okStr:">=",ok:br.GTE,fail:br.LT},formatExclusiveMaximum:{okStr:"<",ok:br.LT,fail:br.GTE},formatExclusiveMinimum:{okStr:">",ok:br.GT,fail:br.LTE}},rO={message:({keyword:t,schemaCode:e})=>(0,St.str)`should be ${Wa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,St._)`{comparison: ${Wa[t].okStr}, limit: ${e}}`};to.formatLimitDefinition={keyword:Object.keys(Wa),type:"string",schemaType:"string",$data:!0,error:rO,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new tO.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,St._)`${p}[${c.schemaCode}]`);t.fail$data((0,St.or)((0,St._)`typeof ${f} != "object"`,(0,St._)`${f} instanceof RegExp`,(0,St._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,St._)`${i.code.formats}${(0,St.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,St._)`${p}.compare(${r}, ${n}) ${Wa[o].fail} 0`}},dependencies:["format"]};var nO=t=>(t.addKeyword(to.formatLimitDefinition),t);to.default=nO});var xw=E((Ds,ww)=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var ro=yw(),oO=vw(),fp=H(),_w=new fp.Name("fullFormats"),sO=new fp.Name("fastFormats"),mp=(t,e={keywords:!0})=>{if(Array.isArray(e))return bw(t,e,ro.fullFormats,_w),t;let[r,n]=e.mode==="fast"?[ro.fastFormats,sO]:[ro.fullFormats,_w],o=e.formats||ro.formatNames;return bw(t,o,r,n),e.keywords&&(0,oO.default)(t),t};mp.get=(t,e="full")=>{let n=(e==="fast"?ro.fastFormats:ro.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function bw(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,fp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}ww.exports=Ds=mp;Object.defineProperty(Ds,"__esModule",{value:!0});Ds.default=mp});import{readFileSync as lN}from"fs";import{join as Rc}from"path";import{fileURLToPath as dN}from"url";var cn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Zs=class extends cn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},me=class extends cn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var un=class extends cn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},He=class extends cn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var hf={ollama:{tier:"tool"},"claude-cli":{tier:"agent",maxComplexity:"complex"},"gemini-cli":{tier:"agent",maxComplexity:"complex"},"codex-cli":{tier:"agent",maxComplexity:"complex"},"claude-host":{tier:"agent",maxComplexity:"complex"},"codex-host":{tier:"agent",maxComplexity:"complex"},"gemini-host":{tier:"agent",maxComplexity:"complex"}},jS={ollama:{invocation:"http",roles:["participant","tool"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"claude-cli":{invocation:"cli",roles:["participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"codex-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"claude-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"codex-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0}};function Mc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Bs(t,e,r,n=t){let o=hf[n]??hf[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Mc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function tr(t,e){let r=jS[t.type],n=r?.roles?[...r.roles]:["participant"];return{id:t.id,type:t.type,invocation:r?.invocation??"unknown",roles:n,supportsAutonomousExecution:r?.supportsAutonomousExecution??!1,supportsReadOnlyChat:r?.supportsReadOnlyChat??!0,supportsToolUse:e?.supportsToolUse??r?.supportsToolUse??!1}}var Ws={low:0,medium:.5,high:.7},NS={chat:"low",simple_review:"low",code_review:"medium",code_generation:"medium",design:"medium",writing:"medium",analysis:"medium",ideation:"medium",debate_turn:"medium",architecture:"high",cross_validate:"high",complex_refactor:"high"};function gf(t,e){return e?.[t]??NS[t]??"low"}function Hs(t,e,r=Ws){return t>=r[e]}var Ks=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.getAll().find(n=>n.type==="claude-host"||n.type==="claude-cli")}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new Zs(e);return r}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(e=>e.isAvailable())}getAvailableDescriptors(){return this.getAvailable().map(e=>this.getDescriptor(e.id))}getByCapability(e){return this.getAvailable().filter(r=>r.getCapabilities().strengths.includes(e))}has(e){return this.providers.has(e)}getCapability(e){let r=this.get(e);return Bs(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??tr(r,r.getCapabilities())}getByTier(e){return this.getAvailable().filter(r=>this.getCapability(r.id).tier===e)}getByRole(e){return this.getAvailable().filter(r=>this.getDescriptor(r.id).roles.includes(e))}getBestForTask(e,r,n,o){let s=this.getAvailable();if(s.length===0)return;if(!r)return s[0];let i=n??gf(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],g=c.get(m)??{totalScore:0,count:0};g.totalScore+=f.avgScore*f.count,g.count+=f.count,c.set(m,g)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return Hs(m,i,o)});if(u.length===0)return;let l,d=-1;for(let p of u){let f=`${p.id}:${e}`,m=a.get(f);m&&m.avgScore>d&&(d=m.avgScore,l=p)}return l??u[0]}};var h={};Ze(h,{BRAND:()=>l$,DIRTY:()=>$r,EMPTY_PATH:()=>US,INVALID:()=>j,NEVER:()=>K$,OK:()=>Oe,ParseStatus:()=>Te,Schema:()=>B,ZodAny:()=>or,ZodArray:()=>qt,ZodBigInt:()=>Pr,ZodBoolean:()=>Tr,ZodBranded:()=>yo,ZodCatch:()=>Nr,ZodDate:()=>Er,ZodDefault:()=>jr,ZodDiscriminatedUnion:()=>Ys,ZodEffects:()=>it,ZodEnum:()=>Or,ZodError:()=>Ke,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>Xs,ZodIntersection:()=>Cr,ZodIssueCode:()=>$,ZodLazy:()=>Dr,ZodLiteral:()=>zr,ZodMap:()=>bn,ZodNaN:()=>xn,ZodNativeEnum:()=>Mr,ZodNever:()=>mt,ZodNull:()=>Ir,ZodNullable:()=>Et,ZodNumber:()=>kr,ZodObject:()=>Je,ZodOptional:()=>ot,ZodParsedType:()=>R,ZodPipeline:()=>vo,ZodPromise:()=>sr,ZodReadonly:()=>Lr,ZodRecord:()=>Qs,ZodSchema:()=>B,ZodSet:()=>wn,ZodString:()=>nr,ZodSymbol:()=>vn,ZodTransformer:()=>it,ZodTuple:()=>Tt,ZodType:()=>B,ZodUndefined:()=>Rr,ZodUnion:()=>Ar,ZodUnknown:()=>Ut,ZodVoid:()=>_n,addIssueToContext:()=>T,any:()=>_$,array:()=>S$,bigint:()=>m$,boolean:()=>Tf,coerce:()=>H$,custom:()=>$f,date:()=>h$,datetimeRegex:()=>xf,defaultErrorMap:()=>Ft,discriminatedUnion:()=>T$,effect:()=>L$,enum:()=>M$,function:()=>D$,getErrorMap:()=>hn,getParsedType:()=>Pt,instanceof:()=>p$,intersection:()=>E$,isAborted:()=>Js,isAsync:()=>gn,isDirty:()=>Gs,isValid:()=>rr,late:()=>d$,lazy:()=>z$,literal:()=>O$,makeIssue:()=>go,map:()=>A$,nan:()=>f$,nativeEnum:()=>j$,never:()=>w$,null:()=>v$,nullable:()=>Z$,number:()=>Pf,object:()=>$$,objectUtil:()=>jc,oboolean:()=>W$,onumber:()=>B$,optional:()=>F$,ostring:()=>V$,pipeline:()=>q$,preprocess:()=>U$,promise:()=>N$,quotelessJson:()=>LS,record:()=>I$,set:()=>C$,setErrorMap:()=>ZS,strictObject:()=>k$,string:()=>kf,symbol:()=>g$,transformer:()=>L$,tuple:()=>R$,undefined:()=>y$,union:()=>P$,unknown:()=>b$,util:()=>G,void:()=>x$});var G;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(G||(G={}));var jc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(jc||(jc={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pt=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var $=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),LS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ke=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ke.create=t=>new Ke(t);var FS=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,G.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${G.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${G.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${G.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:G.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case $.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,G.assertNever(t)}return{message:r}},Ft=FS;var yf=Ft;function ZS(t){yf=t}function hn(){return yf}var go=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},US=[];function T(t,e){let r=hn(),n=go({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ft?void 0:Ft].filter(o=>!!o)});t.common.issues.push(n)}var Te=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return j;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return j;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},j=Object.freeze({status:"aborted"}),$r=t=>({status:"dirty",value:t}),Oe=t=>({status:"valid",value:t}),Js=t=>t.status==="aborted",Gs=t=>t.status==="dirty",rr=t=>t.status==="valid",gn=t=>typeof Promise<"u"&&t instanceof Promise;var A;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(A||(A={}));var st=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},vf=(t,e)=>{if(rr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ke(t.common.issues);return this._error=r,this._error}}};function U(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var B=class{get description(){return this._def.description}_getType(e){return Pt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(gn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return vf(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return rr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>rr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(gn(o)?o:Promise.resolve(o));return vf(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:$.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new it({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ot.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return qt.create(this)}promise(){return sr.create(this,this._def)}or(e){return Ar.create([this,e],this._def)}and(e){return Cr.create(this,e,this._def)}transform(e){return new it({...U(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new jr({...U(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new yo({typeName:P.ZodBranded,type:this,...U(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Nr({...U(this._def),innerType:this,catchValue:r,typeName:P.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vo.create(this,e)}readonly(){return Lr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qS=/^c[^\s-]{8,}$/i,VS=/^[0-9a-z]+$/,BS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,WS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,HS=/^[a-z0-9_-]{21}$/i,KS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,JS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,GS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,YS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Nc,QS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,XS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,e$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,t$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,r$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,n$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",o$=new RegExp(`^${bf}$`);function wf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function s$(t){return new RegExp(`^${wf(t)}$`)}function xf(t){let e=`${bf}T${wf(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function i$(t,e){return!!((e==="v4"||!e)&&QS.test(t)||(e==="v6"||!e)&&e$.test(t))}function a$(t,e){if(!KS.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function c$(t,e){return!!((e==="v4"||!e)&&XS.test(t)||(e==="v6"||!e)&&t$.test(t))}var nr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.string,received:s.parsedType}),j}let n=new Te,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")GS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Nc||(Nc=new RegExp(YS,"u")),Nc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")WS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")HS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")qS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")VS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")BS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:$.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:$.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?xf(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?o$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?s$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?JS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?i$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?a$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?c$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?r$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?n$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):G.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...A.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...A.errToObj(e)})}url(e){return this._addCheck({kind:"url",...A.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...A.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...A.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...A.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...A.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...A.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...A.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...A.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...A.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...A.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...A.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...A.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...A.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...A.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...A.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...A.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...A.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...A.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...A.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...A.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...A.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...A.errToObj(r)})}nonempty(e){return this.min(1,A.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};nr.create=t=>new nr({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...U(t)});function u$(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var kr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.number,received:s.parsedType}),j}let n,o=new Te;for(let s of this._def.checks)s.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?u$(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_finite,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:A.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:A.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};kr.create=t=>new kr({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...U(t)});var Pr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,o=new Te;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.bigint,received:r.parsedType}),j}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Pr.create=t=>new Pr({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...U(t)});var Tr=class extends B{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.boolean,received:n.parsedType}),j}return Oe(e.data)}};Tr.create=t=>new Tr({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...U(t)});var Er=class t extends B{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.date,received:s.parsedType}),j}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_date}),j}let n=new Te,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):G.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:A.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:A.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Er.create=t=>new Er({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...U(t)});var vn=class extends B{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.symbol,received:n.parsedType}),j}return Oe(e.data)}};vn.create=t=>new vn({typeName:P.ZodSymbol,...U(t)});var Rr=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.undefined,received:n.parsedType}),j}return Oe(e.data)}};Rr.create=t=>new Rr({typeName:P.ZodUndefined,...U(t)});var Ir=class extends B{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.null,received:n.parsedType}),j}return Oe(e.data)}};Ir.create=t=>new Ir({typeName:P.ZodNull,...U(t)});var or=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}};or.create=t=>new or({typeName:P.ZodAny,...U(t)});var Ut=class extends B{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oe(e.data)}};Ut.create=t=>new Ut({typeName:P.ZodUnknown,...U(t)});var mt=class extends B{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.never,received:r.parsedType}),j}};mt.create=t=>new mt({typeName:P.ZodNever,...U(t)});var _n=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.void,received:n.parsedType}),j}return Oe(e.data)}};_n.create=t=>new _n({typeName:P.ZodVoid,...U(t)});var qt=class t extends B{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:$.invalid_type,expected:R.array,received:r.parsedType}),j;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?$.too_big:$.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new st(r,i,r.path,a)))).then(i=>Te.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new st(r,i,r.path,a)));return Te.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:A.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:A.toString(r)}})}nonempty(e){return this.min(1,e)}};qt.create=(t,e)=>new qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...U(e)});function yn(t){if(t instanceof Je){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ot.create(yn(n))}return new Je({...t._def,shape:()=>e})}else return t instanceof qt?new qt({...t._def,type:yn(t.element)}):t instanceof ot?ot.create(yn(t.unwrap())):t instanceof Et?Et.create(yn(t.unwrap())):t instanceof Tt?Tt.create(t.items.map(e=>yn(e))):t}var Je=class t extends B{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=G.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:$.invalid_type,expected:R.object,received:u.parsedType}),j}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new st(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(T(o,{code:$.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new st(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Te.mergeObjectSync(n,u)):Te.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return A.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:A.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:P.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of G.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return yn(this)}partial(e){let r={};for(let n of G.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ot;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Sf(G.objectKeys(this.shape))}};Je.create=(t,e)=>new Je({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:P.ZodObject,...U(e)});Je.strictCreate=(t,e)=>new Je({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:P.ZodObject,...U(e)});Je.lazycreate=(t,e)=>new Je({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:P.ZodObject,...U(e)});var Ar=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ke(a.ctx.common.issues));return T(r,{code:$.invalid_union,unionErrors:i}),j}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ke(c));return T(r,{code:$.invalid_union,unionErrors:a}),j}}get options(){return this._def.options}};Ar.create=(t,e)=>new Ar({options:t,typeName:P.ZodUnion,...U(e)});var Zt=t=>t instanceof Dr?Zt(t.schema):t instanceof it?Zt(t.innerType()):t instanceof zr?[t.value]:t instanceof Or?t.options:t instanceof Mr?G.objectValues(t.enum):t instanceof jr?Zt(t._def.innerType):t instanceof Rr?[void 0]:t instanceof Ir?[null]:t instanceof ot?[void 0,...Zt(t.unwrap())]:t instanceof Et?[null,...Zt(t.unwrap())]:t instanceof yo||t instanceof Lr?Zt(t.unwrap()):t instanceof Nr?Zt(t._def.innerType):[],Ys=class t extends B{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:$.invalid_type,expected:R.object,received:r.parsedType}),j;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),j)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Zt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:P.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...U(n)})}};function Lc(t,e){let r=Pt(t),n=Pt(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=G.objectKeys(e),s=G.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Lc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Lc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Cr=class extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Js(s)||Js(i))return j;let a=Lc(s.value,i.value);return a.valid?((Gs(s)||Gs(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:$.invalid_intersection_types}),j)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Cr.create=(t,e,r)=>new Cr({left:t,right:e,typeName:P.ZodIntersection,...U(r)});var Tt=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:$.invalid_type,expected:R.array,received:n.parsedType}),j;if(n.data.length<this._def.items.length)return T(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),j;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new st(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Te.mergeArray(r,i)):Te.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Tt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tt({items:t,typeName:P.ZodTuple,rest:null,...U(e)})};var Qs=class t extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:$.invalid_type,expected:R.object,received:n.parsedType}),j;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new st(n,a,n.path,a)),value:i._parse(new st(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Te.mergeObjectAsync(r,o):Te.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof B?new t({keyType:e,valueType:r,typeName:P.ZodRecord,...U(n)}):new t({keyType:nr.create(),valueType:e,typeName:P.ZodRecord,...U(r)})}},bn=class extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:$.invalid_type,expected:R.map,received:n.parsedType}),j;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new st(n,a,n.path,[u,"key"])),value:s._parse(new st(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return j;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return j;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};bn.create=(t,e,r)=>new bn({valueType:e,keyType:t,typeName:P.ZodMap,...U(r)});var wn=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:$.invalid_type,expected:R.set,received:n.parsedType}),j;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return j;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new st(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:A.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};wn.create=(t,e)=>new wn({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...U(e)});var Xs=class t extends B{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:$.invalid_type,expected:R.function,received:r.parsedType}),j;function n(a,c){return go({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hn(),Ft].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return go({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hn(),Ft].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof sr){let a=this;return Oe(async function(...c){let u=new Ke([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Oe(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ke([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ke([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Tt.create(e).rest(Ut.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Tt.create([]).rest(Ut.create()),returns:r||Ut.create(),typeName:P.ZodFunction,...U(n)})}},Dr=class extends B{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Dr.create=(t,e)=>new Dr({getter:t,typeName:P.ZodLazy,...U(e)});var zr=class extends B{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),j}return{status:"valid",value:e.data}}get value(){return this._def.value}};zr.create=(t,e)=>new zr({value:t,typeName:P.ZodLiteral,...U(e)});function Sf(t,e){return new Or({values:t,typeName:P.ZodEnum,...U(e)})}var Or=class t extends B{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:G.joinValues(n),received:r.parsedType,code:$.invalid_type}),j}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:$.invalid_enum_value,options:n}),j}return Oe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Or.create=Sf;var Mr=class extends B{_parse(e){let r=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=G.objectValues(r);return T(n,{expected:G.joinValues(o),received:n.parsedType,code:$.invalid_type}),j}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=G.objectValues(r);return T(n,{received:n.data,code:$.invalid_enum_value,options:o}),j}return Oe(e.data)}get enum(){return this._def.values}};Mr.create=(t,e)=>new Mr({values:t,typeName:P.ZodNativeEnum,...U(e)});var sr=class extends B{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:$.invalid_type,expected:R.promise,received:r.parsedType}),j;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Oe(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};sr.create=(t,e)=>new sr({type:t,typeName:P.ZodPromise,...U(e)});var it=class extends B{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return j;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?j:c.status==="dirty"?$r(c.value):r.value==="dirty"?$r(c.value):c});{if(r.value==="aborted")return j;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?j:a.status==="dirty"?$r(a.value):r.value==="dirty"?$r(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?j:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?j:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!rr(i))return j;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>rr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):j);G.assertNever(o)}};it.create=(t,e,r)=>new it({schema:t,typeName:P.ZodEffects,effect:e,...U(r)});it.createWithPreprocess=(t,e,r)=>new it({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...U(r)});var ot=class extends B{_parse(e){return this._getType(e)===R.undefined?Oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ot.create=(t,e)=>new ot({innerType:t,typeName:P.ZodOptional,...U(e)});var Et=class extends B{_parse(e){return this._getType(e)===R.null?Oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(t,e)=>new Et({innerType:t,typeName:P.ZodNullable,...U(e)});var jr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};jr.create=(t,e)=>new jr({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...U(e)});var Nr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return gn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...U(e)});var xn=class extends B{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.nan,received:n.parsedType}),j}return{status:"valid",value:e.data}}};xn.create=t=>new xn({typeName:P.ZodNaN,...U(t)});var l$=Symbol("zod_brand"),yo=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vo=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?j:s.status==="dirty"?(r.dirty(),$r(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?j:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:P.ZodPipeline})}},Lr=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(rr(o)&&(o.value=Object.freeze(o.value)),o);return gn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Lr.create=(t,e)=>new Lr({innerType:t,typeName:P.ZodReadonly,...U(e)});function _f(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function $f(t,e={},r){return t?or.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=_f(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=_f(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):or.create()}var d$={object:Je.lazycreate},P;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(P||(P={}));var p$=(t,e={message:`Input not instance of ${t.name}`})=>$f(r=>r instanceof t,e),kf=nr.create,Pf=kr.create,f$=xn.create,m$=Pr.create,Tf=Tr.create,h$=Er.create,g$=vn.create,y$=Rr.create,v$=Ir.create,_$=or.create,b$=Ut.create,w$=mt.create,x$=_n.create,S$=qt.create,$$=Je.create,k$=Je.strictCreate,P$=Ar.create,T$=Ys.create,E$=Cr.create,R$=Tt.create,I$=Qs.create,A$=bn.create,C$=wn.create,D$=Xs.create,z$=Dr.create,O$=zr.create,M$=Or.create,j$=Mr.create,N$=sr.create,L$=it.create,F$=ot.create,Z$=Et.create,U$=it.createWithPreprocess,q$=vo.create,V$=()=>kf().optional(),B$=()=>Pf().optional(),W$=()=>Tf().optional(),H$={string:(t=>nr.create({...t,coerce:!0})),number:(t=>kr.create({...t,coerce:!0})),boolean:(t=>Tr.create({...t,coerce:!0})),bigint:(t=>Pr.create({...t,coerce:!0})),date:(t=>Er.create({...t,coerce:!0}))};var K$=j;Nt();var J$=h.enum(["read-only","workspace-write","full-auto"]),G$=J$.default("read-only"),Y$=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:G$,config:h.record(h.unknown()).default({})}),Q$=h.enum(["default-only","auto"]).default("default-only"),X$=h.object({defaultProvider:h.string().optional(),selectionPolicy:Q$,locale:h.string().optional(),providers:h.array(Y$).min(1,"At least one provider required")});function Vt(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":return"workspace-write";default:return"read-only"}}function ei(t){return t==="workspace-write"||t==="full-auto"}function ek(t){return Vs.includes(t)}function tk(t){if(t!==void 0)return ek(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${xr}`),xr)}function Ef(t){let e=X$.parse(t);return{defaultProvider:e.defaultProvider,selectionPolicy:e.selectionPolicy,locale:tk(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}ni();wo();ho();mn();Nt();import{mkdirSync as Lf,readFileSync as Rt,readdirSync as Wc,existsSync as ir,unlinkSync as kk,rmdirSync as Pk}from"fs";import{join as ce}from"path";import{spawn as Ff}from"child_process";import{randomUUID as Tk}from"crypto";function Zr(t,e){let r=ce(t,"status.json"),n=JSON.parse(Rt(r,"utf-8"));Ue(r,{...n,...e})}var ii=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;constructor(e=process.cwd(),r){this.jobsDir=ce(e,Qp),Lf(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7}submit(e){let r=`${e.provider}-${Date.now()}-${Tk().slice(0,6)}`,n=ce(this.jobsDir,r);Lf(n,{recursive:!0});let o={id:r,provider:e.provider,prompt:e.prompt,timeout:e.timeout??3e5,createdAt:new Date().toISOString(),cwd:process.cwd()},s={id:r,state:"queued",provider:e.provider};return Ue(ce(n,"job.json"),o),Ue(ce(n,"status.json"),s),se(ce(n,"prompt.txt"),e.prompt),this.statusCache.set(r,s),this.spawnWorker(n),this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!oi(e))return null;let r=["completed","error","timed_out","cancelled","missing_cli"],n=this.statusCache.get(e);if(n&&r.includes(n.state))return n;let o=ce(this.jobsDir,e,"status.json");if(!ir(o))return null;let s=JSON.parse(Rt(o,"utf-8"));if(s.state==="queued"){let i=ce(this.jobsDir,e,"job.json");try{let a=JSON.parse(Rt(i,"utf-8"));if(Date.now()-new Date(a.createdAt).getTime()>6e4){let u={...s,state:"error",completedAt:new Date().toISOString()};return Ue(o,u),se(ce(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,u),u}}catch{}}return this.statusCache.set(e,s),s}getResult(e){if(!oi(e))return null;let r=this.getStatus(e);if(!r)return null;let n=ce(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode},s=ce(n,"output.txt");ir(s)&&(o.output=Rt(s,"utf-8"));let i=ce(n,"error.txt");return ir(i)&&(o.error=Rt(i,"utf-8")),o}listJobs(){if(!ir(this.jobsDir))return[];let e=Wc(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory()),r=[];for(let n of e){let o=ce(this.jobsDir,n.name,"status.json");ir(o)&&r.push(JSON.parse(Rt(o,"utf-8")))}return r}cancel(e){if(!oi(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&pn(r.pid);let n=ce(this.jobsDir,e),o={...r,state:"cancelled",completedAt:new Date().toISOString()};return Ue(ce(n,"status.json"),o),this.statusCache.set(e,o),!0}cleanup(){if(!ir(this.jobsDir))return 0;let e=Wc(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory()),r=[];for(let u of e){let l=ce(this.jobsDir,u.name,"status.json"),d=ce(this.jobsDir,u.name,"job.json");if(!ir(l))continue;let p=JSON.parse(Rt(l,"utf-8")),f=null;try{f=JSON.parse(Rt(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}let n=["completed","error","timed_out","cancelled","missing_cli"],o=r.filter(u=>n.includes(u.status.state)).sort((u,l)=>{let d=u.descriptor?.createdAt??"",p=l.descriptor?.createdAt??"";return d.localeCompare(p)}),s=0,i=Date.now(),a=this.maxAgeDays*24*60*60*1e3,c=r.length;for(let u of o){let d=(u.descriptor?.createdAt?i-new Date(u.descriptor.createdAt).getTime():1/0)>a,p=c-s>this.maxJobs;if(!d&&!p)continue;let f=ce(this.jobsDir,u.name);try{let m=Wc(f);for(let g of m)kk(ce(f,g));Pk(f),this.statusCache.delete(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(ir(r)){let n=Ff(process.execPath,[r,e],{detached:!0,stdio:"ignore"});if(n.pid)try{Zr(e,{pid:n.pid})}catch{}n.on("error",o=>{o.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(Nf(),jf)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Rt(ce(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){Zr(e,{state:"missing_cli",completedAt:new Date().toISOString()}),se(ce(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Rt(ce(e,"prompt.txt"),"utf-8"),c=i(a);Zr(e,{state:"running",startedAt:new Date().toISOString()});let u=Lt(s,c),l=Ff(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",y=>{f+=y.length,f<=10485760&&(d+=y.toString())}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let g=setTimeout(()=>{er(l),se(ce(e,"output.txt"),d),se(ce(e,"error.txt"),p),Zr(e,{state:"timed_out",completedAt:new Date().toISOString()})},n.timeout);l.on("close",y=>{clearTimeout(g),se(ce(e,"output.txt"),d),se(ce(e,"error.txt"),p);let _=d.trim().length>0;Zr(e,{state:y===0||_?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()})}),l.on("error",y=>{clearTimeout(g);let _=y.code==="ENOENT"?"missing_cli":"error";se(ce(e,"error.txt"),y.message),Zr(e,{state:_,completedAt:new Date().toISOString()})})}).catch(()=>{try{Zr(e,{state:"error",completedAt:new Date().toISOString()}),se(ce(e,"error.txt"),"Failed to load job worker module")}catch{}})}};ni();Nt();import{mkdirSync as Ek,readdirSync as Zf,readFileSync as Rk,unlinkSync as Ik}from"fs";import{join as xo}from"path";function Uf(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}function Ak(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function Ck(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var ai=class{tracesDir;writer;constructor(e,r){this.tracesDir=xo(e,Xp),Ek(this.tracesDir,{recursive:!0}),this.writer=new ti(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Uf(new Date(r.timestamp)),o=xo(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
12
+ `,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=Rk(i,"utf-8").split(`
13
+ `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);Ck(u)?o.push(u):Ak(u)&&n.push(u)}catch{}}for(let i of o){let a=n.find(c=>c.traceId===i.traceId&&c.providerId===i.providerId);a&&(a.quality=i.quality)}let s=n;return e.providerId&&(s=s.filter(i=>i.providerId===e.providerId)),e.task&&(s=s.filter(i=>i.task===e.task)),e.traceId&&(s=s.filter(i=>i.traceId===e.traceId)),e.successOnly&&(s=s.filter(i=>i.response.success)),e.failedOnly&&(s=s.filter(i=>!i.response.success)),e.limit!==void 0&&(s=s.slice(0,e.limit)),s}updateQuality(e,r,n){let o=new Date,s={type:"quality_update",traceId:e,providerId:r,timestamp:o.toISOString(),quality:n},i=Uf(o),a=xo(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(s)+`
14
+ `,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let s of r){if(!s.quality)continue;let i=`${s.providerId}:${s.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=s.quality.score,a.count+=1,a.totalLatency+=s.latencyMs,n.set(i,a)}let o=new Map;for(let[s,i]of n)o.set(s,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return o}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,o;try{o=Zf(this.tracesDir)}catch{return 0}for(let s of o){if(!s.endsWith(".jsonl"))continue;let i=s.replace(".jsonl",""),a=new Date(i+"T00:00:00.000Z");isNaN(a.getTime())||a<r&&(Ik(xo(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=Zf(this.tracesDir).filter(n=>n.endsWith(".jsonl")).sort()}catch{return[]}if(e!==void 0){let n=new Date;n.setDate(n.getDate()-e),r=r.filter(o=>{let s=o.replace(".jsonl",""),i=new Date(s+"T00:00:00.000Z");return!isNaN(i.getTime())&&i>=n})}return r.map(n=>xo(this.tracesDir,n))}};var Dk=/[;|&`$(){}!><\n\r\\]/,ci=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),zk=new Set(["rm","sudo","chmod","chown","mkfs","dd","curl","wget","kill","pkill","killall","mv","cp","sh","bash","zsh","python","perl","ruby","node","npm","npx","eval","exec","source"]);function qf(t){if(Dk.test(t))return{valid:!1,error:"Command contains shell metacharacters (piping, chaining, or subshell operators are not allowed)"};let e=t.split(/\s+/).filter(Boolean);if(e.length===0)return{valid:!1,error:"Empty command"};if(e[0].includes("/")||e[0].includes("\\"))return{valid:!1,error:"Command must not contain path separators (use bare command names only)"};for(let n=1;n<e.length;n++)if(e[n].includes("/")||e[n].includes("\\"))return{valid:!1,error:`Argument must not contain path separators: ${JSON.stringify(e[n])}`};let r=e[0];if(!ci.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...ci].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(zk.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}Nt();var Vf=[{type:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/,description:"AWS Access Key ID"},{type:"private_key",regex:/-----BEGIN\s+(RSA|EC|DSA|OPENSSH)?\s*PRIVATE KEY-----/,description:"Private key header"},{type:"password_assignment",regex:/(?:password|passwd|pwd)\s*[:=]\s*["']?[^\s"',;]{4,}["']?/i,description:"Password assignment"},{type:"api_key_assignment",regex:/(?:api[_-]?key|apikey|secret[_-]?key)\s*[:=]\s*["']?[^\s"',;]{8,}["']?/i,description:"API key assignment"},{type:"bearer_token",regex:/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/,description:"Bearer JWT token"},{type:"generic_secret",regex:/(?:token|secret|credential)\s*[:=]\s*["'][^"']{8,}["']/i,description:"Generic secret assignment"}],Bf=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function Wf(t){let e=Array.isArray(t)?t:t.split(`
15
+ `),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of Vf){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!Bf.some(u=>u.test(a))){r.push({type:s.type,pattern:s.description,line:n+1,excerpt:o.length>80?o.slice(0,80)+"...":o});break}}}return{clean:r.length===0,findings:r}}function Hc(t){if(t.length===0)return t;let e=t.split(`
16
+ `);for(let r=0;r<e.length;r++){let n=e[r];for(let o of Vf){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>Bf.some(a=>a.test(i))?i:ff)}e[r]=n}return e.join(`
17
+ `)}Nt();import{execFileSync as Ok}from"child_process";import{existsSync as Hf,rmSync as Mk,mkdirSync as jk}from"fs";import{join as Kf}from"path";var ui=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=Kf(e,ef)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=Kf(this.worktreeBaseDir,r);jk(this.worktreeBaseDir,{recursive:!0}),Hf(o)&&this.forceRemoveWorktree(o),this.gitSafe(["branch","-D",n]),this.git(["worktree","add","-b",n,o,"HEAD"]);let s={id:e,path:o,branch:n};return this.worktrees.set(e,s),s}remove(e){let r=this.worktrees.get(e);r&&(this.forceRemoveWorktree(r.path),this.gitSafe(["branch","-D",r.branch]),this.worktrees.delete(e))}get(e){return this.worktrees.get(e)}list(){return[...this.worktrees.values()]}listOrphans(){let e=this.gitSafe(["worktree","list","--porcelain"]);if(!e)return[];let r=[],n="",o="",s=()=>{n.includes(".agestra/worktrees")&&o.startsWith("agestra-worker/")&&([...this.worktrees.values()].some(a=>a.path===n)||r.push({path:n,branch:o})),n="",o=""};for(let i of e.split(`
18
+ `))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?o=i.slice(18):i===""&&s();return n&&s(),r}cleanOrphans(){let e=this.listOrphans(),r=0;for(let n of e)this.forceRemoveWorktree(n.path),this.gitSafe(["branch","-D",n.branch]),r++;return r}forceRemoveWorktree(e){this.gitSafe(["worktree","remove",e])===null&&this.gitSafe(["worktree","remove","--force",e])===null&&(Hf(e)&&Mk(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return Ok("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var Nk=["npm","node","git","tsc"];function Jf(t){return{task:t.taskDescription,files:{readonly:t.filesToRead??[],readwrite:t.filesToModify??[]},constraints:t.constraints,success_criteria:t.successCriteria??[],permissions:{sandbox_root:t.workingDir,allowed_commands:[...Nk]},timeout_minutes:t.timeoutMinutes??10}}function Gf(t){let e=[];return(!t.task||t.task.trim().length===0)&&e.push("task must not be empty"),(!t.permissions.sandbox_root||t.permissions.sandbox_root.trim().length===0)&&e.push("permissions.sandbox_root must not be empty"),t.timeout_minutes<=0&&e.push("timeout_minutes must be positive"),{valid:e.length===0,errors:e}}var $e;(function(t){t.SPAWNING="SPAWNING",t.RUNNING="RUNNING",t.COLLECTING="COLLECTING",t.COMPLETED="COMPLETED",t.FAILED="FAILED",t.CANCELLING="CANCELLING",t.CANCELLED="CANCELLED",t.TIMEOUT="TIMEOUT"})($e||($e={}));var li=10,Kc=2e4;import{spawn as Vk}from"child_process";import{writeFileSync as Gc,mkdirSync as Bk,readFileSync as em,existsSync as tm}from"fs";import{isAbsolute as rm,join as So,resolve as nm}from"path";import{randomBytes as Wk}from"crypto";import{execFileSync as Hk}from"child_process";Nt();mn();ho();wo();wo();import{readFileSync as Yf}from"fs";var Jc=class{builders=new Map;register(e,r){this.builders.set(e,r)}has(e){return this.builders.has(e)}build(e,r,n,o){let s=this.builders.get(e);if(!s){let i=[...this.builders.keys()];throw new Error(`No CLI launch builder registered for provider "${e}". Known: [${i.join(", ")}]`)}return s(r,n,o)}knownProviders(){return[...this.builders.keys()]}};function Lk(t,e,r){let n=Qf(t,e,r);return{command:"codex",args:["exec","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function Fk(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",Qf(t,e,r)]}}function Qf(t,e,r){let n=Yf(t,"utf-8"),o=Zk(r,e);return["You are an autonomous coding worker operating in the current workspace.","Execute the task manifest below without asking for confirmation.","Stay within the workspace, respect read-only vs read-write boundaries, and summarize changes plus verification at the end.","",n,o].join(`
19
+ `)}function Xf(){let t=new Jc;return t.register("codex",Lk),t.register("gemini",Fk),t}function Zk(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!Vc(o,e));if(r.length===0)return"";let n=["Read-only file snapshots:","These files may live outside the worker sandbox root. Use the embedded contents below as authoritative context and do not attempt to edit them.",""];for(let o of r.slice(0,li))try{let s=Yf(o,"utf-8"),i=s.length>Kc?`${s.slice(0,Kc)}
20
+ ...[truncated]`:s;n.push(`### File: ${o}`),n.push("```"),n.push(i),n.push("```"),n.push("")}catch(s){let i=s instanceof Error?s.message:String(s);n.push(`### File: ${o}`),n.push(`[unavailable: ${i}]`),n.push("")}return r.length>li&&(n.push(`...[${r.length-li} additional read-only files omitted]`),n.push("")),n.join(`
21
+ `)}var $o=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=So(e,sf),this.worktreeManager=new ui(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??Xf()}knownProviders(){let e=new Set;for(let r of this.cliBuilderRegistry.knownProviders())e.add(r);for(let r of this.providerPolicies.keys())e.add(r);return[...e]}activeWorkerCount(){let e=0;for(let r of this.workers.values()){let n=r.info.state;(n===$e.RUNNING||n===$e.COLLECTING)&&e++}return e}spawn(e){if(this.activeWorkerCount()>=3)throw new Error(`Worker quota exceeded: ${this.activeWorkerCount()}/${3} workers already active. Wait for existing workers to complete or call stop() before spawning a new one.`);let r=this.validateWorkingDirectory(e.workingDir),n=this.normalizeReadablePaths(e.filesToRead,r),o=this.normalizeWritablePaths(e.filesToModify,r);this.assertAutonomousExecutionAllowed(e.provider);let s=[e.taskDescription,e.constraints??""],i=Wf(s);if(!i.clean){let Z=i.findings.map(De=>De.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${Z}`)}let a=Wk(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=So(this.workersBaseDir,c);Bk(u,{recursive:!0});let l=Jf({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=Gf(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=So(u,"task-manifest.json");Gc(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=So(u,"stdout.log"),g=So(u,"stderr.log"),y=f?.path??r,_=this.cliBuilderRegistry.build(e.provider,p,y,n),S=Lt(_.command,_.args),v=Vk(S.command,S.args,{cwd:y,env:t.buildWorkerEnv(),detached:!0,stdio:[_.stdin?"pipe":"ignore","pipe","pipe"]}),k=[],x=[];v.stdout?.on("data",Z=>k.push(Z)),v.stderr?.on("data",Z=>x.push(Z)),_.stdin!==void 0&&v.stdin?.end(_.stdin),v.unref();let z={workerId:c,provider:e.provider,state:$e.RUNNING,pid:v.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},O={info:z,process:v,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,O),e.timeoutMinutes){let Z=e.timeoutMinutes*6e4;setTimeout(()=>{if(O.info.state===$e.RUNNING){O.info.state=$e.TIMEOUT,O.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let Y=O.process?.pid;Y&&pn(Y)}},Z).unref()}return v.on("close",Z=>{O.info.exitCode=Z;try{Gc(m,Buffer.concat(k).toString("utf-8")),Gc(g,Buffer.concat(x).toString("utf-8"))}catch{}O.info.state===$e.CANCELLING?O.info.state=$e.CANCELLED:Z===0?O.info.state=$e.COLLECTING:(O.info.state=$e.FAILED,O.info.error=`Process exited with code ${Z}`)}),z}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{tm(r.outputPath)&&(o=em(r.outputPath,"utf-8").split(`
22
22
  `).slice(-20).join(`
23
- `))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:Vc(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{Jf(r.outputPath)&&(n=Gf(r.outputPath,"utf-8"))}catch{}n=Vc(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 Fk("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 tf){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(!Xs(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=Qf(n)?n:Yf(r,n);return Vt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=Qf(n)?n:Yf(r,n);return ht(o,this.baseDir)})}};var di=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 Zk}from"child_process";var Uk=3e5,qk=3,Vk=15e3,Bk=3e3,Wk=6e5,pi=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??Uk,this.maxConsecutiveFailures=e.maxConsecutiveFailures??qk,this.startupTimeoutMs=e.startupTimeoutMs??Vk}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??Wk)}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>nf?(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{}},Bk);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=Zk(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(`
23
+ `))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:Hc(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{tm(r.outputPath)&&(n=em(r.outputPath,"utf-8"))}catch{}n=Hc(n);let o=null;try{r.info.worktreePath&&(o=this.reviewChanges(r.info.workerId))}catch{o=null}return r.info.state===$e.COLLECTING&&(r.info.state=$e.COMPLETED),{workerId:r.info.workerId,state:r.info.state,exitCode:r.info.exitCode,outputFull:n,gitDiff:o?.fullDiff??"",filesChanged:o?.filesChanged??[],worktreeBranch:r.info.worktreeBranch}}stop(e){let r=this.workers.get(e);if(!r||!r.process||r.info.state!==$e.RUNNING)return;r.info.state=$e.CANCELLING;let n=r.process.pid;if(n)pn(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===$e.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=$e.CANCELLED}},5e3)}listAll(){return[...this.workers.values()].map(e=>({...e.info}))}reviewChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);if(!r.info.worktreePath)throw new Error(`Worker ${e} has no isolated worktree`);let n=r.info.worktreePath;return this.execGitSafe(["add","-N","."],n),{workerId:r.info.workerId,provider:r.info.provider,worktreePath:r.info.worktreePath,branch:r.info.worktreeBranch,filesChanged:this.listChangedFiles(n),diffStat:this.execGit(["diff","--stat","HEAD"],n),fullDiff:this.execGit(["diff","HEAD"],n)}}acceptChanges(e,r){let n=this.workers.get(e);if(!n)throw new Error(`Worker not found: ${e}`);if(!n.info.worktreePath||!n.info.worktreeBranch)throw new Error(`Worker ${e} has no isolated worktree`);let o=n.info.worktreePath,s=r??`agestra: worker ${e}`;this.execGit(["add","-A"],o);let i=this.execGit(["status","--porcelain"],o),a=i.trim()?i.trim().split(`
24
+ `).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",s],o),this.execGit(["merge",n.info.worktreeBranch,"--no-edit"],this.baseDir)),this.worktreeManager.remove(n.info.workerId),n.info.worktreePath=null,n.info.worktreeBranch=null,{merged:a}}rejectChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);r.info.worktreePath&&this.worktreeManager.remove(r.info.workerId),r.info.worktreePath=null,r.info.worktreeBranch=null}tryCreateWorktree(e){try{return this.worktreeManager.create(e)}catch{return null}}execGit(e,r){return Hk("git",e,{cwd:r,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}execGitSafe(e,r){try{return this.execGit(e,r)}catch{return null}}listChangedFiles(e){let r=this.execGitSafe(["status","--porcelain"],e);return r?.trim()?r.trim().split(`
25
+ `).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of af){let n=process.env[r];n!==void 0&&(e[r]=n)}for(let[r,n]of Object.entries(process.env))r.startsWith("AGESTRA_")&&n!==void 0&&(e[r]=n);return e}getProviderPolicy(e){let r=this.providerPolicies.get(e);if(r===void 0){let n=[...this.providerPolicies.keys()];throw new Error(`No execution policy configured for provider "${e}". Known: [${n.join(", ")}]`)}return r}assertAutonomousExecutionAllowed(e){let r=this.getProviderPolicy(e);if(!ei(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return ht(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let o=rm(n)?n:nm(r,n);return Bt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=rm(n)?n:nm(r,n);return ht(o,this.baseDir)})}};var pi=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(e,r){this.upstream=e,this.ttlMs=r?.ttlMs??6e4}getQualityStats(e){let r=Date.now();return this.cached!==null&&this.cachedDaysBack===e&&r-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(e),this.cachedAt=r,this.cachedDaysBack=e,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var Sn=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(e,r=16){this.maxConcurrent=e,this.maxQueueSize=r}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}async run(e){await this.acquire();try{return await e()}finally{this.release()}}};mn();Nt();import{spawn as Kk}from"child_process";var Jk=3e5,Gk=3,Yk=15e3,Qk=3e3,Xk=6e5,fi=class{state="idle";process=null;consecutiveFailures=0;lastFailureTime=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;commandArgs;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(e){this.command=e.command,this.commandPrefix=e.commandPrefix??[],this.commandArgs=e.commandArgs??[],this.idleTimeoutMs=e.idleTimeoutMs??Jk,this.maxConsecutiveFailures=e.maxConsecutiveFailures??Gk,this.startupTimeoutMs=e.startupTimeoutMs??Yk}async request(e,r){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??Xk)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures<this.maxConsecutiveFailures?!1:Date.now()-this.lastFailureTime>uf?(this.consecutiveFailures=0,!1):!0}resetFailures(){this.consecutiveFailures=0}async shutdown(){if(!this.process||this.state==="shutdown"||this.state==="idle")return;this.state="shutdown",this.clearIdleTimer();for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error("App server shutting down"));this.pendingRequests.clear(),this.startupReject&&(this.startupReject(new Error("App server shutting down")),this.startupResolve=null,this.startupReject=null);let e=this.process;this.process=null;try{e.kill("SIGTERM")}catch{this.state="idle";return}let r=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},Qk);await new Promise(n=>{e.on("close",()=>{clearTimeout(r),n()}),(e.exitCode!==null||e.signalCode!==null)&&(clearTimeout(r),n())}),this.state="idle"}async start(){if(this.state!=="idle"&&this.state!=="error")return;this.state="starting",this.stdoutBuffer="";let e=[...this.commandPrefix,...this.commandArgs,"app-server"],r=Lt(this.command,e);return this.process=Kk(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0}),this.process.stdout.on("data",n=>{this.handleStdout(n.toString())}),this.process.stderr.on("data",n=>{process.stderr.write(`[codex-app-server] ${n.toString()}`)}),this.process.on("close",(n,o)=>{this.handleProcessClose(n,o)}),this.process.on("error",n=>{this.handleProcessError(n)}),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((e,r)=>{let n=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",r(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs);this.startupResolve=()=>{clearTimeout(n),e()},this.startupReject=o=>{clearTimeout(n),r(o)}})}handleStdout(e){this.stdoutBuffer+=e;for(let n of this.pendingRequests.values())n.resetTimer();let r;for(;(r=this.stdoutBuffer.indexOf(`
26
26
  `))!==-1;){let n=this.stdoutBuffer.slice(0,r).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(r+1),!!n){if(this.state==="starting"&&(n.includes("ready")||n.includes("initialized"))){this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null);continue}try{let o=JSON.parse(n);if(o.id&&this.pendingRequests.has(o.id)){let s=this.pendingRequests.get(o.id);this.pendingRequests.delete(o.id),clearTimeout(s.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),s.resolve(o)}}catch{this.state==="starting"&&(this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null))}}}}sendRequest(e,r){return new Promise((n,o)=>{if(!this.process||!this.process.stdin){o(new Error("App server process not available"));return}let s=()=>{this.pendingRequests.delete(e.id),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),o(new Error(`App server request timeout (${r}ms of inactivity)`))},i=setTimeout(s,r),a=()=>{clearTimeout(i),i=setTimeout(s,r)};this.pendingRequests.set(e.id,{resolve:n,reject:o,timer:i,resetTimer:a}),this.state="busy",this.clearIdleTimer();try{this.process.stdin.write(JSON.stringify(e)+`
27
- `)}catch(c){clearTimeout(i),this.pendingRequests.delete(e.id),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",o(new Error(`Failed to write to app server: ${c.message}`))}})}handleProcessClose(e,r){for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error(`App server process exited (code=${e}, signal=${r})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject(new Error(`App server process exited during startup (code=${e})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(e){this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${e.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};function M(t){return t instanceof Error?t.message:String(t)}function $n(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}mn();async function kn(t,e){try{if((await ze({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await ze({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function Xf(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 We(r,n)}function em(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}
27
+ `)}catch(c){clearTimeout(i),this.pendingRequests.delete(e.id),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",o(new Error(`Failed to write to app server: ${c.message}`))}})}handleProcessClose(e,r){for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error(`App server process exited (code=${e}, signal=${r})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject(new Error(`App server process exited during startup (code=${e})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(e){this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${e.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};function M(t){return t instanceof Error?t.message:String(t)}function $n(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}mn();async function kn(t,e){try{if((await ze({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await ze({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function om(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await ze({command:t==="npx"?"npx":e,args:t==="npx"?[r,"--version"]:["--version"],timeout:1e4});return i.exitCode===0?{status:"ok",message:`${n} CLI available`}:{status:"error",message:`Exit code: ${i.exitCode}`}}catch(o){return{status:"error",message:o.message}}}function Pn(t,e,r){let n=e.trim()||`Exit code ${t}`,o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("quota")){let s=new me(r,`Rate limited: ${n}`);throw s.markUnavailable=!0,s}throw o.includes("auth")||o.includes("credential")||o.includes("login")||o.includes("api key")?new me(r,`Authentication issue: ${n}`):new He(r,n)}function sm(t){let e="",r=!1;return{feed(n){if(r)return null;e+=n;let o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("rate-limit")||o.includes("resource_exhausted")||o.includes("quota")){r=!0;let s=new me(t,`Rate limited (detected in stream): ${n.trim().slice(0,200)}`);return s.markUnavailable=!0,s}return o.includes("authentication")||o.includes("credential")||o.includes("api key")?(r=!0,new me(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Ur(t){let e=t.prompt;if(t.system&&(e=`${t.system}
28
28
 
29
29
  ${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
30
30
 
31
31
  ### File: ${r.path}
32
32
  \`\`\`
33
33
  ${r.content}
34
- \`\`\``);return e}function fi(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 We?t:t.message?.includes("timeout")?new un(e,r):new We(e,t.message)}function Hk(t){let e=t.prompt;if(t.files?.length)for(let r of t.files)r.content&&(e+=`
34
+ \`\`\``);return e}function mi(t,e){return!!t.files?.length||e.length>4e3}function ar(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Tn(t,e,r){throw t instanceof me||t instanceof He?t:t.message?.includes("timeout")?new un(e,r):new He(e,t.message)}function e0(t){let e=t.prompt;if(t.files?.length)for(let r of t.files)r.content&&(e+=`
35
35
 
36
36
  ### File: ${r.path}
37
37
  \`\`\`
38
38
  ${r.content}
39
- \`\`\``);return e}function Kk(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 er(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=Hk(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:Kk(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 We(this.id,n)}}};var Gk={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"]}]},mi=class extends cr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:Gk,modelName:e.modelName??"claude-host"})}};var Jk={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"]}]},hi=class extends cr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:Jk,modelName:e.modelName??"codex-host"})}};var Qk={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"]}]},gi=class extends cr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:Qk,modelName:e.modelName??"gemini-host"})}};jt();var tm={"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 rm={"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 nm={"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 om={"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 sm=Object.freeze({en:tm,ko:rm,ja:nm,zh:om});function r0(t){return typeof t=="string"&&qs.includes(t)}function Kc(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 im(t){return t===void 0?Gc(xr):r0(t)?Gc(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${xr}`),Gc(xr))}function n0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return Kc(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 ${Cc}`)),Kc(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),Kc(o,s))}}}function Gc(t){return n0(t,sm[t],sm[Cc])}async function am(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:o0(n.name||"")}))}function o0(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 am(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 We(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 We||i instanceof me?i:new We(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 ${Wp})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var i0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function cm(t){return t.split(`
40
- `).filter(n=>{let o=n.trim();return o?!i0.some(s=>s.test(o)):!1}).join(`
41
- `).trim()}function um(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 Jc="gemini",Qc="@google/gemini-cli",Vr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new Sn(rf);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await kn(Jc,Qc);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,Jc,Qc,["--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=fi(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,Jc,Qc,s),c=em(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=um(u.stdout);if(l!==null){let p=a0(u.stdout);return{text:l,model:p,provider:this.id}}return{text:cm(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 a0(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 c0}from"crypto";function Yc(t){let e=t.trim().split(`
39
+ \`\`\``);return e}function t0(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var cr=class{id;type;bridge;modelName;displayName;capabilities;constructor(e){this.id=e.id??e.bridge.providerId,this.type=e.type,this.bridge=e.bridge,this.modelName=e.modelName??e.type,this.displayName=e.displayName,this.capabilities=e.capabilities}async initialize(){}async healthCheck(){return this.bridge.healthCheck?this.bridge.healthCheck():this.bridge.isAvailable()?{status:"ok",message:`${this.displayName} host bridge available`}:{status:"error",message:`${this.displayName} host bridge unavailable`}}getCapabilities(){return{...this.capabilities,models:this.capabilities.models.map((e,r)=>r===0?{...e,name:this.modelName}:{...e})}}getDescriptor(){return tr(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new me(this.id,`${this.displayName} host bridge is not available`);try{let r=e0(e),n={...e.extra??{}};e.model&&(n.model=e.model),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.maxTokens=e.maxTokens);let o=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:o.text,model:t0(this.modelName,o.metadata),provider:this.id,metadata:o.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new me(this.id,n):new He(this.id,n)}}};var r0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude-host",description:"Claude host model via MCP sampling bridge",strengths:["reasoning","review","synthesis"]}]},hi=class extends cr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:r0,modelName:e.modelName??"claude-host"})}};var n0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["coding","reasoning","review","implementation"],models:[{name:"codex-host",description:"Codex host model via MCP sampling bridge",strengths:["coding","implementation","review"]}]},gi=class extends cr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:n0,modelName:e.modelName??"codex-host"})}};var o0={maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["analysis","reasoning","research","review"],models:[{name:"gemini-host",description:"Gemini host model via MCP sampling bridge",strengths:["analysis","research","review"]}]},yi=class extends cr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:o0,modelName:e.modelName??"gemini-host"})}};Nt();var im={"report.header.topic":"Topic","report.header.participants":"Participants","report.header.individualDocs":"Individual documents","report.table.proposer":"Proposer","report.table.opinion":"Opinion","report.table.severity":"Severity","report.table.agreement":"Agreement","report.section.mainTable":"Proposal ledger","report.section.dissentDetail":"Dissenting items","report.section.contributionSummary":"AI contribution summary","report.contribution.ai":"AI","report.contribution.proposed":"Proposed","report.contribution.accepted":"Accepted","report.contribution.revises":"Revises issued","report.contribution.abstains":"Abstains","report.footer.synthesisPath":"Final synthesis document","report.footer.debatePath":"Debate transcript","report.footer.pendingSynthesis":"(pending leader approval)","report.status.running":"running","report.status.readyForApproval":"ready for approval","report.status.consensus":"consensus","report.status.escalated":"escalated","report.status.approved":"approved","report.status.rejected":"rejected","report.status.leaderTimeout":"leader timeout","report.status.error":"error","synthesis.status.consensus":"Consensus reached","synthesis.status.escalated":"Partial / escalated","synthesis.section.acceptedItems":"Accepted Items","synthesis.section.rejectedItems":"Rejected / Withdrawn Items","synthesis.section.openItems":"Open Items","synthesis.section.sources":"Sources","synthesis.narration.consensusIn":"Consensus reached in round {round} of {max}.","synthesis.narration.escalated":"Session escalated by user after {round} rounds without consensus.","synthesis.narration.leaderNote":"Leader note","approval.pending":"Awaiting leader approval. Call `agent_debate_approve`, `agent_debate_continue`, or `agent_debate_reject`.","approval.timeout":"Session timed out waiting for leader decision ({hours}h).","moderator.narration.roundHeader":"Round {round} of {max}","moderator.narration.consensusInRound":"Consensus reached after {round} round(s).","moderator.narration.dissentDetailHeader":"Unresolved items","moderator.narration.noInterest":"No interest from participants","moderator.narration.participantDropout":"Participant `{participantId}` marked unavailable after repeated failures.","moderator.narration.participantTimeout":"Participant `{participantId}` did not respond in this round.","moderator.narration.leaderTimeoutFooter":"Leader Timeout","moderator.narration.rejected":"Session rejected by leader.","moderator.narration.approved":"Session approved by leader.","moderator.narration.aliasClarification":"Alias clarification phase","prompt.system.moderator":"You are the moderator of a structured multi-AI debate. You do not author proposals; you aggregate structured votes and produce a neutral synthesis. Respond only in the channels the protocol defines.","error.participantTimeout":"Participant `{participantId}` timed out after {seconds}s.","error.parseFailure":"Could not parse `<{tag}>` block from `{participantId}`.","error.sessionNotFound":"Debate session `{sessionId}` was not found.","error.invalidState":"Operation `{operation}` is not allowed in state `{state}`.","error.unknownLocaleFallback":"Unknown locale `{locale}`; falling back to `{fallback}`.","askUser.escalation.header":"Maximum rounds reached without consensus","askUser.escalation.question":"How would you like to proceed?","askUser.escalation.continue":"Continue +{rounds} rounds","askUser.escalation.escalate":"Escalate without consensus","askUser.escalation.stop":"Stop the debate"};var am={"report.header.topic":"\uC8FC\uC81C","report.header.participants":"\uCC38\uAC00\uC790","report.header.individualDocs":"\uAC1C\uBCC4 \uAC80\uD1A0 \uBB38\uC11C","report.table.proposer":"\uC81C\uC548\uC790","report.table.opinion":"\uC758\uACAC","report.table.severity":"\uC911\uC694\uB3C4","report.table.agreement":"\uB3D9\uC758\uC728","report.section.mainTable":"\uC81C\uC548 \uC6D0\uC7A5","report.section.dissentDetail":"\uBBF8\uD569\uC758 \uD56D\uBAA9 \uC0C1\uC138","report.section.contributionSummary":"AI \uAE30\uC5EC\uB3C4 \uC694\uC57D","report.contribution.ai":"AI","report.contribution.proposed":"\uC81C\uC548","report.contribution.accepted":"\uCC44\uD0DD","report.contribution.revises":"\uC218\uC815 \uC694\uCCAD","report.contribution.abstains":"\uAE30\uAD8C","report.footer.synthesisPath":"\uCD5C\uC885 \uD569\uC758 \uBB38\uC11C","report.footer.debatePath":"\uD1A0\uB860 \uAE30\uB85D","report.footer.pendingSynthesis":"(\uB9AC\uB354 \uC2B9\uC778 \uB300\uAE30 \uC911)","report.status.running":"\uC9C4\uD589 \uC911","report.status.readyForApproval":"\uC2B9\uC778 \uB300\uAE30","report.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","report.status.escalated":"\uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","report.status.approved":"\uC2B9\uC778\uB428","report.status.rejected":"\uAE30\uAC01\uB428","report.status.leaderTimeout":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","report.status.error":"\uC624\uB958","synthesis.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","synthesis.status.escalated":"\uBD80\uBD84 \uD569\uC758 / \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","synthesis.section.acceptedItems":"\uCC44\uD0DD \uD56D\uBAA9","synthesis.section.rejectedItems":"\uAE30\uAC01 / \uCCA0\uD68C \uD56D\uBAA9","synthesis.section.openItems":"\uBBF8\uACB0 \uD56D\uBAA9","synthesis.section.sources":"\uADFC\uAC70","synthesis.narration.consensusIn":"\uC804\uCCB4 {max}\uB77C\uC6B4\uB4DC \uC911 {round}\uB77C\uC6B4\uB4DC\uC5D0\uC11C \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","synthesis.narration.escalated":"{round}\uB77C\uC6B4\uB4DC \uB3D9\uC548 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD558\uC5EC \uC0AC\uC6A9\uC790 \uD310\uB2E8\uC73C\uB85C \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","synthesis.narration.leaderNote":"\uB9AC\uB354 \uBA54\uBAA8","approval.pending":"\uB9AC\uB354 \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uACE0 \uC788\uC2B5\uB2C8\uB2E4. `agent_debate_approve`, `agent_debate_continue`, `agent_debate_reject` \uC911 \uD558\uB098\uB97C \uD638\uCD9C\uD574 \uC8FC\uC2ED\uC2DC\uC624.","approval.timeout":"\uB9AC\uB354 \uACB0\uC815\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC138\uC158\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4({hours}\uC2DC\uAC04).","moderator.narration.roundHeader":"{round}/{max} \uB77C\uC6B4\uB4DC","moderator.narration.consensusInRound":"{round}\uB77C\uC6B4\uB4DC \uB9CC\uC5D0 \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","moderator.narration.dissentDetailHeader":"\uBBF8\uD574\uACB0 \uD56D\uBAA9","moderator.narration.noInterest":"\uCC38\uAC00\uC790 \uAD00\uC2EC \uC5C6\uC74C","moderator.narration.participantDropout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uBC18\uBCF5\uC801 \uC2E4\uD328\uB85C \uC778\uD574 \uC0AC\uC6A9 \uBD88\uAC00 \uC0C1\uD0DC\uB85C \uD45C\uC2DC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uC774\uBC88 \uB77C\uC6B4\uB4DC\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","moderator.narration.leaderTimeoutFooter":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","moderator.narration.rejected":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uAE30\uAC01\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.approved":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uC2B9\uC778\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.aliasClarification":"\uBCC4\uCE6D \uD655\uC778 \uB2E8\uACC4","prompt.system.moderator":"\uB2F9\uC2E0\uC740 \uAD6C\uC870\uD654\uB41C \uB2E4\uC911 AI \uD1A0\uB860\uC758 \uC911\uC7AC\uC790\uC785\uB2C8\uB2E4. \uC81C\uC548\uC744 \uC9C1\uC811 \uC791\uC131\uD558\uC9C0 \uC54A\uC73C\uBA70, \uAD6C\uC870\uD654\uB41C \uD22C\uD45C\uB97C \uC9D1\uACC4\uD558\uACE0 \uC911\uB9BD\uC801\uC778 \uD569\uC758\uC548\uC744 \uC0B0\uCD9C\uD569\uB2C8\uB2E4. \uD504\uB85C\uD1A0\uCF5C\uC774 \uC815\uC758\uD55C \uCC44\uB110 \uC548\uC5D0\uC11C\uB9CC \uC751\uB2F5\uD558\uC2ED\uC2DC\uC624.","error.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 {seconds}\uCD08 \uB0B4\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","error.parseFailure":"\uCC38\uAC00\uC790 `{participantId}`\uC758 `<{tag}>` \uBE14\uB85D\uC744 \uD574\uC11D\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.","error.sessionNotFound":"\uD1A0\uB860 \uC138\uC158 `{sessionId}`\uC744(\uB97C) \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.invalidState":"\uC0C1\uD0DC `{state}`\uC5D0\uC11C\uB294 `{operation}` \uC791\uC5C5\uC744 \uC218\uD589\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.unknownLocaleFallback":"\uC54C \uC218 \uC5C6\uB294 \uB85C\uCF00\uC77C `{locale}`; \uAE30\uBCF8\uAC12 `{fallback}`(\uC73C)\uB85C \uB300\uCCB4\uD569\uB2C8\uB2E4.","askUser.escalation.header":"\uCD5C\uB300 \uB77C\uC6B4\uB4DC\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC73C\uB098 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4","askUser.escalation.question":"\uC5B4\uB5BB\uAC8C \uC9C4\uD589\uD558\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?","askUser.escalation.continue":"{rounds}\uB77C\uC6B4\uB4DC \uCD94\uAC00 \uC9C4\uD589","askUser.escalation.escalate":"\uD569\uC758 \uC5C6\uC774 \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","askUser.escalation.stop":"\uD1A0\uB860 \uC885\uB8CC"};var cm={"report.header.topic":"\u30C6\u30FC\u30DE","report.header.participants":"\u53C2\u52A0\u8005","report.header.individualDocs":"\u500B\u5225\u30EC\u30D3\u30E5\u30FC\u6587\u66F8","report.table.proposer":"\u63D0\u6848\u8005","report.table.opinion":"\u610F\u898B","report.table.severity":"\u91CD\u5927\u5EA6","report.table.agreement":"\u5408\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u5E33","report.section.dissentDetail":"\u672A\u5408\u610F\u9805\u76EE\u306E\u8A73\u7D30","report.section.contributionSummary":"AI \u8CA2\u732E\u5EA6\u30B5\u30DE\u30EA\u30FC","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u6848","report.contribution.accepted":"\u63A1\u629E","report.contribution.revises":"\u4FEE\u6B63\u8981\u8ACB","report.contribution.abstains":"\u68C4\u6A29","report.footer.synthesisPath":"\u6700\u7D42\u5408\u610F\u6587\u66F8","report.footer.debatePath":"\u8A0E\u8B70\u8A18\u9332","report.footer.pendingSynthesis":"(\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u5F85\u3061)","report.status.running":"\u9032\u884C\u4E2D","report.status.readyForApproval":"\u627F\u8A8D\u5F85\u3061","report.status.consensus":"\u5408\u610F\u5F62\u6210","report.status.escalated":"\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","report.status.approved":"\u627F\u8A8D\u6E08\u307F","report.status.rejected":"\u5374\u4E0B","report.status.leaderTimeout":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","report.status.error":"\u30A8\u30E9\u30FC","synthesis.status.consensus":"\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F","synthesis.status.escalated":"\u90E8\u5206\u5408\u610F / \u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","synthesis.section.acceptedItems":"\u63A1\u629E\u9805\u76EE","synthesis.section.rejectedItems":"\u5374\u4E0B / \u53D6\u308A\u4E0B\u3052\u9805\u76EE","synthesis.section.openItems":"\u672A\u6C7A\u9805\u76EE","synthesis.section.sources":"\u6839\u62E0","synthesis.narration.consensusIn":"\u5168 {max} \u30E9\u30A6\u30F3\u30C9\u4E2D {round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","synthesis.narration.escalated":"{round} \u30E9\u30A6\u30F3\u30C9\u7D4C\u904E\u3057\u3066\u3082\u5408\u610F\u306B\u81F3\u3089\u305A\u3001\u30E6\u30FC\u30B6\u30FC\u5224\u65AD\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3\u3055\u308C\u307E\u3057\u305F\u3002","synthesis.narration.leaderNote":"\u30EA\u30FC\u30C0\u30FC\u30E1\u30E2","approval.pending":"\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u3092\u5F85\u6A5F\u3057\u3066\u3044\u307E\u3059\u3002`agent_debate_approve`\u3001`agent_debate_continue`\u3001`agent_debate_reject` \u306E\u3044\u305A\u308C\u304B\u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044\u3002","approval.timeout":"\u30EA\u30FC\u30C0\u30FC\u5224\u65AD\u3092\u5F85\u6A5F\u4E2D\u306B\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F({hours} \u6642\u9593)\u3002","moderator.narration.roundHeader":"\u30E9\u30A6\u30F3\u30C9 {round}/{max}","moderator.narration.consensusInRound":"{round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u6C7A\u9805\u76EE","moderator.narration.noInterest":"\u53C2\u52A0\u8005\u306E\u95A2\u5FC3\u306A\u3057","moderator.narration.participantDropout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u7E70\u308A\u8FD4\u3057\u306E\u5931\u6557\u306B\u3088\u308A\u5229\u7528\u4E0D\u53EF\u3068\u3057\u3066\u30DE\u30FC\u30AF\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u4ECA\u56DE\u306E\u30E9\u30A6\u30F3\u30C9\u3067\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","moderator.narration.leaderTimeoutFooter":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","moderator.narration.rejected":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u5374\u4E0B\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.approved":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u627F\u8A8D\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.aliasClarification":"\u5225\u540D\u78BA\u8A8D\u30D5\u30A7\u30FC\u30BA","prompt.system.moderator":"\u3042\u306A\u305F\u306F\u69CB\u9020\u5316\u30DE\u30EB\u30C1 AI \u8A0E\u8B70\u306E\u30E2\u30C7\u30EC\u30FC\u30BF\u30FC\u3067\u3059\u3002\u63D0\u6848\u3092\u81EA\u3089\u8D77\u6848\u305B\u305A\u3001\u69CB\u9020\u5316\u6295\u7968\u3092\u96C6\u8A08\u3057\u3066\u4E2D\u7ACB\u7684\u306A\u5408\u610F\u6848\u3092\u63D0\u793A\u3057\u307E\u3059\u3002\u30D7\u30ED\u30C8\u30B3\u30EB\u304C\u5B9A\u7FA9\u3059\u308B\u30C1\u30E3\u30CD\u30EB\u306E\u7BC4\u56F2\u5185\u3067\u306E\u307F\u5FDC\u7B54\u3057\u3066\u304F\u3060\u3055\u3044\u3002","error.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F {seconds} \u79D2\u4EE5\u5185\u306B\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.parseFailure":"\u53C2\u52A0\u8005 `{participantId}` \u306E `<{tag}>` \u30D6\u30ED\u30C3\u30AF\u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.sessionNotFound":"\u8A0E\u8B70\u30BB\u30C3\u30B7\u30E7\u30F3 `{sessionId}` \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.invalidState":"\u72B6\u614B `{state}` \u3067\u306F\u64CD\u4F5C `{operation}` \u3092\u5B9F\u884C\u3067\u304D\u307E\u305B\u3093\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u306E\u30ED\u30B1\u30FC\u30EB `{locale}`\u3002\u65E2\u5B9A\u5024 `{fallback}` \u306B\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u3059\u3002","askUser.escalation.header":"\u6700\u5927\u30E9\u30A6\u30F3\u30C9\u306B\u9054\u3057\u307E\u3057\u305F\u304C\u5408\u610F\u306B\u81F3\u308A\u307E\u305B\u3093\u3067\u3057\u305F","askUser.escalation.question":"\u3069\u306E\u3088\u3046\u306B\u9032\u3081\u307E\u3059\u304B?","askUser.escalation.continue":"{rounds} \u30E9\u30A6\u30F3\u30C9\u8FFD\u52A0\u3057\u3066\u7D9A\u884C","askUser.escalation.escalate":"\u5408\u610F\u306A\u3057\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","askUser.escalation.stop":"\u8A0E\u8B70\u3092\u7D42\u4E86"};var um={"report.header.topic":"\u4E3B\u9898","report.header.participants":"\u53C2\u4E0E\u8005","report.header.individualDocs":"\u4E2A\u4EBA\u8BC4\u5BA1\u6587\u6863","report.table.proposer":"\u63D0\u8BAE\u8005","report.table.opinion":"\u610F\u89C1","report.table.severity":"\u4E25\u91CD\u7A0B\u5EA6","report.table.agreement":"\u540C\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u8D26","report.section.dissentDetail":"\u672A\u8FBE\u6210\u4E00\u81F4\u9879\u8BE6\u60C5","report.section.contributionSummary":"AI \u8D21\u732E\u6C47\u603B","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u51FA","report.contribution.accepted":"\u91C7\u7EB3","report.contribution.revises":"\u4FEE\u8BA2\u8BF7\u6C42","report.contribution.abstains":"\u5F03\u6743","report.footer.synthesisPath":"\u6700\u7EC8\u5171\u8BC6\u6587\u6863","report.footer.debatePath":"\u8FA9\u8BBA\u8BB0\u5F55","report.footer.pendingSynthesis":"(\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6)","report.status.running":"\u8FDB\u884C\u4E2D","report.status.readyForApproval":"\u5F85\u6279\u51C6","report.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","report.status.escalated":"\u5DF2\u5347\u7EA7","report.status.approved":"\u5DF2\u6279\u51C6","report.status.rejected":"\u5DF2\u62D2\u7EDD","report.status.leaderTimeout":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","report.status.error":"\u9519\u8BEF","synthesis.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","synthesis.status.escalated":"\u90E8\u5206\u5171\u8BC6 / \u5DF2\u5347\u7EA7","synthesis.section.acceptedItems":"\u91C7\u7EB3\u9879","synthesis.section.rejectedItems":"\u62D2\u7EDD / \u64A4\u56DE\u9879","synthesis.section.openItems":"\u672A\u51B3\u9879","synthesis.section.sources":"\u4F9D\u636E","synthesis.narration.consensusIn":"\u5728\u5168\u90E8 {max} \u8F6E\u4E2D\u7684\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","synthesis.narration.escalated":"\u7ECF\u8FC7 {round} \u8F6E\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6,\u7531\u7528\u6237\u51B3\u5B9A\u5347\u7EA7\u5904\u7406\u3002","synthesis.narration.leaderNote":"\u8D1F\u8D23\u4EBA\u5907\u6CE8","approval.pending":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6\u3002\u8BF7\u8C03\u7528 `agent_debate_approve`\u3001`agent_debate_continue` \u6216 `agent_debate_reject`\u3002","approval.timeout":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u51B3\u7B56\u671F\u95F4\u4F1A\u8BDD\u5DF2\u8D85\u65F6({hours} \u5C0F\u65F6)\u3002","moderator.narration.roundHeader":"\u7B2C {round}/{max} \u8F6E","moderator.narration.consensusInRound":"\u5728\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u51B3\u9879","moderator.narration.noInterest":"\u53C2\u4E0E\u8005\u65E0\u5174\u8DA3","moderator.narration.participantDropout":"\u53C2\u4E0E\u8005 `{participantId}` \u56E0\u591A\u6B21\u5931\u8D25\u88AB\u6807\u8BB0\u4E3A\u4E0D\u53EF\u7528\u3002","moderator.narration.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728\u672C\u8F6E\u672A\u4F5C\u51FA\u54CD\u5E94\u3002","moderator.narration.leaderTimeoutFooter":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","moderator.narration.rejected":"\u8D1F\u8D23\u4EBA\u5DF2\u62D2\u7EDD\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.approved":"\u8D1F\u8D23\u4EBA\u5DF2\u6279\u51C6\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.aliasClarification":"\u522B\u540D\u6F84\u6E05\u9636\u6BB5","prompt.system.moderator":"\u4F60\u662F\u7ED3\u6784\u5316\u591A AI \u8FA9\u8BBA\u7684\u4E3B\u6301\u4EBA\u3002\u4F60\u4E0D\u64B0\u5199\u63D0\u6848,\u800C\u662F\u6C47\u603B\u7ED3\u6784\u5316\u6295\u7968\u5E76\u4EA7\u51FA\u4E2D\u7ACB\u7684\u5171\u8BC6\u65B9\u6848\u3002\u4EC5\u5728\u534F\u8BAE\u5B9A\u4E49\u7684\u901A\u9053\u8303\u56F4\u5185\u4F5C\u51FA\u54CD\u5E94\u3002","error.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728 {seconds} \u79D2\u5185\u672A\u54CD\u5E94\u3002","error.parseFailure":"\u65E0\u6CD5\u89E3\u6790\u53C2\u4E0E\u8005 `{participantId}` \u7684 `<{tag}>` \u5757\u3002","error.sessionNotFound":"\u672A\u627E\u5230\u8FA9\u8BBA\u4F1A\u8BDD `{sessionId}`\u3002","error.invalidState":"\u5728\u72B6\u6001 `{state}` \u4E0B\u4E0D\u5141\u8BB8\u6267\u884C\u64CD\u4F5C `{operation}`\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u533A\u57DF `{locale}`,\u56DE\u9000\u5230 `{fallback}`\u3002","askUser.escalation.header":"\u5DF2\u8FBE\u6700\u5927\u8F6E\u6B21\u4F46\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6","askUser.escalation.question":"\u60A8\u5E0C\u671B\u5982\u4F55\u7EE7\u7EED?","askUser.escalation.continue":"\u518D\u8FDB\u884C {rounds} \u8F6E","askUser.escalation.escalate":"\u4E0D\u8FBE\u6210\u5171\u8BC6\u5373\u5347\u7EA7","askUser.escalation.stop":"\u7ED3\u675F\u8FA9\u8BBA"};var lm=Object.freeze({en:im,ko:am,ja:cm,zh:um});function u0(t){return typeof t=="string"&&Vs.includes(t)}function Yc(t,e){return e===void 0?t:t.replace(/\{(\w+)\}/g,(r,n)=>{if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];return typeof o=="number"?String(o):o}return r})}function dm(t){return t===void 0?Qc(xr):u0(t)?Qc(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${xr}`),Qc(xr))}function l0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return Yc(i,s);let a=r[o];return a!==void 0?(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in locale '${t}', falling back to ${Oc}`)),Yc(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),Yc(o,s))}}}function Qc(t){return l0(t,lm[t],lm[Oc])}async function pm(t){let e=await fetch(`${t}/api/tags`);if(!e.ok)throw new Error(`Ollama API error: ${e.status}`);return((await e.json()).models||[]).map(n=>({name:n.name||"unknown",size:n.size||0,strengths:d0(n.name||"")}))}function d0(t){let e=["chat"],r=t.toLowerCase();return(r.includes("coder")||r.includes("code"))&&e.push("code_review","code_generation"),r.includes("instruct")&&e.push("instruction_following"),r.includes("embed")&&e.push("embedding"),e}var qr=class t{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(e){this.id=e.id,this.host=e.host,this.defaultModel=e.defaultModel||"auto",this.maxContext=e.maxContext??32768,this.timeouts={default:e.timeouts?.default??3e4,generate:e.timeouts?.generate??3e5,chat:e.timeouts?.chat??3e5}}async initialize(){try{this.models=await pm(this.host),this.available=this.models.length>0}catch{this.available=!1}}async healthCheck(){try{let e=await fetch(`${this.host}/api/tags`);if(!e.ok)return{status:"error",message:`HTTP ${e.status}`};let r=await e.json(),n=r.models?.length??0;return{status:n>0?"ok":"degraded",message:`${n} models available`,details:{models:r.models?.map(o=>o.name)}}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(e=>e.strengths))],models:this.models.map(e=>({name:e.name,description:`Ollama model (${Math.round(e.size/1e9)}GB)`,strengths:e.strengths,sizeGb:e.size/1e9}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(e){if(!this.available)throw new me(this.id,"Ollama not running or no models installed");let r=e.model||this.selectModel(),n={model:r,prompt:e.prompt,system:e.system||"You are a helpful assistant.",stream:!1,...e.extra||{}},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeouts.generate);try{let i=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(i.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new me(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!i.ok)throw new He(this.id,`HTTP ${i.status}: ${i.statusText}`);let a=await i.json();return{text:a.response||"",model:a.model||r,provider:this.id}}catch(i){throw i.name==="AbortError"?new un(this.id,this.timeouts.generate):i instanceof He||i instanceof me?i:new He(this.id,i.message)}finally{clearTimeout(s)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new me(this.id,`No models detected. Install a model first (ollama pull ${Yp})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var f0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function fm(t){return t.split(`
40
+ `).filter(n=>{let o=n.trim();return o?!f0.some(s=>s.test(o)):!1}).join(`
41
+ `).trim()}function mm(t){try{let e=JSON.parse(t.trim());if(e&&typeof e.response=="string")return e.response}catch{let e=t.split(`
42
+ `);for(let r=e.length-1;r>=0;r--){let n=e[r].trim();if(n.startsWith("{"))try{let o=JSON.parse(n);if(o&&typeof o.response=="string")return o.response}catch{}}}return null}var Xc="gemini",eu="@google/gemini-cli",Vr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new Sn(cf);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await kn(Xc,eu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){if(!this.available)return{status:"error",message:"Gemini CLI not installed"};try{let{command:e,cliArgs:r}=ar(this.cliPath,Xc,eu,["--version"]),n=await ze({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Gemini CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["long_context","file_analysis","translation","summarization"],models:[{name:"gemini-2.5-pro",description:"Google Gemini 2.5 Pro via CLI",strengths:["long_context","reasoning"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available)throw new me(this.id,"Gemini CLI not installed");let r=Ur(e),n=mi(e,r),s=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=ar(this.cliPath,Xc,eu,s),c=sm(this.id);try{let u=await ze({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,onStderrChunk:p=>c.feed(p)});if(u.exitCode!==0)try{Pn(u.exitCode,u.stderr,this.id)}catch(p){throw p.markUnavailable&&(this.available=!1),p}let l=mm(u.stdout);if(l!==null){let p=m0(u.stdout);return{text:l,model:p,provider:this.id}}return{text:fm(u.stdout),model:"gemini",provider:this.id}}catch(u){if(u instanceof me)throw u.markUnavailable&&(this.available=!1),u;Tn(u,this.id,this.timeout)}}};function m0(t){try{let e=JSON.parse(t.trim());if(e?.stats?.models){for(let[n,o]of Object.entries(e.stats.models))if(o?.roles?.main)return n;let r=Object.keys(e.stats.models);if(r.length>0)return r[0]}}catch{}return"gemini"}import{randomUUID as h0}from"crypto";function tu(t){let e=t.trim().split(`
43
43
  `),r=[];for(let n of e)try{let o=JSON.parse(n);o.type==="item.completed"&&o.item?.type==="agent_message"&&o.item.text&&r.push(o.item.text)}catch{n.trim()&&r.push(n.trim())}return r.join(`
44
- `)||t.trim()}var yi="codex",vi="@openai/codex";function u0(){return["-C",process.cwd()]}function l0(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(yi,vi);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new pi({command:this.cliPath==="npx"?"npx":yi,commandPrefix:this.cliPath==="npx"?[vi]:void 0,commandArgs:u0()}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=ar(this.cliPath,yi,vi,["--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:c0()},n=await this.appServer.request(r,this.timeout);if(n.error)throw new We(this.id,n.error.message);return{text:Yc(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=Ur(e),n=process.platform==="win32"||fi(e,r),o=l0(r,n),{command:s,cliArgs:i}=ar(this.cliPath,yi,vi,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:Yc(a.stdout),model:"codex",provider:this.id}}catch(a){Tn(a,this.id,this.timeout)}}};function lm(t){try{return JSON.parse(t.trim())}catch{return null}}function dm(t){let e=lm(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=lm(o);if(s)return s}return null}function pm(t){let e=dm(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function fm(t){let e=dm(t);return typeof e?.model=="string"?e.model:"claude"}var d0=1,Xc="claude",eu="@anthropic-ai/claude-code",Wr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Sn(d0);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(){return Xf(this.cliPath,Xc,eu,"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,Xc,eu,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:pm(i.stdout)??i.stdout.trim(),model:fm(i.stdout),provider:this.id}}catch(i){Tn(i,this.id,this.timeout)}}};import{randomUUID as p0}from"crypto";var f0=7200*1e3,ko=class{debates=new Map;create(e){this.purgeStaleDebates();let r=p0(),n=new Date().toISOString(),o={id:r,topic:e.topic,goal:e.goal,providerIds:e.providerIds,turns:[],status:"active",documentId:e.documentId,createdAt:n};return this.debates.set(r,o),o}addTurn(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);if(o.status==="concluded")throw new Error(`Debate already concluded: ${e}`);let s={turnNumber:o.turns.length+1,speaker:r,content:n,timestamp:new Date().toISOString()};return o.turns.push(s),o}buildPromptForProvider(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);let o=`Topic: ${n.topic}
44
+ `)||t.trim()}var vi="codex",_i="@openai/codex";function g0(){return["-C",process.cwd()]}function y0(t,e){return["exec","--skip-git-repo-check","-C",process.cwd(),"--full-auto","--ephemeral","--json","--",e?"-":t]}var Br=class{id;type="codex-cli";timeout;available=!1;cliPath=null;appServer=null;constructor(e){this.id=e.id,this.timeout=e.timeout??6e5}async initialize(){let e=await kn(vi,_i);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new fi({command:this.cliPath==="npx"?"npx":vi,commandPrefix:this.cliPath==="npx"?[_i]:void 0,commandArgs:g0()}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=ar(this.cliPath,vi,_i,["--version"]),n=await ze({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Codex CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:128e3,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!0,strengths:["code_generation","code_review","autonomous_execution"],models:[{name:"codex",description:"OpenAI Codex CLI",strengths:["code_generation"]}]}}isAvailable(){return this.available}async chat(e){if(!this.available)throw new me(this.id,"Codex CLI not installed");if(this.appServer&&!this.appServer.shouldFallback())try{return await this.chatViaAppServer(e)}catch{}return this.chatViaCli(e)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r={method:"exec",params:{prompt:Ur(e),fullAuto:!0,ephemeral:!0},id:h0()},n=await this.appServer.request(r,this.timeout);if(n.error)throw new He(this.id,n.error.message);return{text:tu(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=Ur(e),n=process.platform==="win32"||mi(e,r),o=y0(r,n),{command:s,cliArgs:i}=ar(this.cliPath,vi,_i,o);try{let a=await ze({command:s,args:i,stdin:n?r:void 0,timeout:this.timeout});if(a.exitCode!==0)try{Pn(a.exitCode,a.stderr,this.id)}catch(u){throw u.markUnavailable&&(this.available=!1),u}return{text:tu(a.stdout),model:"codex",provider:this.id}}catch(a){Tn(a,this.id,this.timeout)}}};function hm(t){try{return JSON.parse(t.trim())}catch{return null}}function gm(t){let e=hm(t);if(e)return e;let r=t.split(`
45
+ `);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=hm(o);if(s)return s}return null}function ym(t){let e=gm(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function vm(t){let e=gm(t);return typeof e?.model=="string"?e.model:"claude"}var v0=1,ru="claude",nu="@anthropic-ai/claude-code",Wr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Sn(v0);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await kn(ru,nu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return om(this.cliPath,ru,nu,"Claude")}getCapabilities(){return{maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude",description:"Anthropic Claude Code CLI",strengths:["reasoning","review","synthesis"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available||!this.cliPath)throw new me(this.id,"Claude CLI not installed");let r=Ur(e),n=["-p","--output-format","json"];e.model&&n.push("--model",e.model),n.push(r);let{command:o,cliArgs:s}=ar(this.cliPath,ru,nu,n);try{let i=await ze({command:o,args:s,timeout:this.timeout});if(i.exitCode!==0){let c=[i.stderr,i.stdout].filter(Boolean).join(`
46
+ `).trim();try{Pn(i.exitCode,c,this.id)}catch(u){throw(u.markUnavailable||/auth|credential|login|api key|oauth|token|401/i.test(c))&&(this.available=!1),u}}return{text:ym(i.stdout)??i.stdout.trim(),model:vm(i.stdout),provider:this.id}}catch(i){Tn(i,this.id,this.timeout)}}};import{randomUUID as _0}from"crypto";var b0=7200*1e3,Po=class{debates=new Map;create(e){this.purgeStaleDebates();let r=_0(),n=new Date().toISOString(),o={id:r,topic:e.topic,goal:e.goal,providerIds:e.providerIds,turns:[],status:"active",documentId:e.documentId,createdAt:n};return this.debates.set(r,o),o}addTurn(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);if(o.status==="concluded")throw new Error(`Debate already concluded: ${e}`);let s={turnNumber:o.turns.length+1,speaker:r,content:n,timestamp:new Date().toISOString()};return o.turns.push(s),o}buildPromptForProvider(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);let o=`Topic: ${n.topic}
47
47
  `;if(n.goal&&(o+=`Goal: ${n.goal}
48
48
  `),n.turns.length>0){o+=`
49
49
  === Conversation History ===
50
50
 
51
- `;let i=n.turns.length;if(i>Us){let u=i-Us,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];o+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
51
+ `;let i=n.turns.length;if(i>qs){let u=i-qs,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];o+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
52
52
 
53
- `}let a=n.turns.slice(-Us),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
53
+ `}let a=n.turns.slice(-qs),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
54
54
  ${u.content}
55
55
 
56
- `;if(c.length+l.length>Ec){c+=`[... history truncated at ${Ec} characters]
56
+ `;if(c.length+l.length>Ac){c+=`[... history truncated at ${Ac} characters]
57
57
 
58
58
  `;break}c+=l}o+=c,o+=`===
59
59
 
@@ -89,31 +89,31 @@ Evaluation goal: ${n.goal}
89
89
 
90
90
  ${o.content}
91
91
 
92
- `;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>f0&&this.debates.delete(r)}}};import{mkdirSync as m0,readFileSync as mm,readdirSync as tu,existsSync as _i,renameSync as h0,rmdirSync as g0}from"fs";import{join as y0}from"path";import{randomUUID as v0}from"crypto";function ru(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 hm=new Set(["completed","completed_with_errors","failed"]);function gm(t,e){return hm.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&hm.has(e)||t==="in_progress"&&e==="in_progress")}function ym(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 Po=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,m0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=y0(this.sessionDir,"sessions");if(!_i(e))return;let r;try{r=tu(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(_i(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{h0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{tu(e).length===0&&g0(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:v0(),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(_i(n))try{let o=mm(n,"utf-8"),s=JSON.parse(o);return ym(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(!gm(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(!gm(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);Ge(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!_i(this.sessionDir)){this.fullyLoaded=!0;return}let e=tu(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=mm(o,"utf-8"),i=JSON.parse(s);if(!ym(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 vm(t,e,r){try{let n=En(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var To=class{registry;chatAdapter;constructor(e,r){this.registry=e,this.chatAdapter=r}async chatWith(e,r){return this.chatAdapter?this.chatAdapter.chat(e,r):e.chat(r)}canValidate(e){if(this.chatAdapter){let r=this.registry.getCapability(e);return r.tier==="agent"||r.tier==="tool"}return this.isAgentTier(e)}async validate(e){let{items:r,criteria:n}=e,o=this.resolveValidators(e),s=[];for(let l of r)for(let d of o)d.id!==l.providerId&&s.push(this.reviewItem(l,d,n));let i=await Promise.all(s),a=this.detectConflicts(i),c=i.length>0&&i.every(l=>l.passed),u=i.length===0?this.chatAdapter?"No validators available for cross-validation.":"No agent-tier validators available for cross-validation.":void 0;return{reviews:i,overallPass:c,conflicts:a,message:u}}resolveValidators(e){if(e.validators)return e.validators.filter(o=>this.canValidate(o.id));let r=new Set,n=[];for(let o of e.items)r.has(o.providerId)||(r.add(o.providerId),this.canValidate(o.providerId)&&n.push(this.registry.get(o.providerId)));return n}isAgentTier(e){return this.registry.getCapability(e).tier==="agent"}async reviewItem(e,r,n){let o=n?`
92
+ `;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>b0&&this.debates.delete(r)}}};import{mkdirSync as w0,readFileSync as _m,readdirSync as ou,existsSync as bi,renameSync as x0,rmdirSync as S0}from"fs";import{join as $0}from"path";import{randomUUID as k0}from"crypto";function su(t){if(t.providers<=0)throw new Error(`deriveTerminalStatus: providers must be positive, got ${t.providers}`);if(t.failed<0||t.failed>t.providers)throw new Error(`deriveTerminalStatus: failed (${t.failed}) out of range [0, ${t.providers}]`);return t.failed===0?"completed":t.failed===t.providers?"failed":"completed_with_errors"}var bm=new Set(["completed","completed_with_errors","failed"]);function wm(t,e){return bm.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&bm.has(e)||t==="in_progress"&&e==="in_progress")}function xm(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}var To=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,w0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=$0(this.sessionDir,"sessions");if(!bi(e))return;let r;try{r=ou(e)}catch(o){console.warn(`[SessionManager] failed to read legacy nested dir ${e}: ${String(o)}`);return}let n=r.filter(o=>o.endsWith(".json"));for(let o of n){let s,i;try{s=Me(o,e),i=Me(o,this.sessionDir)}catch(a){console.warn(`[SessionManager] skipped legacy file ${JSON.stringify(o)}: ${String(a)}`);continue}if(bi(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{x0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{ou(e).length===0&&S0(e)}catch(o){console.warn(`[SessionManager] could not remove legacy nested dir ${e}: ${String(o)}`)}}createSession(e,r){let n=new Date().toISOString(),o={id:k0(),type:e,status:"pending",config:r,createdAt:n,updatedAt:n};return this.sessions.set(o.id,o),this.persist(o),o}getSession(e){let r=this.sessions.get(e);if(r)return r;if(!this.fullyLoaded){let n;try{n=Me(`${e}.json`,this.sessionDir)}catch{return}if(bi(n))try{let o=_m(n,"utf-8"),s=JSON.parse(o);return xm(s)?(this.sessions.set(s.id,s),s):void 0}catch{}}}listSessions(){return this.ensureFullyLoaded(),[...this.sessions.values()]}updateSessionStatus(e,r){let n=this.getSession(e);if(!n)throw new Error(`Session not found: ${e}`);if(!wm(n.status,r))throw new Error(`Illegal session transition: ${n.id} ${n.status} -> ${r}`);n.status=r,n.updatedAt=new Date().toISOString(),this.persist(n)}transitionSession(e,r,n){let o=this.getSession(e);if(!o)throw new Error(`Session not found: ${e}`);if(!wm(o.status,r))throw new Error(`Illegal session transition: ${o.id} ${o.status} -> ${r}`);o.status=r,n!==void 0&&(o.result=n),o.updatedAt=new Date().toISOString(),this.persist(o)}completeSession(e,r){this.transitionSession(e,"completed",r)}persist(e){let r=Me(`${e.id}.json`,this.sessionDir);Ue(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!bi(this.sessionDir)){this.fullyLoaded=!0;return}let e=ou(this.sessionDir).filter(r=>r.endsWith(".json"));for(let r of e){let n=r.replace(/\.json$/,"");if(!this.sessions.has(n))try{let o=Me(r,this.sessionDir),s=_m(o,"utf-8"),i=JSON.parse(s);if(!xm(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function En(t){if(!t||!t.trim())return null;try{return JSON.parse(t.trim())}catch{}let e=[],r=0,n=-1;for(let o=0;o<t.length;o++){let s=t[o];s==="{"?(r===0&&(n=o),r++):s==="}"&&(r--,r===0&&n>=0&&(e.push(t.slice(n,o+1)),n=-1),r<0&&(r=0))}if(e.length===0)return null;for(let o=e.length-1;o>=0;o--)try{return JSON.parse(e[o])}catch{continue}return null}function Sm(t,e,r){try{let n=En(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var Eo=class{registry;chatAdapter;constructor(e,r){this.registry=e,this.chatAdapter=r}async chatWith(e,r){return this.chatAdapter?this.chatAdapter.chat(e,r):e.chat(r)}canValidate(e){if(this.chatAdapter){let r=this.registry.getCapability(e);return r.tier==="agent"||r.tier==="tool"}return this.isAgentTier(e)}async validate(e){let{items:r,criteria:n}=e,o=this.resolveValidators(e),s=[];for(let l of r)for(let d of o)d.id!==l.providerId&&s.push(this.reviewItem(l,d,n));let i=await Promise.all(s),a=this.detectConflicts(i),c=i.length>0&&i.every(l=>l.passed),u=i.length===0?this.chatAdapter?"No validators available for cross-validation.":"No agent-tier validators available for cross-validation.":void 0;return{reviews:i,overallPass:c,conflicts:a,message:u}}resolveValidators(e){if(e.validators)return e.validators.filter(o=>this.canValidate(o.id));let r=new Set,n=[];for(let o of e.items)r.has(o.providerId)||(r.add(o.providerId),this.canValidate(o.providerId)&&n.push(this.registry.get(o.providerId)));return n}isAgentTier(e){return this.registry.getCapability(e).tier==="agent"}async reviewItem(e,r,n){let o=n?`
93
93
  Additional criteria: ${n}`:"",s=[`You are a cross-validator reviewing work from provider "${e.providerId}".`,`Task: ${e.task}`,`Content to review:
94
94
  ${e.content}`,o,"",'Respond with JSON only: { "passed": boolean, "feedback": "string", "suggestedFixes": "string or omit" }'].join(`
95
- `),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return vm(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 wm,readdirSync as xm,statSync as wi}from"fs";import{join as Sm,relative as w0}from"path";var _m=50*1024,bi=500,bm=100;function x0(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function S0(t,e){let r=[],n=o=>{let s=wi(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of xm(o)){let a=Sm(o,i),c=wi(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function $0(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 $m={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=Vt(String(t.path??""),e),n=wm(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
95
+ `),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return Sm(n,o=>({targetProvider:e,reviewerProvider:r,passed:!!o.passed,feedback:String(o.feedback??""),suggestedFixes:o.suggestedFixes?String(o.suggestedFixes):void 0}),o=>({targetProvider:e,reviewerProvider:r,passed:!1,feedback:o}))}detectConflicts(e){let r=[],n=new Map;for(let o of e){let s=o.targetProvider;n.has(s)||n.set(s,[]),n.get(s).push(o)}for(let[o,s]of n){if(s.length<2)continue;let i=s.filter(c=>c.passed),a=s.filter(c=>!c.passed);if(i.length>0&&a.length>0){let c=i.map(l=>l.reviewerProvider).join(", "),u=a.map(l=>l.reviewerProvider).join(", ");r.push(`Conflict on "${o}": passed by [${c}], failed by [${u}]`)}}return r}};import{readFileSync as Pm,readdirSync as Tm,statSync as xi}from"fs";import{join as Em,relative as E0}from"path";var $m=50*1024,wi=500,km=100;function R0(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function I0(t,e){let r=[],n=o=>{let s=xi(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of Tm(o)){let a=Em(o,i),c=xi(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function A0(t,e){if(process.platform!=="win32")return{command:t,args:e};let r=n=>`'${n.replace(/'/g,"''")}'`;switch(t){case"ls":{let n=e.length>0?r(e[0]):".",o=e.slice(1).map(r);return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-ChildItem -Name -LiteralPath ${n}${o.length?" "+o.join(" "):""}`]}}case"cat":return e.length===0?{command:t,args:e}:{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-Content -LiteralPath ${e.map(r).join(",")}`]};default:return{command:t,args:e}}}var Rm={name:"file_read",description:"Read the contents of a file. Returns the text content.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},offset:{type:"number",description:"Line offset to start reading from (0-based)"},limit:{type:"number",description:"Maximum number of lines to read"}},async execute(t,e){let r=Bt(String(t.path??""),e),n=Pm(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
96
96
  `),s=Number(t.offset??0),i=Number(t.limit??o.length);n=o.slice(s,s+i).join(`
97
- `)}return Buffer.byteLength(n,"utf-8")>_m&&(n=$n(n,_m,`
98
- ... [truncated]`)),n}},k0={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)`}},km={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=Vt(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=bi)return;let u=xm(a);for(let l of u){if(o.length>=bi)break;let d=Sm(a,l),p=c?`${c}/${l}`:l;try{let f=wi(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=bi?`
99
- ... [truncated at ${bi} entries]`:"";return o.join(`
100
- `)+i}},Pm={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=Vt(String(t.path??"."),e),o=t.glob?x0(String(t.glob)):null,s=wi(n).isDirectory(),i=S0(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=w0(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=wm(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>=bm))return c.join(`
97
+ `)}return Buffer.byteLength(n,"utf-8")>$m&&(n=$n(n,$m,`
98
+ ... [truncated]`)),n}},C0={name:"file_write",description:"Write content to a file. Creates parent directories if needed. Overwrites existing files.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},content:{type:"string",description:"Content to write",required:!0}},async execute(t,e){let r=ht(String(t.path??""),e),n=String(t.content??"");return se(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},Im={name:"file_list",description:"List files and directories at the given path.",parameters:{path:{type:"string",description:"Directory path relative to workspace (default: '.')"},recursive:{type:"boolean",description:"List recursively (default: false)"}},async execute(t,e){let r=Bt(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=wi)return;let u=Tm(a);for(let l of u){if(o.length>=wi)break;let d=Em(a,l),p=c?`${c}/${l}`:l;try{let f=xi(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=wi?`
99
+ ... [truncated at ${wi} entries]`:"";return o.join(`
100
+ `)+i}},Am={name:"grep_search",description:"Search file contents with a regex pattern. Returns matching lines with file paths and line numbers.",parameters:{pattern:{type:"string",description:"Regular expression pattern to search for",required:!0},path:{type:"string",description:"Directory or file path to search in (default: '.')"},glob:{type:"string",description:"Glob pattern to filter files (e.g., '*.ts')"}},async execute(t,e){let r=String(t.pattern??""),n=Bt(String(t.path??"."),e),o=t.glob?R0(String(t.glob)):null,s=xi(n).isDirectory(),i=I0(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=E0(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=Pm(u,"utf-8")}catch{continue}let p=d.split(/\r?\n/);for(let f=0;f<p.length;f++)if(a.test(p[f])&&(c.push(`${l}:${f+1}:${p[f]}`),c.length>=km))return c.join(`
101
101
  `)+`
102
- ... [truncated at ${bm} matches]`}return c.join(`
103
- `)||"No matches found."}catch{return"No matches found."}}},P0={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...ai].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=jf(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=$0(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?`
102
+ ... [truncated at ${km} matches]`}return c.join(`
103
+ `)||"No matches found."}catch{return"No matches found."}}},D0={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...ci].join(", ")}). Shell operators (pipes, chaining, subshells) are blocked.`,parameters:{command:{type:"string",description:"Shell command to execute",required:!0}},async execute(t,e){let r=String(t.command??"").trim();if(!r)return"Error: empty command";let n=qf(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=A0(s,i);try{let c=await ze({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
104
104
  `:"")+`[stderr] ${c.stderr}`),c.exitCode!==0&&(u+=`
105
105
  [exit code: ${c.exitCode}]`),c.truncated&&(u+=`
106
- ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${M(c)}`}}};function nu(){return[$m,k0,km,Pm,P0]}function xi(){return[$m,km,Pm]}function ou(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 T0=15,E0=30,R0=3e5,I0=2e3,A0=`You are a coding assistant with access to tools for reading, writing, and searching files in a workspace. Use the provided tools when you need to inspect or modify code. When your task is complete, respond with your final answer without making any tool calls.
106
+ ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${M(c)}`}}};function iu(){return[Rm,C0,Im,Am,D0]}function Si(){return[Rm,Im,Am]}function au(t){return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:e.parameters,required:Object.entries(e.parameters).filter(([,r])=>r.required===!0).map(([r])=>r)}}}))}var z0=15,O0=30,M0=3e5,j0=2e3,N0=`You are a coding assistant with access to tools for reading, writing, and searching files in a workspace. Use the provided tools when you need to inspect or modify code. When your task is complete, respond with your final answer without making any tool calls.
107
107
 
108
108
  Guidelines:
109
109
  - Read files before modifying them to understand the existing code.
110
110
  - Use grep_search to find relevant code across the workspace.
111
111
  - Write complete file contents when using file_write (not just diffs).
112
- - Provide a clear summary of what you did when finished.`,Si=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??T0,E0),this.timeoutMs=e.timeoutMs??R0,this.systemPrompt=e.systemPrompt??A0,this.tools=e.tools??nu(),this.toolDefs=ou(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r]))}async run(e){let r=Date.now(),n=[],o="",s=[{role:"system",content:this.systemPrompt},{role:"user",content:e}];for(let i=0;i<this.maxIterations;i++){if(Date.now()-r>this.timeoutMs)return{success:!1,output:o||"Agent loop timed out before completion.",iterations:i,toolCalls:n,error:`Timed out after ${this.timeoutMs}ms`};let a;try{a=await this.callOllama(s)}catch(u){let l=M(u);return{success:!1,output:o||"",iterations:i,toolCalls:n,error:`Ollama API error: ${l}`}}let c=a.message;if(c.content&&(o=c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:o,iterations:i+1,toolCalls:n};s.push(c);for(let u of c.tool_calls){let l=u.function.name,d=u.function.arguments,p;if(typeof d=="string"){let y=En(d);p=y&&typeof y=="object"&&!Array.isArray(y)?y:{}}else p=d??{};let f=this.toolMap.get(l),m=Date.now(),g;if(!f)g=`Error: unknown tool '${l}'. Available tools: ${[...this.toolMap.keys()].join(", ")}`;else try{g=await f.execute(p,this.baseDir)}catch(y){g=`Error: ${M(y)}`}n.push({iteration:i,toolName:l,arguments:p,result:$n(g,I0,"... [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 Tm(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(Vs(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Tm(e);return o?{text:(await new Si({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 Eo,readFileSync as z0,readdirSync as O0}from"fs";import{join as In}from"path";var Ro=class{baseDir;constructor(e){this.baseDir=e}async run(e={}){let r=e.timeoutMs??12e4,n=e.buildProfile??"auto",o=this.resolveProfile(n),s=e.designDoc??this.detectDesignDoc(),i=o?await this.runProfile(o,r):{exitCode:0,output:"(no build profile resolved)"},a=i.exitCode===0,c=i.output,u=[];o?u.push(`${o.name}: ${a?"PASS":"FAIL"}`):u.push("No profile resolved"),s&&u.push(`Design doc: ${s}`);let d=`**AutoQA: ${a?"PASS":"FAIL"}**
112
+ - Provide a clear summary of what you did when finished.`,$i=class{host;model;baseDir;maxIterations;timeoutMs;systemPrompt;tools;toolDefs;toolMap;constructor(e){this.host=e.providerHost.replace(/\/$/,""),this.model=e.model,this.baseDir=e.baseDir,this.maxIterations=Math.min(e.maxIterations??z0,O0),this.timeoutMs=e.timeoutMs??M0,this.systemPrompt=e.systemPrompt??N0,this.tools=e.tools??iu(),this.toolDefs=au(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r]))}async run(e){let r=Date.now(),n=[],o="",s=[{role:"system",content:this.systemPrompt},{role:"user",content:e}];for(let i=0;i<this.maxIterations;i++){if(Date.now()-r>this.timeoutMs)return{success:!1,output:o||"Agent loop timed out before completion.",iterations:i,toolCalls:n,error:`Timed out after ${this.timeoutMs}ms`};let a;try{a=await this.callOllama(s)}catch(u){let l=M(u);return{success:!1,output:o||"",iterations:i,toolCalls:n,error:`Ollama API error: ${l}`}}let c=a.message;if(c.content&&(o=c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:o,iterations:i+1,toolCalls:n};s.push(c);for(let u of c.tool_calls){let l=u.function.name,d=u.function.arguments,p;if(typeof d=="string"){let y=En(d);p=y&&typeof y=="object"&&!Array.isArray(y)?y:{}}else p=d??{};let f=this.toolMap.get(l),m=Date.now(),g;if(!f)g=`Error: unknown tool '${l}'. Available tools: ${[...this.toolMap.keys()].join(", ")}`;else try{g=await f.execute(p,this.baseDir)}catch(y){g=`Error: ${M(y)}`}n.push({iteration:i,toolName:l,arguments:p,result:$n(g,j0,"... [truncated in log]"),durationMs:Date.now()-m}),s.push({role:"tool",content:g})}}return{success:!1,output:o||"Agent loop reached max iterations without completing.",iterations:this.maxIterations,toolCalls:n,error:`Max iterations (${this.maxIterations}) reached`}}async callOllama(e){let r=`${this.host}/api/chat`,n={model:this.model,messages:e,tools:this.toolDefs,stream:!1},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`HTTP ${i.status}: ${a.slice(0,200)}`)}return await i.json()}finally{clearTimeout(s)}}};function Cm(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var Rn=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(Bs(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Cm(e);return o?{text:(await new $i({providerHost:o.host,model:o.model,baseDir:this.baseDir,tools:this.tools}).run(r.prompt)).output,model:o.model,provider:e.id}:e.chat(r)}};import{existsSync as Ro,readFileSync as Z0,readdirSync as U0}from"fs";import{join as In}from"path";var Io=class{baseDir;constructor(e){this.baseDir=e}async run(e={}){let r=e.timeoutMs??12e4,n=e.buildProfile??"auto",o=this.resolveProfile(n),s=e.designDoc??this.detectDesignDoc(),i=o?await this.runProfile(o,r):{exitCode:0,output:"(no build profile resolved)"},a=i.exitCode===0,c=i.output,u=[];o?u.push(`${o.name}: ${a?"PASS":"FAIL"}`):u.push("No profile resolved"),s&&u.push(`Design doc: ${s}`);let d=`**AutoQA: ${a?"PASS":"FAIL"}**
113
113
  ${u.join(`
114
- `)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=dn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(Eo(In(this.baseDir,"tsconfig.json")))return dn.tsc;if(Eo(In(this.baseDir,"vitest.config.ts"))||Eo(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(!Eo(e))return null;try{let r=O0(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(!Eo(e))return null;try{return JSON.parse(z0(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{oi(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}
114
+ `)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=dn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(Ro(In(this.baseDir,"tsconfig.json")))return dn.tsc;if(Ro(In(this.baseDir,"vitest.config.ts"))||Ro(In(this.baseDir,"vitest.config.js")))return dn.vitest;let e=this.getPackageScripts();return e?.build?dn["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?dn["npm-test"]:null}detectDesignDoc(){let e=In(this.baseDir,"docs","plans");if(!Ro(e))return null;try{let r=U0(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return In("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=In(this.baseDir,"package.json");if(!Ro(e))return null;try{return JSON.parse(Z0(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{si(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof tt?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await ze({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),o=n.exitCode===0?n.stdout:`${n.stdout}
115
115
  ${n.stderr}`.trim(),s=$n(o,1e4,`
116
- ... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var M0=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),N0=/[\w./\\]+\.[a-z]{1,4}/gi,j0=/\b\d+\.?\d*\b/g,L0=/`[^`\n]+`/g,F0=/https?:\/\/\S+/g,Z0=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function $i(t){return Math.max(0,Math.min(1,t))}function Bt(t,e){return t.match(e)?.length??0}function U0(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 q0(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return M0.has(e)?!0:e.replace(/\s+/g,"").length<5}function V0(t){let e=U0(t);if(e.length===0)return .1;let r=e.filter(q0).length,n=(e.length-r)/e.length;return Math.max(.1,$i(n))}function B0(t){let e=Bt(t,/^\s*#\s+/gm),r=Bt(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Bt(t,/^\s*```/gm)/2),o=Bt(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return $i(s/3)}function W0(t){let e=Bt(t,N0)+Bt(t,j0)+Bt(t,L0)+Bt(t,F0)+Bt(t,Z0);return $i(e/3)}function Em(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function H0(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Em(i.content))r.add(a);if(r.size===0)return 0;let n=Em(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return $i(o/s)}function Io(t,e,r){let n={substanceRatio:V0(t),structureScore:B0(t),specificityScore:W0(t),engagementScore:H0(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as ki,readFileSync as Rm,readdirSync as su,existsSync as Co,statSync as G0,unlinkSync as J0}from"fs";import{basename as Im,join as Ao,relative as Am,sep as Cm}from"path";import{randomUUID as Q0}from"crypto";var Y0="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 X0(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(!Co(t))return"001";let r=su(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 Dm(t){return Cm==="/"?t:t.split(Cm).join("/")}var Do=class{baseDir;reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.baseDir=e,this.reviewDir=Ao(e,Y0),this.individualDir=Ao(e,Qp),this.debateDir=Ao(e,Zs),this.synthesisDir=Ao(e,Yp),ki(this.reviewDir,{recursive:!0}),ki(this.individualDir,{recursive:!0}),ki(this.debateDir,{recursive:!0}),ki(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(Co(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):Q0().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}
116
+ ... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var q0=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),V0=/[\w./\\]+\.[a-z]{1,4}/gi,B0=/\b\d+\.?\d*\b/g,W0=/`[^`\n]+`/g,H0=/https?:\/\/\S+/g,K0=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function ki(t){return Math.max(0,Math.min(1,t))}function Wt(t,e){return t.match(e)?.length??0}function J0(t){let r=t.split(/[.!?]+|\n+(?=\S)/g).map(n=>n.trim()).filter(n=>n.length>0);return r.length>0?r:t.trim().length>0?[t.trim()]:[]}function G0(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return q0.has(e)?!0:e.replace(/\s+/g,"").length<5}function Y0(t){let e=J0(t);if(e.length===0)return .1;let r=e.filter(G0).length,n=(e.length-r)/e.length;return Math.max(.1,ki(n))}function Q0(t){let e=Wt(t,/^\s*#\s+/gm),r=Wt(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Wt(t,/^\s*```/gm)/2),o=Wt(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return ki(s/3)}function X0(t){let e=Wt(t,V0)+Wt(t,B0)+Wt(t,W0)+Wt(t,H0)+Wt(t,K0);return ki(e/3)}function Dm(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function eP(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Dm(i.content))r.add(a);if(r.size===0)return 0;let n=Dm(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return ki(o/s)}function Ao(t,e,r){let n={substanceRatio:Y0(t),structureScore:Q0(t),specificityScore:X0(t),engagementScore:eP(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Pi,readFileSync as zm,readdirSync as cu,existsSync as Do,statSync as rP,unlinkSync as nP}from"fs";import{basename as Om,join as Co,relative as Mm,sep as jm}from"path";import{randomUUID as oP}from"crypto";var sP="reviews";function An(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function iP(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function Cn(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}${r}${n}`}function Dn(t,e){if(!Do(t))return"001";let r=cu(t).filter(o=>o.includes(`_${e}_`)),n=0;for(let o of r){let s=o.match(new RegExp(`_${e}_(\\d{3})\\.md$`));if(s){let i=parseInt(s[1],10);i>n&&(n=i)}}return String(n+1).padStart(3,"0")}function Nm(t){return jm==="/"?t:t.split(jm).join("/")}var zo=class{baseDir;reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.baseDir=e,this.reviewDir=Co(e,sP),this.individualDir=Co(e,rf),this.debateDir=Co(e,Us),this.synthesisDir=Co(e,nf),Pi(this.reviewDir,{recursive:!0}),Pi(this.individualDir,{recursive:!0}),Pi(this.debateDir,{recursive:!0}),Pi(this.synthesisDir,{recursive:!0})}get allDirs(){return[this.individualDir,this.debateDir,this.synthesisDir,this.reviewDir]}resolveDocPath(e){let r;for(let n of this.allDirs)try{let o=Me(`${e}.md`,n);if(Do(o))return o}catch(o){r===void 0&&(r=o)}throw r!==void 0?r:new Error(`Document not found: ${e}`)}async createReview(e){let r=Cn(),n=e.topic?An(e.topic):oP().slice(0,8),o=Dn(this.reviewDir,r),s=e.provider?`${e.provider}_${n}_${r}_${o}`:`${n}_${r}_${o}`,i=Me(`${s}.md`,this.reviewDir),a=`# Review: ${e.topic??s}
117
117
 
118
118
  `;a+=`**Date:** ${new Date().toISOString().slice(0,10)}
119
119
  `,e.provider&&(a+=`**Provider:** ${e.provider}
@@ -136,7 +136,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
136
136
  `),a+=`
137
137
  ---
138
138
 
139
- `,se(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=Cn(),n=X0(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}
139
+ `,se(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=Cn(),n=iP(e.participantId),o=An(e.topic),s=Dn(this.individualDir,r),i=`${n}_${o}_${r}_${s}`,a=Me(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
140
140
 
141
141
  `;if(c+=`**Date:** ${new Date().toISOString().slice(0,10)}
142
142
  `,c+=`**Participant:** ${e.participantId}
@@ -151,7 +151,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
151
151
  `,c+=e.content,c+=`
152
152
 
153
153
  ---
154
- `,se(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=Cn(),n=e.sessionId.slice(0,8),o=Dn(this.individualDir,r),s=`${Xp}_${n}_${r}_${o}`,i=Me(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
154
+ `,se(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=Cn(),n=e.sessionId.slice(0,8),o=Dn(this.individualDir,r),s=`${of}_${n}_${r}_${o}`,i=Me(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
155
155
 
156
156
  `;if(a+=`**Session:** ${e.sessionId}
157
157
  `,a+=`**Rejected at:** ${new Date().toISOString()}
@@ -170,7 +170,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
170
170
  `}a+=`
171
171
  `}return a+=`
172
172
  ---
173
- `,se(i,a),{id:s,content:a,path:i}}async createSynthesis(e){let r=Cn(),n=An(e.topic),o=Dn(this.synthesisDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.synthesisDir),a=Dm(Am(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>Dm(Am(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
173
+ `,se(i,a),{id:s,content:a,path:i}}async createSynthesis(e){let r=Cn(),n=An(e.topic),o=Dn(this.synthesisDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.synthesisDir),a=Nm(Mm(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>Nm(Mm(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
174
174
 
175
175
  `;if(u+=`**Date:** ${new Date().toISOString().slice(0,10)}
176
176
  `,u+=`**Status:** ${e.status}
@@ -181,16 +181,16 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
181
181
  `;if(u+=`
182
182
  ## Sources
183
183
 
184
- `,u+=`- Debate transcript: [${Im(e.debatePath)}](${a})
184
+ `,u+=`- Debate transcript: [${Om(e.debatePath)}](${a})
185
185
  `,e.individualPaths.length>0){u+=`- Individual reviews:
186
- `;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${Im(d)}](${c[l]})
186
+ `;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${Om(d)}](${c[l]})
187
187
  `}}return u+=`
188
188
  ---
189
189
 
190
190
  `,u+=e.body,u+=`
191
191
 
192
192
  ---
193
- `,se(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Me(`${e}.md`,this.synthesisDir);if(!Co(n))throw new Error(`Synthesis document not found: ${e}`);ti(n,`
193
+ `,se(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Me(`${e}.md`,this.synthesisDir);if(!Do(n))throw new Error(`Synthesis document not found: ${e}`);ri(n,`
194
194
  ${r}
195
195
  `)}async addComment(e,r){let n=this.resolveDocPath(e),o=`
196
196
  ## Comment by ${r.author}
@@ -198,45 +198,45 @@ ${r}
198
198
  ${r.content}
199
199
 
200
200
  ---
201
- `;ti(n,o)}async read(e){let r=this.resolveDocPath(e),n=Rm(r,"utf-8");return{id:e,content:n,path:r}}async createDocument(e){let r=Cn(),n=e.topic?An(e.topic):An(e.title),o=Dn(this.reviewDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.reviewDir),a=`# ${e.title}
201
+ `;ri(n,o)}async read(e){let r=this.resolveDocPath(e),n=zm(r,"utf-8");return{id:e,content:n,path:r}}async createDocument(e){let r=Cn(),n=e.topic?An(e.topic):An(e.title),o=Dn(this.reviewDir,r),s=`${n}_${r}_${o}`,i=Me(`${s}.md`,this.reviewDir),a=`# ${e.title}
202
202
 
203
203
  `;if(e.metadata){for(let[c,u]of Object.entries(e.metadata))a+=`**${c}:** ${u}
204
204
  `;a+=`
205
205
  `}return a+=e.content,a+=`
206
206
 
207
207
  ---
208
- `,se(i,a),{id:s,content:a,path:i}}async list(){let e=[];for(let r of this.allDirs){if(!Co(r))continue;let n=su(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Me(o,r),a=Rm(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(!Co(a))continue;let c=su(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Ao(a,u),d=G0(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{J0(c[u].path),i++}catch{}}}return{removed:i}}};var FF=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 Wt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Pi={};function at(t){return t&&Object.assign(Pi,t),Pi}var ie={};Be(ie,{BIGINT_FORMAT_RANGES:()=>Om,Class:()=>au,NUMBER_FORMAT_RANGES:()=>hu,aborted:()=>Kr,allowsEval:()=>pu,assert:()=>oP,assertEqual:()=>eP,assertIs:()=>rP,assertNever:()=>nP,assertNotEqual:()=>tP,assignProp:()=>du,cached:()=>Oo,captureStackTrace:()=>Ei,cleanEnum:()=>yP,cleanRegex:()=>No,clone:()=>It,createTransparentProxy:()=>lP,defineLazy:()=>de,esc:()=>Hr,escapeRegex:()=>ur,extend:()=>fP,finalizeIssue:()=>gt,floatSafeRemainder:()=>lu,getElementAtPath:()=>sP,getEnumValues:()=>cu,getLengthableOrigin:()=>jo,getParsedType:()=>uP,getSizableOrigin:()=>Mm,isObject:()=>zn,isPlainObject:()=>On,issue:()=>gu,joinValues:()=>Ti,jsonStringifyReplacer:()=>uu,merge:()=>mP,normalizeParams:()=>j,nullish:()=>Mo,numKeys:()=>cP,omit:()=>pP,optionalKeys:()=>mu,partial:()=>hP,pick:()=>dP,prefixIssues:()=>At,primitiveTypes:()=>zm,promiseAllObject:()=>iP,propertyKeyTypes:()=>fu,randomString:()=>aP,required:()=>gP,stringifyPrimitive:()=>Ri,unwrapMessage:()=>zo});function eP(t){return t}function tP(t){return t}function rP(t){}function nP(t){throw new Error}function oP(t){}function cu(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 Ti(t,e="|"){return t.map(r=>Ri(r)).join(e)}function uu(t,e){return typeof e=="bigint"?e.toString():e}function Oo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Mo(t){return t==null}function No(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function lu(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 du(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function sP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function iP(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 aP(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 Ei=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pu=Oo(()=>{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 cP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var uP=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}`)}},fu=new Set(["string","number","symbol"]),zm=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 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 lP(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 Ri(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function mu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var hu={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]},Om={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function dP(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 pP(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 fP(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 du(this,"shape",n),n},checks:[]};return It(t,r)}function mP(t,e){return It(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return du(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function hP(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 gP(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 zo(t){return typeof t=="string"?t:t?.message}function gt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=zo(t.inst?._zod.def?.error?.(t))??zo(e?.error?.(t))??zo(r.customError?.(t))??zo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Mm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function jo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function gu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function yP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var au=class{constructor(...e){}};var Nm=(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,uu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ii=w("$ZodError",Nm),yu=w("$ZodError",Nm,{Parent:Error});function jm(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 Lm(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 Fm=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 Wt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw Ei(a,o?.callee),a}return i.value};var Zm=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 Ei(a,o?.callee),a}return i.value};var vu=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 Wt;return s.issues.length?{success:!1,error:new(t??Ii)(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Lo=vu(yu),_u=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}},Ai=_u(yu);var Um=/^[cC][^\s-]{8,}$/,qm=/^[0-9a-z]+$/,Vm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Bm=/^[0-9a-vA-V]{20}$/,Wm=/^[A-Za-z0-9]{27}$/,Hm=/^[a-zA-Z0-9_-]{21}$/,Km=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Gm=/^([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})$/,bu=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 Jm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var _P="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Qm(){return new RegExp(_P,"u")}var Ym=/^(?:(?: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])$/,Xm=/^(([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})$/,eh=/^((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])$/,th=/^(([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])$/,rh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wu=/^[A-Za-z0-9_-]*$/,nh=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var oh=/^\+(?:[0-9]){6,14}[0-9]$/,sh="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ih=new RegExp(`^${sh}$`);function ah(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 ch(t){return new RegExp(`^${ah(t)}$`)}function uh(t){let e=ah({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(`^${sh}T(?:${n})$`)}var lh=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var dh=/^\d+$/,ph=/^-?\d+(?:\.\d+)?/i,fh=/true|false/i,mh=/null/i;var hh=/^[^A-Z]*$/,gh=/^[^a-z]*$/;var Ne=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),yh={number:"number",bigint:"bigint",object:"date"},Su=w("$ZodCheckLessThan",(t,e)=>{Ne.init(t,e);let r=yh[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})}}),$u=w("$ZodCheckGreaterThan",(t,e)=>{Ne.init(t,e);let r=yh[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})}}),vh=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):lu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),_h=w("$ZodCheckNumberFormat",(t,e)=>{Ne.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=hu[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 bh=w("$ZodCheckMaxLength",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Mo(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=jo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),wh=w("$ZodCheckMinLength",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Mo(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=jo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),xh=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Mo(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=jo(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})}}),Fo=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=()=>{})}),Sh=w("$ZodCheckRegex",(t,e)=>{Fo.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})}}),$h=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=hh),Fo.init(t,e)}),kh=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=gh),Fo.init(t,e)}),Ph=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})}}),Th=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})}}),Eh=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 Rh=w("$ZodCheckOverwrite",(t,e)=>{Ne.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Ci=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
208
+ `,se(i,a),{id:s,content:a,path:i}}async list(){let e=[];for(let r of this.allDirs){if(!Do(r))continue;let n=cu(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Me(o,r),a=zm(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!Do(a))continue;let c=cu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Co(a,u),d=rP(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=o-c[u].mtime;if(u>=n||l>s)try{nP(c[u].path),i++}catch{}}}return{removed:i}}};var dZ=Object.freeze({status:"aborted"});function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ht=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ti={};function at(t){return t&&Object.assign(Ti,t),Ti}var ie={};Ze(ie,{BIGINT_FORMAT_RANGES:()=>Fm,Class:()=>lu,NUMBER_FORMAT_RANGES:()=>vu,aborted:()=>Kr,allowsEval:()=>hu,assert:()=>dP,assertEqual:()=>aP,assertIs:()=>uP,assertNever:()=>lP,assertNotEqual:()=>cP,assignProp:()=>mu,cached:()=>Mo,captureStackTrace:()=>Ri,cleanEnum:()=>$P,cleanRegex:()=>No,clone:()=>It,createTransparentProxy:()=>yP,defineLazy:()=>de,esc:()=>Hr,escapeRegex:()=>ur,extend:()=>bP,finalizeIssue:()=>gt,floatSafeRemainder:()=>fu,getElementAtPath:()=>pP,getEnumValues:()=>du,getLengthableOrigin:()=>Lo,getParsedType:()=>gP,getSizableOrigin:()=>Zm,isObject:()=>zn,isPlainObject:()=>On,issue:()=>_u,joinValues:()=>Ei,jsonStringifyReplacer:()=>pu,merge:()=>wP,normalizeParams:()=>N,nullish:()=>jo,numKeys:()=>hP,omit:()=>_P,optionalKeys:()=>yu,partial:()=>xP,pick:()=>vP,prefixIssues:()=>At,primitiveTypes:()=>Lm,promiseAllObject:()=>fP,propertyKeyTypes:()=>gu,randomString:()=>mP,required:()=>SP,stringifyPrimitive:()=>Ii,unwrapMessage:()=>Oo});function aP(t){return t}function cP(t){return t}function uP(t){}function lP(t){throw new Error}function dP(t){}function du(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ei(t,e="|"){return t.map(r=>Ii(r)).join(e)}function pu(t,e){return typeof e=="bigint"?e.toString():e}function Mo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function jo(t){return t==null}function No(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function de(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function mu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function pP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function fP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function mP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Hr(t){return JSON.stringify(t)}var Ri=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hu=Mo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function On(t){if(zn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(zn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function hP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var gP=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},gu=new Set(["string","number","symbol"]),Lm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ur(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function It(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function N(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function yP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ii(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function yu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var vu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Fm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return It(t,{...t._zod.def,shape:r,checks:[]})}function _P(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return It(t,{...t._zod.def,shape:r,checks:[]})}function bP(t,e){if(!On(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return mu(this,"shape",n),n},checks:[]};return It(t,r)}function wP(t,e){return It(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return mu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function xP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return It(e,{...e._zod.def,shape:o,checks:[]})}function SP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return It(e,{...e._zod.def,shape:o,checks:[]})}function Kr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function At(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Oo(t){return typeof t=="string"?t:t?.message}function gt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Oo(t.inst?._zod.def?.error?.(t))??Oo(e?.error?.(t))??Oo(r.customError?.(t))??Oo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Zm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Lo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _u(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function $P(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var lu=class{constructor(...e){}};var Um=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,pu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ai=w("$ZodError",Um),bu=w("$ZodError",Um,{Parent:Error});function qm(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Vm(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Bm=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ht;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw Ri(a,o?.callee),a}return i.value};var Wm=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw Ri(a,o?.callee),a}return i.value};var wu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ht;return s.issues.length?{success:!1,error:new(t??Ai)(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Fo=wu(bu),xu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Ci=xu(bu);var Hm=/^[cC][^\s-]{8,}$/,Km=/^[0-9a-z]+$/,Jm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gm=/^[0-9a-vA-V]{20}$/,Ym=/^[A-Za-z0-9]{27}$/,Qm=/^[a-zA-Z0-9_-]{21}$/,Xm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var eh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Su=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var th=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var PP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rh(){return new RegExp(PP,"u")}var nh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,sh=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ih=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ah=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$u=/^[A-Za-z0-9_-]*$/,ch=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var uh=/^\+(?:[0-9]){6,14}[0-9]$/,lh="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",dh=new RegExp(`^${lh}$`);function ph(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fh(t){return new RegExp(`^${ph(t)}$`)}function mh(t){let e=ph({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${lh}T(?:${n})$`)}var hh=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var gh=/^\d+$/,yh=/^-?\d+(?:\.\d+)?/i,vh=/true|false/i,_h=/null/i;var bh=/^[^A-Z]*$/,wh=/^[^a-z]*$/;var je=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),xh={number:"number",bigint:"bigint",object:"date"},Pu=w("$ZodCheckLessThan",(t,e)=>{je.init(t,e);let r=xh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Tu=w("$ZodCheckGreaterThan",(t,e)=>{je.init(t,e);let r=xh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Sh=w("$ZodCheckMultipleOf",(t,e)=>{je.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):fu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),$h=w("$ZodCheckNumberFormat",(t,e)=>{je.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=vu[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=gh)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var kh=w("$ZodCheckMaxLength",(t,e)=>{var r;je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Lo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ph=w("$ZodCheckMinLength",(t,e)=>{var r;je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Lo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Th=w("$ZodCheckLengthEquals",(t,e)=>{var r;je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Lo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Zo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;je.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Eh=w("$ZodCheckRegex",(t,e)=>{Zo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Rh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=bh),Zo.init(t,e)}),Ih=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=wh),Zo.init(t,e)}),Ah=w("$ZodCheckIncludes",(t,e)=>{je.init(t,e);let r=ur(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Ch=w("$ZodCheckStartsWith",(t,e)=>{je.init(t,e);let r=new RegExp(`^${ur(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Dh=w("$ZodCheckEndsWith",(t,e)=>{je.init(t,e);let r=new RegExp(`.*${ur(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var zh=w("$ZodCheckOverwrite",(t,e)=>{je.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Di=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
209
209
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
210
- `))}};var Ah={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=Ah;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 Wt;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 Wt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Lo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ai(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),zi=w("$ZodString",(t,e)=>{pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??lh(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)=>{Fo.init(t,e),zi.init(t,e)}),Zh=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Gm),he.init(t,e)}),Uh=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=bu(n))}else e.pattern??(e.pattern=bu());he.init(t,e)}),qh=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Jm),he.init(t,e)}),Vh=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:nh.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})}}}),Bh=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Qm()),he.init(t,e)}),Wh=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Hm),he.init(t,e)}),Hh=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Um),he.init(t,e)}),Kh=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=qm),he.init(t,e)}),Gh=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Vm),he.init(t,e)}),Jh=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Bm),he.init(t,e)}),Qh=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Wm),he.init(t,e)}),Yh=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=uh(e)),he.init(t,e)}),Xh=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ih),he.init(t,e)}),eg=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ch(e)),he.init(t,e)}),tg=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Km),he.init(t,e)}),rg=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ym),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ng=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Xm),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})}}}),og=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=eh),he.init(t,e)}),sg=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=th),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 ig(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var ag=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=rh),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{ig(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function bP(t){if(!wu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return ig(r)}var cg=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=wu),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{bP(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),ug=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=oh),he.init(t,e)});function wP(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 lg=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{wP(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Pu=w("$ZodNumber",(t,e)=>{pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??ph,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)=>{_h.init(t,e),Pu.init(t,e)}),pg=w("$ZodBoolean",(t,e)=>{pe.init(t,e),t._zod.pattern=fh,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 fg=w("$ZodNull",(t,e)=>{pe.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)=>{pe.init(t,e),t._zod.parse=r=>r}),hg=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 Ch(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}var gg=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=>Ch(u,r,i))):Ch(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Di(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}function Dh(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 yg=w("$ZodObject",(t,e)=>{pe.init(t,e);let r=Oo(()=>{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=mu(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 Ci(["shape","payload","ctx"]),f=r.value,m=x=>{let _=Hr(x);return`shape[${_}]._zod.run({ value: input[${_}], 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 _=g[x];p.write(`const ${_} = ${m(x)};`);let P=Hr(x);p.write(`
211
- if (${_}.issues.length) {
212
- if (input[${P}] === undefined) {
213
- if (${P} in input) {
214
- newResult[${P}] = undefined;
210
+ `))}};var Mh={major:4,minor:0,patch:0};var pe=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Mh;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Kr(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Ht;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Kr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Kr(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Ht;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Fo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ci(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Oi=w("$ZodString",(t,e)=>{pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??hh(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),he=w("$ZodStringFormat",(t,e)=>{Zo.init(t,e),Oi.init(t,e)}),Wh=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=eh),he.init(t,e)}),Hh=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Su(n))}else e.pattern??(e.pattern=Su());he.init(t,e)}),Kh=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=th),he.init(t,e)}),Jh=w("$ZodURL",(t,e)=>{he.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ch.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Gh=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=rh()),he.init(t,e)}),Yh=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Qm),he.init(t,e)}),Qh=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hm),he.init(t,e)}),Xh=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Km),he.init(t,e)}),eg=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Jm),he.init(t,e)}),tg=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Gm),he.init(t,e)}),rg=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ym),he.init(t,e)}),ng=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=mh(e)),he.init(t,e)}),og=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=dh),he.init(t,e)}),sg=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=fh(e)),he.init(t,e)}),ig=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Xm),he.init(t,e)}),ag=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=nh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),cg=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=oh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),ug=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=sh),he.init(t,e)}),lg=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ih),he.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function dg(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var pg=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ah),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{dg(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function TP(t){if(!$u.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return dg(r)}var fg=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=$u),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{TP(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),mg=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=uh),he.init(t,e)});function EP(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var hg=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{EP(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Ru=w("$ZodNumber",(t,e)=>{pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??yh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),gg=w("$ZodNumber",(t,e)=>{$h.init(t,e),Ru.init(t,e)}),yg=w("$ZodBoolean",(t,e)=>{pe.init(t,e),t._zod.pattern=vh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var vg=w("$ZodNull",(t,e)=>{pe.init(t,e),t._zod.pattern=_h,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var _g=w("$ZodUnknown",(t,e)=>{pe.init(t,e),t._zod.parse=r=>r}),bg=w("$ZodNever",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function jh(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}var wg=w("$ZodArray",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>jh(u,r,i))):jh(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function zi(t,e,r){t.issues.length&&e.issues.push(...At(r,t.issues)),e.value[r]=t.value}function Nh(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...At(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var xg=w("$ZodObject",(t,e)=>{pe.init(t,e);let r=Mo(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof pe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=yu(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});de(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let g of m.values)p[f].add(g)}}return p});let n=d=>{let p=new Di(["shape","payload","ctx"]),f=r.value,m=S=>{let v=Hr(S);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let S of f.keys)g[S]=`key_${y++}`;p.write("const newResult = {}");for(let S of f.keys)if(f.optionalKeys.has(S)){let v=g[S];p.write(`const ${v} = ${m(S)};`);let k=Hr(S);p.write(`
211
+ if (${v}.issues.length) {
212
+ if (input[${k}] === undefined) {
213
+ if (${k} in input) {
214
+ newResult[${k}] = undefined;
215
215
  }
216
216
  } else {
217
217
  payload.issues = payload.issues.concat(
218
- ${_}.issues.map((iss) => ({
218
+ ${v}.issues.map((iss) => ({
219
219
  ...iss,
220
- path: iss.path ? [${P}, ...iss.path] : [${P}],
220
+ path: iss.path ? [${k}, ...iss.path] : [${k}],
221
221
  }))
222
222
  );
223
223
  }
224
- } else if (${_}.value === undefined) {
225
- if (${P} in input) newResult[${P}] = undefined;
224
+ } else if (${v}.value === undefined) {
225
+ if (${k} in input) newResult[${k}] = undefined;
226
226
  } else {
227
- newResult[${P}] = ${_}.value;
227
+ newResult[${k}] = ${v}.value;
228
228
  }
229
- `)}else{let _=g[x];p.write(`const ${_} = ${m(x)};`),p.write(`
230
- if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
229
+ `)}else{let v=g[S];p.write(`const ${v} = ${m(S)};`),p.write(`
230
+ if (${v}.issues.length) payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
231
231
  ...iss,
232
- path: iss.path ? [${Hr(x)}, ...iss.path] : [${Hr(x)}]
233
- })));`),p.write(`newResult[${Hr(x)}] = ${_}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(x,_)=>v(d,x,_)},o,s=zn,i=!Pi.jitless,c=i&&pu.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 _=l.shape;for(let P of l.keys){let S=_[P],z=S._zod.run({value:f[P],issues:[]},p),O=S._zod.optin==="optional"&&S._zod.optout==="optional";z instanceof Promise?m.push(z.then(Z=>O?Dh(Z,d,P,f):Di(Z,d,P))):O?Dh(z,d,P,f):Di(z,d,P)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],y=l.keySet,v=u._zod,x=v.def.type;for(let _ of Object.keys(f)){if(y.has(_))continue;if(x==="never"){g.push(_);continue}let P=v.run({value:f[_],issues:[]},p);P instanceof Promise?m.push(P.then(S=>Di(S,d,_))):Di(P,d,_)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function zh(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 Tu=w("$ZodUnion",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),de(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>No(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>zh(i,r,t,n)):zh(s,r,t,n)}}),vg=w("$ZodDiscriminatedUnion",(t,e)=>{Tu.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=Oo(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!zn(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),_g=w("$ZodIntersection",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Oh(r,c,u)):Oh(r,s,i)}});function ku(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=ku(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=ku(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 Oh(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=ku(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 bg=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 wg=w("$ZodEnum",(t,e)=>{pe.init(t,e);let r=cu(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>fu.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}}),xg=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 Sg=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 Wt;return r.value=o,r}}),$g=w("$ZodOptional",(t,e)=>{pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${No(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),kg=w("$ZodNullable",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${No(r.source)}|null)$`):void 0}),de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Pg=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=>Mh(s,e)):Mh(o,e)}});function Mh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Tg=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))}),Eg=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=>Nh(s,t)):Nh(o,t)}});function Nh(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 Rg=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 Ig=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=>jh(s,e,n)):jh(o,e,n)}});function jh(t,e,r){return Kr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Ag=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(Lh):Lh(o)}});function Lh(t){return t.value=Object.freeze(t.value),t}var Cg=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=>Fh(s,r,n,t));Fh(o,r,n,t)}});function Fh(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(gu(o))}}var xP=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},SP=()=>{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 ${xP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ri(n.values[0])}`:`Invalid option: expected one of ${Ti(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":""}: ${Ti(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 Dg(){return{localeError:SP()}}var Eu=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 $P(){return new Eu}var Zo=$P();function zg(t,e){return new t({type:"string",...j(e)})}function Og(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Ru(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function Mg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Ng(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function jg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function Lg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function Fg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function Zg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function Ug(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function qg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function Vg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function Bg(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function Wg(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function Hg(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function Kg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function Gg(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function Jg(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function Qg(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function Yg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function Xg(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function ey(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function ty(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function ry(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function ny(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function oy(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function sy(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function iy(t,e){return new t({type:"number",checks:[],...j(e)})}function ay(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function cy(t,e){return new t({type:"boolean",...j(e)})}function uy(t,e){return new t({type:"null",...j(e)})}function ly(t){return new t({type:"unknown"})}function dy(t,e){return new t({type:"never",...j(e)})}function Oi(t,e){return new Su({check:"less_than",...j(e),value:t,inclusive:!1})}function Uo(t,e){return new Su({check:"less_than",...j(e),value:t,inclusive:!0})}function Mi(t,e){return new $u({check:"greater_than",...j(e),value:t,inclusive:!1})}function qo(t,e){return new $u({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ni(t,e){return new vh({check:"multiple_of",...j(e),value:t})}function ji(t,e){return new bh({check:"max_length",...j(e),maximum:t})}function Mn(t,e){return new wh({check:"min_length",...j(e),minimum:t})}function Li(t,e){return new xh({check:"length_equals",...j(e),length:t})}function Iu(t,e){return new Sh({check:"string_format",format:"regex",...j(e),pattern:t})}function Au(t){return new $h({check:"string_format",format:"lowercase",...j(t)})}function Cu(t){return new kh({check:"string_format",format:"uppercase",...j(t)})}function Du(t,e){return new Ph({check:"string_format",format:"includes",...j(e),includes:t})}function zu(t,e){return new Th({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Ou(t,e){return new Eh({check:"string_format",format:"ends_with",...j(e),suffix:t})}function Gr(t){return new Rh({check:"overwrite",tx:t})}function Mu(t){return Gr(e=>e.normalize(t))}function Nu(){return Gr(t=>t.trim())}function ju(){return Gr(t=>t.toLowerCase())}function Lu(){return Gr(t=>t.toUpperCase())}function py(t,e,r){return new t({type:"array",element:e,...j(r)})}function fy(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 Nn(t){return!!t._zod}function lr(t,e){return Nn(t)?Lo(t,e):t.safeParse(e)}function Fi(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 hy(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 Bo={};Be(Bo,{ZodISODate:()=>yy,ZodISODateTime:()=>gy,ZodISODuration:()=>_y,ZodISOTime:()=>vy,date:()=>Zu,datetime:()=>Fu,duration:()=>qu,time:()=>Uu});var gy=w("ZodISODateTime",(t,e)=>{Yh.init(t,e),ve.init(t,e)});function Fu(t){return ry(gy,t)}var yy=w("ZodISODate",(t,e)=>{Xh.init(t,e),ve.init(t,e)});function Zu(t){return ny(yy,t)}var vy=w("ZodISOTime",(t,e)=>{eg.init(t,e),ve.init(t,e)});function Uu(t){return oy(vy,t)}var _y=w("ZodISODuration",(t,e)=>{tg.init(t,e),ve.init(t,e)});function qu(t){return sy(_y,t)}var by=(t,e)=>{Ii.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Lm(t,r)},flatten:{value:r=>jm(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},DZ=w("ZodError",by),Wo=w("ZodError",by,{Parent:Error});var wy=Fm(Wo),xy=Zm(Wo),Sy=vu(Wo),$y=_u(Wo);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)=>wy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Sy(t,r,n),t.parseAsync=async(r,n)=>xy(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>$y(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(wT(r,n)),t.superRefine=r=>t.check(xT(r)),t.overwrite=r=>t.check(Gr(r)),t.optional=()=>xe(t),t.nullable=()=>Ty(t),t.nullish=()=>xe(Ty(t)),t.nonoptional=r=>mT(t,r),t.array=()=>Y(t),t.or=r=>fe([t,r]),t.and=r=>Ui(t,r),t.transform=r=>Bu(t,Cy(r)),t.default=r=>dT(t,r),t.prefault=r=>fT(t,r),t.catch=r=>gT(t,r),t.pipe=r=>Bu(t,r),t.readonly=()=>_T(t),t.describe=r=>{let n=t.clone();return Zo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Zo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Zo.get(t);let n=t.clone();return Zo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Ey=w("_ZodString",(t,e)=>{zi.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(Iu(...n)),t.includes=(...n)=>t.check(Du(...n)),t.startsWith=(...n)=>t.check(zu(...n)),t.endsWith=(...n)=>t.check(Ou(...n)),t.min=(...n)=>t.check(Mn(...n)),t.max=(...n)=>t.check(ji(...n)),t.length=(...n)=>t.check(Li(...n)),t.nonempty=(...n)=>t.check(Mn(1,...n)),t.lowercase=n=>t.check(Au(n)),t.uppercase=n=>t.check(Cu(n)),t.trim=()=>t.check(Nu()),t.normalize=(...n)=>t.check(Mu(...n)),t.toLowerCase=()=>t.check(ju()),t.toUpperCase=()=>t.check(Lu())}),DP=w("ZodString",(t,e)=>{zi.init(t,e),Ey.init(t,e),t.email=r=>t.check(Og(zP,r)),t.url=r=>t.check(Fg(OP,r)),t.jwt=r=>t.check(ty(JP,r)),t.emoji=r=>t.check(Zg(MP,r)),t.guid=r=>t.check(Ru(ky,r)),t.uuid=r=>t.check(Mg(Zi,r)),t.uuidv4=r=>t.check(Ng(Zi,r)),t.uuidv6=r=>t.check(jg(Zi,r)),t.uuidv7=r=>t.check(Lg(Zi,r)),t.nanoid=r=>t.check(Ug(NP,r)),t.guid=r=>t.check(Ru(ky,r)),t.cuid=r=>t.check(qg(jP,r)),t.cuid2=r=>t.check(Vg(LP,r)),t.ulid=r=>t.check(Bg(FP,r)),t.base64=r=>t.check(Yg(HP,r)),t.base64url=r=>t.check(Xg(KP,r)),t.xid=r=>t.check(Wg(ZP,r)),t.ksuid=r=>t.check(Hg(UP,r)),t.ipv4=r=>t.check(Kg(qP,r)),t.ipv6=r=>t.check(Gg(VP,r)),t.cidrv4=r=>t.check(Jg(BP,r)),t.cidrv6=r=>t.check(Qg(WP,r)),t.e164=r=>t.check(ey(GP,r)),t.datetime=r=>t.check(Fu(r)),t.date=r=>t.check(Zu(r)),t.time=r=>t.check(Uu(r)),t.duration=r=>t.check(qu(r))});function b(t){return zg(DP,t)}var ve=w("ZodStringFormat",(t,e)=>{he.init(t,e),Ey.init(t,e)}),zP=w("ZodEmail",(t,e)=>{qh.init(t,e),ve.init(t,e)});var ky=w("ZodGUID",(t,e)=>{Zh.init(t,e),ve.init(t,e)});var Zi=w("ZodUUID",(t,e)=>{Uh.init(t,e),ve.init(t,e)});var OP=w("ZodURL",(t,e)=>{Vh.init(t,e),ve.init(t,e)});var MP=w("ZodEmoji",(t,e)=>{Bh.init(t,e),ve.init(t,e)});var NP=w("ZodNanoID",(t,e)=>{Wh.init(t,e),ve.init(t,e)});var jP=w("ZodCUID",(t,e)=>{Hh.init(t,e),ve.init(t,e)});var LP=w("ZodCUID2",(t,e)=>{Kh.init(t,e),ve.init(t,e)});var FP=w("ZodULID",(t,e)=>{Gh.init(t,e),ve.init(t,e)});var ZP=w("ZodXID",(t,e)=>{Jh.init(t,e),ve.init(t,e)});var UP=w("ZodKSUID",(t,e)=>{Qh.init(t,e),ve.init(t,e)});var qP=w("ZodIPv4",(t,e)=>{rg.init(t,e),ve.init(t,e)});var VP=w("ZodIPv6",(t,e)=>{ng.init(t,e),ve.init(t,e)});var BP=w("ZodCIDRv4",(t,e)=>{og.init(t,e),ve.init(t,e)});var WP=w("ZodCIDRv6",(t,e)=>{sg.init(t,e),ve.init(t,e)});var HP=w("ZodBase64",(t,e)=>{ag.init(t,e),ve.init(t,e)});var KP=w("ZodBase64URL",(t,e)=>{cg.init(t,e),ve.init(t,e)});var GP=w("ZodE164",(t,e)=>{ug.init(t,e),ve.init(t,e)});var JP=w("ZodJWT",(t,e)=>{lg.init(t,e),ve.init(t,e)});var Ry=w("ZodNumber",(t,e)=>{Pu.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(Mi(n,o)),t.gte=(n,o)=>t.check(qo(n,o)),t.min=(n,o)=>t.check(qo(n,o)),t.lt=(n,o)=>t.check(Oi(n,o)),t.lte=(n,o)=>t.check(Uo(n,o)),t.max=(n,o)=>t.check(Uo(n,o)),t.int=n=>t.check(Py(n)),t.safe=n=>t.check(Py(n)),t.positive=n=>t.check(Mi(0,n)),t.nonnegative=n=>t.check(qo(0,n)),t.negative=n=>t.check(Oi(0,n)),t.nonpositive=n=>t.check(Uo(0,n)),t.multipleOf=(n,o)=>t.check(Ni(n,o)),t.step=(n,o)=>t.check(Ni(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ae(t){return iy(Ry,t)}var QP=w("ZodNumberFormat",(t,e)=>{dg.init(t,e),Ry.init(t,e)});function Py(t){return ay(QP,t)}var YP=w("ZodBoolean",(t,e)=>{pg.init(t,e),Se.init(t,e)});function Pe(t){return cy(YP,t)}var XP=w("ZodNull",(t,e)=>{fg.init(t,e),Se.init(t,e)});function Wu(t){return uy(XP,t)}var eT=w("ZodUnknown",(t,e)=>{mg.init(t,e),Se.init(t,e)});function _e(){return ly(eT)}var tT=w("ZodNever",(t,e)=>{hg.init(t,e),Se.init(t,e)});function rT(t){return dy(tT,t)}var nT=w("ZodArray",(t,e)=>{gg.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(ji(r,n)),t.length=(r,n)=>t.check(Li(r,n)),t.unwrap=()=>t.element});function Y(t,e){return py(nT,t,e)}var Iy=w("ZodObject",(t,e)=>{yg.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:rT()}),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(Dy,t,r[0]),t.required=(...r)=>ie.required(zy,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 Iy(r)}function Ze(t,e){return new Iy({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ie.normalizeParams(e)})}var Ay=w("ZodUnion",(t,e)=>{Tu.init(t,e),Se.init(t,e),t.options=e.options});function fe(t,e){return new Ay({type:"union",options:t,...ie.normalizeParams(e)})}var oT=w("ZodDiscriminatedUnion",(t,e)=>{Ay.init(t,e),vg.init(t,e)});function Hu(t,e,r){return new oT({type:"union",options:e,discriminator:t,...ie.normalizeParams(r)})}var sT=w("ZodIntersection",(t,e)=>{_g.init(t,e),Se.init(t,e)});function Ui(t,e){return new sT({type:"intersection",left:t,right:e})}var iT=w("ZodRecord",(t,e)=>{bg.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new iT({type:"record",keyType:t,valueType:e,...ie.normalizeParams(r)})}var Vu=w("ZodEnum",(t,e)=>{wg.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 Vu({...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 Vu({...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 Vu({type:"enum",entries:r,...ie.normalizeParams(e)})}var aT=w("ZodLiteral",(t,e)=>{xg.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 aT({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var cT=w("ZodTransform",(t,e)=>{Sg.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 Cy(t){return new cT({type:"transform",transform:t})}var Dy=w("ZodOptional",(t,e)=>{$g.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new Dy({type:"optional",innerType:t})}var uT=w("ZodNullable",(t,e)=>{kg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ty(t){return new uT({type:"nullable",innerType:t})}var lT=w("ZodDefault",(t,e)=>{Pg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function dT(t,e){return new lT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var pT=w("ZodPrefault",(t,e)=>{Tg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function fT(t,e){return new pT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var zy=w("ZodNonOptional",(t,e)=>{Eg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function mT(t,e){return new zy({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var hT=w("ZodCatch",(t,e)=>{Rg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function gT(t,e){return new hT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var yT=w("ZodPipe",(t,e)=>{Ig.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function Bu(t,e){return new yT({type:"pipe",in:t,out:e})}var vT=w("ZodReadonly",(t,e)=>{Ag.init(t,e),Se.init(t,e)});function _T(t){return new vT({type:"readonly",innerType:t})}var Oy=w("ZodCustom",(t,e)=>{Cg.init(t,e),Se.init(t,e)});function bT(t){let e=new Ne({check:"custom"});return e._zod.check=t,e}function My(t,e){return fy(Oy,t??(()=>!0),e)}function wT(t,e={}){return my(Oy,t,e)}function xT(t){let e=bT(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 Ku(t,e){return Bu(Cy(t),e)}at(Dg());var Ju="2025-11-25";var Ny=[Ju,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],dr="io.modelcontextprotocol/related-task",Vi="2.0",Ee=My(t=>t!==null&&(typeof t=="object"||typeof t=="function")),jy=fe([b(),ae().int()]),Ly=b(),PU=Ze({ttl:fe([ae(),Wu()]).optional(),pollInterval:ae().optional()}),ST=I({ttl:ae().optional()}),$T=I({taskId:b()}),Qu=Ze({progressToken:jy.optional(),[dr]:$T.optional()}),nt=I({_meta:Qu.optional()}),Ho=nt.extend({task:ST.optional()}),Fy=t=>Ho.safeParse(t).success,Re=I({method:b(),params:nt.loose().optional()}),ct=I({_meta:Qu.optional()}),ut=I({method:b(),params:ct.loose().optional()}),Ie=Ze({_meta:Qu.optional()}),Bi=fe([b(),ae().int()]),Zy=I({jsonrpc:C(Vi),id:Bi,...Re.shape}).strict(),Yu=t=>Zy.safeParse(t).success,Uy=I({jsonrpc:C(Vi),...ut.shape}).strict(),qy=t=>Uy.safeParse(t).success,Xu=I({jsonrpc:C(Vi),id:Bi,result:Ie}).strict(),Ko=t=>Xu.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 el=I({jsonrpc:C(Vi),id:Bi.optional(),error:I({code:ae().int(),message:b(),data:_e().optional()})}).strict();var Vy=t=>el.safeParse(t).success;var By=fe([Zy,Uy,Xu,el]),TU=fe([Xu,el]),Wi=Ie.strict(),kT=ct.extend({requestId:Bi.optional(),reason:b().optional()}),Hi=ut.extend({method:C("notifications/cancelled"),params:kT}),PT=I({src:b(),mimeType:b().optional(),sizes:Y(b()).optional(),theme:Je(["light","dark"]).optional()}),Go=I({icons:Y(PT).optional()}),jn=I({name:b(),title:b().optional()}),Wy=jn.extend({...jn.shape,...Go.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),TT=Ui(I({applyDefaults:Pe().optional()}),be(b(),_e())),ET=Ku(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ui(I({form:TT.optional(),url:Ee.optional()}),be(b(),_e()).optional())),RT=Ze({list:Ee.optional(),cancel:Ee.optional(),requests:Ze({sampling:Ze({createMessage:Ee.optional()}).optional(),elicitation:Ze({create:Ee.optional()}).optional()}).optional()}),IT=Ze({list:Ee.optional(),cancel:Ee.optional(),requests:Ze({tools:Ze({call:Ee.optional()}).optional()}).optional()}),AT=I({experimental:be(b(),Ee).optional(),sampling:I({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:ET.optional(),roots:I({listChanged:Pe().optional()}).optional(),tasks:RT.optional()}),CT=nt.extend({protocolVersion:b(),capabilities:AT,clientInfo:Wy}),tl=Re.extend({method:C("initialize"),params:CT});var DT=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:IT.optional()}),zT=Ie.extend({protocolVersion:b(),capabilities:DT,serverInfo:Wy,instructions:b().optional()}),rl=ut.extend({method:C("notifications/initialized"),params:ct.optional()});var Ki=Re.extend({method:C("ping"),params:nt.optional()}),OT=I({progress:ae(),total:xe(ae()),message:xe(b())}),MT=I({...ct.shape,...OT.shape,progressToken:jy}),Gi=ut.extend({method:C("notifications/progress"),params:MT}),NT=nt.extend({cursor:Ly.optional()}),Jo=Re.extend({params:NT.optional()}),Qo=Ie.extend({nextCursor:Ly.optional()}),jT=Je(["working","input_required","completed","failed","cancelled"]),Yo=I({taskId:b(),status:jT,ttl:fe([ae(),Wu()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ae()),statusMessage:xe(b())}),Ln=Ie.extend({task:Yo}),LT=ct.merge(Yo),Xo=ut.extend({method:C("notifications/tasks/status"),params:LT}),Ji=Re.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Qi=Ie.merge(Yo),Yi=Re.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),EU=Ie.loose(),Xi=Jo.extend({method:C("tasks/list")}),ea=Qo.extend({tasks:Y(Yo)}),ta=Re.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),Hy=Ie.merge(Yo),Ky=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),Gy=Ky.extend({text:b()}),nl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Jy=Ky.extend({blob:nl}),es=Je(["user","assistant"]),Fn=I({audience:Y(es).optional(),priority:ae().min(0).max(1).optional(),lastModified:Bo.datetime({offset:!0}).optional()}),Qy=I({...jn.shape,...Go.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(Ze({}))}),FT=I({...jn.shape,...Go.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(Ze({}))}),ZT=Jo.extend({method:C("resources/list")}),UT=Qo.extend({resources:Y(Qy)}),qT=Jo.extend({method:C("resources/templates/list")}),VT=Qo.extend({resourceTemplates:Y(FT)}),ol=nt.extend({uri:b()}),BT=ol,WT=Re.extend({method:C("resources/read"),params:BT}),HT=Ie.extend({contents:Y(fe([Gy,Jy]))}),KT=ut.extend({method:C("notifications/resources/list_changed"),params:ct.optional()}),GT=ol,JT=Re.extend({method:C("resources/subscribe"),params:GT}),QT=ol,YT=Re.extend({method:C("resources/unsubscribe"),params:QT}),XT=ct.extend({uri:b()}),eE=ut.extend({method:C("notifications/resources/updated"),params:XT}),tE=I({name:b(),description:xe(b()),required:xe(Pe())}),rE=I({...jn.shape,...Go.shape,description:xe(b()),arguments:xe(Y(tE)),_meta:xe(Ze({}))}),nE=Jo.extend({method:C("prompts/list")}),oE=Qo.extend({prompts:Y(rE)}),sE=nt.extend({name:b(),arguments:be(b(),b()).optional()}),iE=Re.extend({method:C("prompts/get"),params:sE}),sl=I({type:C("text"),text:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),il=I({type:C("image"),data:nl,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),al=I({type:C("audio"),data:nl,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),aE=I({type:C("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),cE=I({type:C("resource"),resource:fe([Gy,Jy]),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),uE=Qy.extend({type:C("resource_link")}),cl=fe([sl,il,al,uE,cE]),lE=I({role:es,content:cl}),dE=Ie.extend({description:b().optional(),messages:Y(lE)}),pE=ut.extend({method:C("notifications/prompts/list_changed"),params:ct.optional()}),fE=I({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),mE=I({taskSupport:Je(["required","optional","forbidden"]).optional()}),Yy=I({...jn.shape,...Go.shape,description:b().optional(),inputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Y(b()).optional()}).catchall(_e()),outputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Y(b()).optional()}).catchall(_e()).optional(),annotations:fE.optional(),execution:mE.optional(),_meta:be(b(),_e()).optional()}),ul=Jo.extend({method:C("tools/list")}),hE=Qo.extend({tools:Y(Yy)}),ra=Ie.extend({content:Y(cl).default([]),structuredContent:be(b(),_e()).optional(),isError:Pe().optional()}),RU=ra.or(Ie.extend({toolResult:_e()})),gE=Ho.extend({name:b(),arguments:be(b(),_e()).optional()}),ts=Re.extend({method:C("tools/call"),params:gE}),yE=ut.extend({method:C("notifications/tools/list_changed"),params:ct.optional()}),IU=I({autoRefresh:Pe().default(!0),debounceMs:ae().int().nonnegative().default(300)}),rs=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),vE=nt.extend({level:rs}),ll=Re.extend({method:C("logging/setLevel"),params:vE}),_E=ct.extend({level:rs,logger:b().optional(),data:_e()}),bE=ut.extend({method:C("notifications/message"),params:_E}),wE=I({name:b().optional()}),xE=I({hints:Y(wE).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),SE=I({mode:Je(["auto","required","none"]).optional()}),$E=I({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Y(cl).default([]),structuredContent:I({}).loose().optional(),isError:Pe().optional(),_meta:be(b(),_e()).optional()}),kE=Hu("type",[sl,il,al]),qi=Hu("type",[sl,il,al,aE,$E]),PE=I({role:es,content:fe([qi,Y(qi)]),_meta:be(b(),_e()).optional()}),TE=Ho.extend({messages:Y(PE),modelPreferences:xE.optional(),systemPrompt:b().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:Y(b()).optional(),metadata:Ee.optional(),tools:Y(Yy).optional(),toolChoice:SE.optional()}),EE=Re.extend({method:C("sampling/createMessage"),params:TE}),dl=Ie.extend({model:b(),stopReason:xe(Je(["endTurn","stopSequence","maxTokens"]).or(b())),role:es,content:kE}),pl=Ie.extend({model:b(),stopReason:xe(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:es,content:fe([qi,Y(qi)])}),RE=I({type:C("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),IE=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()}),AE=I({type:Je(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),CE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),default:b().optional()}),DE=I({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Y(I({const:b(),title:b()})),default:b().optional()}),zE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),enumNames:Y(b()).optional(),default:b().optional()}),OE=fe([CE,DE]),ME=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({type:C("string"),enum:Y(b())}),default:Y(b()).optional()}),NE=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({anyOf:Y(I({const:b(),title:b()}))}),default:Y(b()).optional()}),jE=fe([ME,NE]),LE=fe([zE,OE,jE]),FE=fe([LE,RE,IE,AE]),ZE=Ho.extend({mode:C("form").optional(),message:b(),requestedSchema:I({type:C("object"),properties:be(b(),FE),required:Y(b()).optional()})}),UE=Ho.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),qE=fe([ZE,UE]),VE=Re.extend({method:C("elicitation/create"),params:qE}),BE=ct.extend({elicitationId:b()}),WE=ut.extend({method:C("notifications/elicitation/complete"),params:BE}),na=Ie.extend({action:Je(["accept","decline","cancel"]),content:Ku(t=>t===null?void 0:t,be(b(),fe([b(),ae(),Pe(),Y(b())])).optional())}),HE=I({type:C("ref/resource"),uri:b()});var KE=I({type:C("ref/prompt"),name:b()}),GE=nt.extend({ref:fe([KE,HE]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),JE=Re.extend({method:C("completion/complete"),params:GE});var QE=Ie.extend({completion:Ze({values:Y(b()).max(100),total:xe(ae().int()),hasMore:xe(Pe())})}),YE=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),XE=Re.extend({method:C("roots/list"),params:nt.optional()}),fl=Ie.extend({roots:Y(YE)}),eR=ut.extend({method:C("notifications/roots/list_changed"),params:ct.optional()}),AU=fe([Ki,tl,JE,ll,iE,nE,ZT,qT,WT,JT,YT,ts,ul,Ji,Yi,Xi,ta]),CU=fe([Hi,Gi,rl,eR,Xo]),DU=fe([Wi,dl,pl,na,fl,Qi,ea,Ln]),zU=fe([Ki,EE,VE,XE,Ji,Yi,Xi,ta]),OU=fe([Hi,Gi,bE,eE,KT,yE,pE,Xo,WE]),MU=fe([Wi,zT,QE,dE,oE,UT,VT,HT,ra,hE,Qi,ea,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 Gu(o.elicitations,r)}return new t(e,r,n)}},Gu=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 ev=Symbol("Let zodToJsonSchema decide on which parser to use");var Xy={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"},tv=t=>typeof t=="string"?{...Xy,name:t}:{...Xy,...t};var rv=t=>{let e=tv(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 ml(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,ml(t,e,n,o)}var oa=(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"?oa(e,t.currentPath):e.join("/")}}function nv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==k.ZodAny&&(r.items=L(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function ov(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 sv(){return{type:"boolean"}}function sa(t,e){return L(t.type._def,e)}var iv=(t,e)=>L(t.innerType._def,e);function hl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>hl(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 tR(t,e)}}var tR=(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 av(t,e){return{...L(t.innerType._def,e),default:t.defaultValue()}}function cv(t,e){return e.effectStrategy==="input"?L(t.schema._def,e):we(e)}function uv(t){return{type:"string",enum:Array.from(t.values)}}var rR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function lv(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(rR(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 gl,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:()=>(gl===void 0&&(gl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gl),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 ia(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":Ue(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":Ue(r,n.regex,n.message,e);break;case"cuid":Ue(r,yt.cuid,n.message,e);break;case"cuid2":Ue(r,yt.cuid2,n.message,e);break;case"startsWith":Ue(r,RegExp(`^${yl(n.value,e)}`),n.message,e);break;case"endsWith":Ue(r,RegExp(`${yl(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":{Ue(r,RegExp(yl(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":Ue(r,yt.base64url,n.message,e);break;case"jwt":Ue(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ue(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ue(r,yt.ipv6Cidr,n.message,e);break}case"emoji":Ue(r,yt.emoji(),n.message,e);break;case"ulid":{Ue(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":{Ue(r,yt.base64,n.message,e);break}}break}case"nanoid":Ue(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function yl(t,e){return e.patternStrategy==="escape"?oR(t):t}var nR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function oR(t){let e="";for(let r=0;r<t.length;r++)nR.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 Ue(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:pv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",pv(e,n),r,n)}function pv(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
232
+ path: iss.path ? [${Hr(S)}, ...iss.path] : [${Hr(S)}]
233
+ })));`),p.write(`newResult[${Hr(S)}] = ${v}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(S,v)=>_(d,S,v)},o,s=zn,i=!Ti.jitless,c=i&&hu.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let v=l.shape;for(let k of l.keys){let x=v[k],z=x._zod.run({value:f[k],issues:[]},p),O=x._zod.optin==="optional"&&x._zod.optout==="optional";z instanceof Promise?m.push(z.then(Z=>O?Nh(Z,d,k,f):zi(Z,d,k))):O?Nh(z,d,k,f):zi(z,d,k)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],y=l.keySet,_=u._zod,S=_.def.type;for(let v of Object.keys(f)){if(y.has(v))continue;if(S==="never"){g.push(v);continue}let k=_.run({value:f[v],issues:[]},p);k instanceof Promise?m.push(k.then(x=>zi(x,d,v))):zi(k,d,v)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function Lh(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>gt(s,n,at())))}),e}var Iu=w("$ZodUnion",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),de(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>No(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Lh(i,r,t,n)):Lh(s,r,t,n)}}),Sg=w("$ZodDiscriminatedUnion",(t,e)=>{Iu.init(t,e);let r=t._zod.parse;de(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Mo(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!zn(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),$g=w("$ZodIntersection",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Fh(r,c,u)):Fh(r,s,i)}});function Eu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(On(t)&&On(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Eu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Eu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Fh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Kr(t))return t;let n=Eu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var kg=w("$ZodRecord",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!On(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...At(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...At(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>gt(u,n,at())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...At(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...At(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Pg=w("$ZodEnum",(t,e)=>{pe.init(t,e);let r=du(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>gu.has(typeof n)).map(n=>typeof n=="string"?ur(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Tg=w("$ZodLiteral",(t,e)=>{pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ur(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Eg=w("$ZodTransform",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ht;return r.value=o,r}}),Rg=w("$ZodOptional",(t,e)=>{pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${No(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Ig=w("$ZodNullable",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${No(r.source)}|null)$`):void 0}),de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Ag=w("$ZodDefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Zh(s,e)):Zh(o,e)}});function Zh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Cg=w("$ZodPrefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Dg=w("$ZodNonOptional",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Uh(s,t)):Uh(o,t)}});function Uh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var zg=w("$ZodCatch",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>gt(i,n,at()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gt(s,n,at()))},input:r.value}),r.issues=[]),r)}});var Og=w("$ZodPipe",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>e.in._zod.values),de(t._zod,"optin",()=>e.in._zod.optin),de(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>qh(s,e,n)):qh(o,e,n)}});function qh(t,e,r){return Kr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Mg=w("$ZodReadonly",(t,e)=>{pe.init(t,e),de(t._zod,"propValues",()=>e.innerType._zod.propValues),de(t._zod,"values",()=>e.innerType._zod.values),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Vh):Vh(o)}});function Vh(t){return t.value=Object.freeze(t.value),t}var jg=w("$ZodCustom",(t,e)=>{je.init(t,e),pe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Bh(s,r,n,t));Bh(o,r,n,t)}});function Bh(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(_u(o))}}var RP=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},IP=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${RP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ii(n.values[0])}`:`Invalid option: expected one of ${Ei(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ei(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Ng(){return{localeError:IP()}}var Au=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function AP(){return new Au}var Uo=AP();function Lg(t,e){return new t({type:"string",...N(e)})}function Fg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function Cu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function Zg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function Ug(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function qg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function Vg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function Bg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function Wg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function Hg(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function Kg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function Jg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function Gg(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function Yg(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function Qg(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function Xg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function ey(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function ty(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function ry(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function ny(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function oy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function sy(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function iy(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}function ay(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function cy(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function uy(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function ly(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function dy(t,e){return new t({type:"number",checks:[],...N(e)})}function py(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function fy(t,e){return new t({type:"boolean",...N(e)})}function my(t,e){return new t({type:"null",...N(e)})}function hy(t){return new t({type:"unknown"})}function gy(t,e){return new t({type:"never",...N(e)})}function Mi(t,e){return new Pu({check:"less_than",...N(e),value:t,inclusive:!1})}function qo(t,e){return new Pu({check:"less_than",...N(e),value:t,inclusive:!0})}function ji(t,e){return new Tu({check:"greater_than",...N(e),value:t,inclusive:!1})}function Vo(t,e){return new Tu({check:"greater_than",...N(e),value:t,inclusive:!0})}function Ni(t,e){return new Sh({check:"multiple_of",...N(e),value:t})}function Li(t,e){return new kh({check:"max_length",...N(e),maximum:t})}function Mn(t,e){return new Ph({check:"min_length",...N(e),minimum:t})}function Fi(t,e){return new Th({check:"length_equals",...N(e),length:t})}function Du(t,e){return new Eh({check:"string_format",format:"regex",...N(e),pattern:t})}function zu(t){return new Rh({check:"string_format",format:"lowercase",...N(t)})}function Ou(t){return new Ih({check:"string_format",format:"uppercase",...N(t)})}function Mu(t,e){return new Ah({check:"string_format",format:"includes",...N(e),includes:t})}function ju(t,e){return new Ch({check:"string_format",format:"starts_with",...N(e),prefix:t})}function Nu(t,e){return new Dh({check:"string_format",format:"ends_with",...N(e),suffix:t})}function Jr(t){return new zh({check:"overwrite",tx:t})}function Lu(t){return Jr(e=>e.normalize(t))}function Fu(){return Jr(t=>t.trim())}function Zu(){return Jr(t=>t.toLowerCase())}function Uu(){return Jr(t=>t.toUpperCase())}function yy(t,e,r){return new t({type:"array",element:e,...N(r)})}function vy(t,e,r){let n=N(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function _y(t,e,r){return new t({type:"custom",check:"custom",fn:e,...N(r)})}function jn(t){return!!t._zod}function lr(t,e){return jn(t)?Fo(t,e):t.safeParse(e)}function Zi(t){if(!t)return;let e;if(jn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function by(t){if(jn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Wo={};Ze(Wo,{ZodISODate:()=>xy,ZodISODateTime:()=>wy,ZodISODuration:()=>$y,ZodISOTime:()=>Sy,date:()=>Vu,datetime:()=>qu,duration:()=>Wu,time:()=>Bu});var wy=w("ZodISODateTime",(t,e)=>{ng.init(t,e),ve.init(t,e)});function qu(t){return ay(wy,t)}var xy=w("ZodISODate",(t,e)=>{og.init(t,e),ve.init(t,e)});function Vu(t){return cy(xy,t)}var Sy=w("ZodISOTime",(t,e)=>{sg.init(t,e),ve.init(t,e)});function Bu(t){return uy(Sy,t)}var $y=w("ZodISODuration",(t,e)=>{ig.init(t,e),ve.init(t,e)});function Wu(t){return ly($y,t)}var ky=(t,e)=>{Ai.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Vm(t,r)},flatten:{value:r=>qm(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},oU=w("ZodError",ky),Ho=w("ZodError",ky,{Parent:Error});var Py=Bm(Ho),Ty=Wm(Ho),Ey=wu(Ho),Ry=xu(Ho);var Se=w("ZodType",(t,e)=>(pe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>It(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Py(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ey(t,r,n),t.parseAsync=async(r,n)=>Ty(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ry(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(ET(r,n)),t.superRefine=r=>t.check(RT(r)),t.overwrite=r=>t.check(Jr(r)),t.optional=()=>xe(t),t.nullable=()=>Cy(t),t.nullish=()=>xe(Cy(t)),t.nonoptional=r=>wT(t,r),t.array=()=>Q(t),t.or=r=>fe([t,r]),t.and=r=>qi(t,r),t.transform=r=>Ku(t,jy(r)),t.default=r=>vT(t,r),t.prefault=r=>bT(t,r),t.catch=r=>ST(t,r),t.pipe=r=>Ku(t,r),t.readonly=()=>PT(t),t.describe=r=>{let n=t.clone();return Uo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Uo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Uo.get(t);let n=t.clone();return Uo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Dy=w("_ZodString",(t,e)=>{Oi.init(t,e),Se.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Du(...n)),t.includes=(...n)=>t.check(Mu(...n)),t.startsWith=(...n)=>t.check(ju(...n)),t.endsWith=(...n)=>t.check(Nu(...n)),t.min=(...n)=>t.check(Mn(...n)),t.max=(...n)=>t.check(Li(...n)),t.length=(...n)=>t.check(Fi(...n)),t.nonempty=(...n)=>t.check(Mn(1,...n)),t.lowercase=n=>t.check(zu(n)),t.uppercase=n=>t.check(Ou(n)),t.trim=()=>t.check(Fu()),t.normalize=(...n)=>t.check(Lu(...n)),t.toLowerCase=()=>t.check(Zu()),t.toUpperCase=()=>t.check(Uu())}),FP=w("ZodString",(t,e)=>{Oi.init(t,e),Dy.init(t,e),t.email=r=>t.check(Fg(ZP,r)),t.url=r=>t.check(Bg(UP,r)),t.jwt=r=>t.check(iy(nT,r)),t.emoji=r=>t.check(Wg(qP,r)),t.guid=r=>t.check(Cu(Iy,r)),t.uuid=r=>t.check(Zg(Ui,r)),t.uuidv4=r=>t.check(Ug(Ui,r)),t.uuidv6=r=>t.check(qg(Ui,r)),t.uuidv7=r=>t.check(Vg(Ui,r)),t.nanoid=r=>t.check(Hg(VP,r)),t.guid=r=>t.check(Cu(Iy,r)),t.cuid=r=>t.check(Kg(BP,r)),t.cuid2=r=>t.check(Jg(WP,r)),t.ulid=r=>t.check(Gg(HP,r)),t.base64=r=>t.check(ny(eT,r)),t.base64url=r=>t.check(oy(tT,r)),t.xid=r=>t.check(Yg(KP,r)),t.ksuid=r=>t.check(Qg(JP,r)),t.ipv4=r=>t.check(Xg(GP,r)),t.ipv6=r=>t.check(ey(YP,r)),t.cidrv4=r=>t.check(ty(QP,r)),t.cidrv6=r=>t.check(ry(XP,r)),t.e164=r=>t.check(sy(rT,r)),t.datetime=r=>t.check(qu(r)),t.date=r=>t.check(Vu(r)),t.time=r=>t.check(Bu(r)),t.duration=r=>t.check(Wu(r))});function b(t){return Lg(FP,t)}var ve=w("ZodStringFormat",(t,e)=>{he.init(t,e),Dy.init(t,e)}),ZP=w("ZodEmail",(t,e)=>{Kh.init(t,e),ve.init(t,e)});var Iy=w("ZodGUID",(t,e)=>{Wh.init(t,e),ve.init(t,e)});var Ui=w("ZodUUID",(t,e)=>{Hh.init(t,e),ve.init(t,e)});var UP=w("ZodURL",(t,e)=>{Jh.init(t,e),ve.init(t,e)});var qP=w("ZodEmoji",(t,e)=>{Gh.init(t,e),ve.init(t,e)});var VP=w("ZodNanoID",(t,e)=>{Yh.init(t,e),ve.init(t,e)});var BP=w("ZodCUID",(t,e)=>{Qh.init(t,e),ve.init(t,e)});var WP=w("ZodCUID2",(t,e)=>{Xh.init(t,e),ve.init(t,e)});var HP=w("ZodULID",(t,e)=>{eg.init(t,e),ve.init(t,e)});var KP=w("ZodXID",(t,e)=>{tg.init(t,e),ve.init(t,e)});var JP=w("ZodKSUID",(t,e)=>{rg.init(t,e),ve.init(t,e)});var GP=w("ZodIPv4",(t,e)=>{ag.init(t,e),ve.init(t,e)});var YP=w("ZodIPv6",(t,e)=>{cg.init(t,e),ve.init(t,e)});var QP=w("ZodCIDRv4",(t,e)=>{ug.init(t,e),ve.init(t,e)});var XP=w("ZodCIDRv6",(t,e)=>{lg.init(t,e),ve.init(t,e)});var eT=w("ZodBase64",(t,e)=>{pg.init(t,e),ve.init(t,e)});var tT=w("ZodBase64URL",(t,e)=>{fg.init(t,e),ve.init(t,e)});var rT=w("ZodE164",(t,e)=>{mg.init(t,e),ve.init(t,e)});var nT=w("ZodJWT",(t,e)=>{hg.init(t,e),ve.init(t,e)});var zy=w("ZodNumber",(t,e)=>{Ru.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(ji(n,o)),t.gte=(n,o)=>t.check(Vo(n,o)),t.min=(n,o)=>t.check(Vo(n,o)),t.lt=(n,o)=>t.check(Mi(n,o)),t.lte=(n,o)=>t.check(qo(n,o)),t.max=(n,o)=>t.check(qo(n,o)),t.int=n=>t.check(Ay(n)),t.safe=n=>t.check(Ay(n)),t.positive=n=>t.check(ji(0,n)),t.nonnegative=n=>t.check(Vo(0,n)),t.negative=n=>t.check(Mi(0,n)),t.nonpositive=n=>t.check(qo(0,n)),t.multipleOf=(n,o)=>t.check(Ni(n,o)),t.step=(n,o)=>t.check(Ni(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ae(t){return dy(zy,t)}var oT=w("ZodNumberFormat",(t,e)=>{gg.init(t,e),zy.init(t,e)});function Ay(t){return py(oT,t)}var sT=w("ZodBoolean",(t,e)=>{yg.init(t,e),Se.init(t,e)});function Pe(t){return fy(sT,t)}var iT=w("ZodNull",(t,e)=>{vg.init(t,e),Se.init(t,e)});function Ju(t){return my(iT,t)}var aT=w("ZodUnknown",(t,e)=>{_g.init(t,e),Se.init(t,e)});function _e(){return hy(aT)}var cT=w("ZodNever",(t,e)=>{bg.init(t,e),Se.init(t,e)});function uT(t){return gy(cT,t)}var lT=w("ZodArray",(t,e)=>{wg.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Mn(r,n)),t.nonempty=r=>t.check(Mn(1,r)),t.max=(r,n)=>t.check(Li(r,n)),t.length=(r,n)=>t.check(Fi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return yy(lT,t,e)}var Oy=w("ZodObject",(t,e)=>{xg.init(t,e),Se.init(t,e),ie.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ge(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:_e()}),t.loose=()=>t.clone({...t._zod.def,catchall:_e()}),t.strict=()=>t.clone({...t._zod.def,catchall:uT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ie.extend(t,r),t.merge=r=>ie.merge(t,r),t.pick=r=>ie.pick(t,r),t.omit=r=>ie.omit(t,r),t.partial=(...r)=>ie.partial(Ny,t,r[0]),t.required=(...r)=>ie.required(Ly,t,r[0])});function I(t,e){let r={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new Oy(r)}function qe(t,e){return new Oy({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ie.normalizeParams(e)})}var My=w("ZodUnion",(t,e)=>{Iu.init(t,e),Se.init(t,e),t.options=e.options});function fe(t,e){return new My({type:"union",options:t,...ie.normalizeParams(e)})}var dT=w("ZodDiscriminatedUnion",(t,e)=>{My.init(t,e),Sg.init(t,e)});function Gu(t,e,r){return new dT({type:"union",options:e,discriminator:t,...ie.normalizeParams(r)})}var pT=w("ZodIntersection",(t,e)=>{$g.init(t,e),Se.init(t,e)});function qi(t,e){return new pT({type:"intersection",left:t,right:e})}var fT=w("ZodRecord",(t,e)=>{kg.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new fT({type:"record",keyType:t,valueType:e,...ie.normalizeParams(r)})}var Hu=w("ZodEnum",(t,e)=>{Pg.init(t,e),Se.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Hu({...e,checks:[],...ie.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Hu({...e,checks:[],...ie.normalizeParams(o),entries:s})}});function Ge(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Hu({type:"enum",entries:r,...ie.normalizeParams(e)})}var mT=w("ZodLiteral",(t,e)=>{Tg.init(t,e),Se.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function C(t,e){return new mT({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var hT=w("ZodTransform",(t,e)=>{Eg.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ie.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ie.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function jy(t){return new hT({type:"transform",transform:t})}var Ny=w("ZodOptional",(t,e)=>{Rg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new Ny({type:"optional",innerType:t})}var gT=w("ZodNullable",(t,e)=>{Ig.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Cy(t){return new gT({type:"nullable",innerType:t})}var yT=w("ZodDefault",(t,e)=>{Ag.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function vT(t,e){return new yT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var _T=w("ZodPrefault",(t,e)=>{Cg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bT(t,e){return new _T({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Ly=w("ZodNonOptional",(t,e)=>{Dg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function wT(t,e){return new Ly({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var xT=w("ZodCatch",(t,e)=>{zg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function ST(t,e){return new xT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var $T=w("ZodPipe",(t,e)=>{Og.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function Ku(t,e){return new $T({type:"pipe",in:t,out:e})}var kT=w("ZodReadonly",(t,e)=>{Mg.init(t,e),Se.init(t,e)});function PT(t){return new kT({type:"readonly",innerType:t})}var Fy=w("ZodCustom",(t,e)=>{jg.init(t,e),Se.init(t,e)});function TT(t){let e=new je({check:"custom"});return e._zod.check=t,e}function Zy(t,e){return vy(Fy,t??(()=>!0),e)}function ET(t,e={}){return _y(Fy,t,e)}function RT(t){let e=TT(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ie.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ie.issue(o))}},t(r.value,r)));return e}function Yu(t,e){return Ku(jy(t),e)}at(Ng());var Xu="2025-11-25";var Uy=[Xu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],dr="io.modelcontextprotocol/related-task",Bi="2.0",Ee=Zy(t=>t!==null&&(typeof t=="object"||typeof t=="function")),qy=fe([b(),ae().int()]),Vy=b(),YU=qe({ttl:fe([ae(),Ju()]).optional(),pollInterval:ae().optional()}),IT=I({ttl:ae().optional()}),AT=I({taskId:b()}),el=qe({progressToken:qy.optional(),[dr]:AT.optional()}),nt=I({_meta:el.optional()}),Ko=nt.extend({task:IT.optional()}),By=t=>Ko.safeParse(t).success,Re=I({method:b(),params:nt.loose().optional()}),ct=I({_meta:el.optional()}),ut=I({method:b(),params:ct.loose().optional()}),Ie=qe({_meta:el.optional()}),Wi=fe([b(),ae().int()]),Wy=I({jsonrpc:C(Bi),id:Wi,...Re.shape}).strict(),tl=t=>Wy.safeParse(t).success,Hy=I({jsonrpc:C(Bi),...ut.shape}).strict(),Ky=t=>Hy.safeParse(t).success,rl=I({jsonrpc:C(Bi),id:Wi,result:Ie}).strict(),Jo=t=>rl.safeParse(t).success;var X;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(X||(X={}));var nl=I({jsonrpc:C(Bi),id:Wi.optional(),error:I({code:ae().int(),message:b(),data:_e().optional()})}).strict();var Jy=t=>nl.safeParse(t).success;var Gy=fe([Wy,Hy,rl,nl]),QU=fe([rl,nl]),Hi=Ie.strict(),CT=ct.extend({requestId:Wi.optional(),reason:b().optional()}),Ki=ut.extend({method:C("notifications/cancelled"),params:CT}),DT=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Ge(["light","dark"]).optional()}),Go=I({icons:Q(DT).optional()}),Nn=I({name:b(),title:b().optional()}),Yy=Nn.extend({...Nn.shape,...Go.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),zT=qi(I({applyDefaults:Pe().optional()}),be(b(),_e())),OT=Yu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,qi(I({form:zT.optional(),url:Ee.optional()}),be(b(),_e()).optional())),MT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({sampling:qe({createMessage:Ee.optional()}).optional(),elicitation:qe({create:Ee.optional()}).optional()}).optional()}),jT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({tools:qe({call:Ee.optional()}).optional()}).optional()}),NT=I({experimental:be(b(),Ee).optional(),sampling:I({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:OT.optional(),roots:I({listChanged:Pe().optional()}).optional(),tasks:MT.optional()}),LT=nt.extend({protocolVersion:b(),capabilities:NT,clientInfo:Yy}),ol=Re.extend({method:C("initialize"),params:LT});var FT=I({experimental:be(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:I({listChanged:Pe().optional()}).optional(),resources:I({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:I({listChanged:Pe().optional()}).optional(),tasks:jT.optional()}),ZT=Ie.extend({protocolVersion:b(),capabilities:FT,serverInfo:Yy,instructions:b().optional()}),sl=ut.extend({method:C("notifications/initialized"),params:ct.optional()});var Ji=Re.extend({method:C("ping"),params:nt.optional()}),UT=I({progress:ae(),total:xe(ae()),message:xe(b())}),qT=I({...ct.shape,...UT.shape,progressToken:qy}),Gi=ut.extend({method:C("notifications/progress"),params:qT}),VT=nt.extend({cursor:Vy.optional()}),Yo=Re.extend({params:VT.optional()}),Qo=Ie.extend({nextCursor:Vy.optional()}),BT=Ge(["working","input_required","completed","failed","cancelled"]),Xo=I({taskId:b(),status:BT,ttl:fe([ae(),Ju()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ae()),statusMessage:xe(b())}),Ln=Ie.extend({task:Xo}),WT=ct.merge(Xo),es=ut.extend({method:C("notifications/tasks/status"),params:WT}),Yi=Re.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Qi=Ie.merge(Xo),Xi=Re.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),XU=Ie.loose(),ea=Yo.extend({method:C("tasks/list")}),ta=Qo.extend({tasks:Q(Xo)}),ra=Re.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),Qy=Ie.merge(Xo),Xy=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),ev=Xy.extend({text:b()}),il=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),tv=Xy.extend({blob:il}),ts=Ge(["user","assistant"]),Fn=I({audience:Q(ts).optional(),priority:ae().min(0).max(1).optional(),lastModified:Wo.datetime({offset:!0}).optional()}),rv=I({...Nn.shape,...Go.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),HT=I({...Nn.shape,...Go.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),KT=Yo.extend({method:C("resources/list")}),JT=Qo.extend({resources:Q(rv)}),GT=Yo.extend({method:C("resources/templates/list")}),YT=Qo.extend({resourceTemplates:Q(HT)}),al=nt.extend({uri:b()}),QT=al,XT=Re.extend({method:C("resources/read"),params:QT}),eE=Ie.extend({contents:Q(fe([ev,tv]))}),tE=ut.extend({method:C("notifications/resources/list_changed"),params:ct.optional()}),rE=al,nE=Re.extend({method:C("resources/subscribe"),params:rE}),oE=al,sE=Re.extend({method:C("resources/unsubscribe"),params:oE}),iE=ct.extend({uri:b()}),aE=ut.extend({method:C("notifications/resources/updated"),params:iE}),cE=I({name:b(),description:xe(b()),required:xe(Pe())}),uE=I({...Nn.shape,...Go.shape,description:xe(b()),arguments:xe(Q(cE)),_meta:xe(qe({}))}),lE=Yo.extend({method:C("prompts/list")}),dE=Qo.extend({prompts:Q(uE)}),pE=nt.extend({name:b(),arguments:be(b(),b()).optional()}),fE=Re.extend({method:C("prompts/get"),params:pE}),cl=I({type:C("text"),text:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),ul=I({type:C("image"),data:il,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),ll=I({type:C("audio"),data:il,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),mE=I({type:C("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),hE=I({type:C("resource"),resource:fe([ev,tv]),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),gE=rv.extend({type:C("resource_link")}),dl=fe([cl,ul,ll,gE,hE]),yE=I({role:ts,content:dl}),vE=Ie.extend({description:b().optional(),messages:Q(yE)}),_E=ut.extend({method:C("notifications/prompts/list_changed"),params:ct.optional()}),bE=I({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),wE=I({taskSupport:Ge(["required","optional","forbidden"]).optional()}),nv=I({...Nn.shape,...Go.shape,description:b().optional(),inputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Q(b()).optional()}).catchall(_e()),outputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Q(b()).optional()}).catchall(_e()).optional(),annotations:bE.optional(),execution:wE.optional(),_meta:be(b(),_e()).optional()}),pl=Yo.extend({method:C("tools/list")}),xE=Qo.extend({tools:Q(nv)}),na=Ie.extend({content:Q(dl).default([]),structuredContent:be(b(),_e()).optional(),isError:Pe().optional()}),eq=na.or(Ie.extend({toolResult:_e()})),SE=Ko.extend({name:b(),arguments:be(b(),_e()).optional()}),rs=Re.extend({method:C("tools/call"),params:SE}),$E=ut.extend({method:C("notifications/tools/list_changed"),params:ct.optional()}),tq=I({autoRefresh:Pe().default(!0),debounceMs:ae().int().nonnegative().default(300)}),ns=Ge(["debug","info","notice","warning","error","critical","alert","emergency"]),kE=nt.extend({level:ns}),fl=Re.extend({method:C("logging/setLevel"),params:kE}),PE=ct.extend({level:ns,logger:b().optional(),data:_e()}),TE=ut.extend({method:C("notifications/message"),params:PE}),EE=I({name:b().optional()}),RE=I({hints:Q(EE).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),IE=I({mode:Ge(["auto","required","none"]).optional()}),AE=I({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(dl).default([]),structuredContent:I({}).loose().optional(),isError:Pe().optional(),_meta:be(b(),_e()).optional()}),CE=Gu("type",[cl,ul,ll]),Vi=Gu("type",[cl,ul,ll,mE,AE]),DE=I({role:ts,content:fe([Vi,Q(Vi)]),_meta:be(b(),_e()).optional()}),zE=Ko.extend({messages:Q(DE),modelPreferences:RE.optional(),systemPrompt:b().optional(),includeContext:Ge(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:Q(b()).optional(),metadata:Ee.optional(),tools:Q(nv).optional(),toolChoice:IE.optional()}),OE=Re.extend({method:C("sampling/createMessage"),params:zE}),ml=Ie.extend({model:b(),stopReason:xe(Ge(["endTurn","stopSequence","maxTokens"]).or(b())),role:ts,content:CE}),hl=Ie.extend({model:b(),stopReason:xe(Ge(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:ts,content:fe([Vi,Q(Vi)])}),ME=I({type:C("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),jE=I({type:C("string"),title:b().optional(),description:b().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:Ge(["email","uri","date","date-time"]).optional(),default:b().optional()}),NE=I({type:Ge(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),LE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),FE=I({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),ZE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),UE=fe([LE,FE]),qE=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({type:C("string"),enum:Q(b())}),default:Q(b()).optional()}),VE=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({anyOf:Q(I({const:b(),title:b()}))}),default:Q(b()).optional()}),BE=fe([qE,VE]),WE=fe([ZE,UE,BE]),HE=fe([WE,ME,jE,NE]),KE=Ko.extend({mode:C("form").optional(),message:b(),requestedSchema:I({type:C("object"),properties:be(b(),HE),required:Q(b()).optional()})}),JE=Ko.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),GE=fe([KE,JE]),YE=Re.extend({method:C("elicitation/create"),params:GE}),QE=ct.extend({elicitationId:b()}),XE=ut.extend({method:C("notifications/elicitation/complete"),params:QE}),oa=Ie.extend({action:Ge(["accept","decline","cancel"]),content:Yu(t=>t===null?void 0:t,be(b(),fe([b(),ae(),Pe(),Q(b())])).optional())}),eR=I({type:C("ref/resource"),uri:b()});var tR=I({type:C("ref/prompt"),name:b()}),rR=nt.extend({ref:fe([tR,eR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),nR=Re.extend({method:C("completion/complete"),params:rR});var oR=Ie.extend({completion:qe({values:Q(b()).max(100),total:xe(ae().int()),hasMore:xe(Pe())})}),sR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),iR=Re.extend({method:C("roots/list"),params:nt.optional()}),gl=Ie.extend({roots:Q(sR)}),aR=ut.extend({method:C("notifications/roots/list_changed"),params:ct.optional()}),rq=fe([Ji,ol,nR,fl,fE,lE,KT,GT,XT,nE,sE,rs,pl,Yi,Xi,ea,ra]),nq=fe([Ki,Gi,sl,aR,es]),oq=fe([Hi,ml,hl,oa,gl,Qi,ta,Ln]),sq=fe([Ji,OE,YE,iR,Yi,Xi,ea,ra]),iq=fe([Ki,Gi,TE,aE,tE,$E,_E,es,XE]),aq=fe([Hi,ZT,oR,vE,dE,JT,YT,eE,na,xE,Qi,ta,Ln]),W=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Qu(o.elicitations,r)}return new t(e,r,n)}},Qu=class extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function pr(t){return t==="completed"||t==="failed"||t==="cancelled"}var sv=Symbol("Let zodToJsonSchema decide on which parser to use");var ov={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},iv=t=>typeof t=="string"?{...ov,name:t}:{...ov,...t};var av=t=>{let e=iv(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function yl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,yl(t,e,n,o)}var sa=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?sa(e,t.currentPath):e.join("/")}}function cv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==P.ZodAny&&(r.items=L(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function uv(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function lv(){return{type:"boolean"}}function ia(t,e){return L(t.type._def,e)}var dv=(t,e)=>L(t.innerType._def,e);function vl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>vl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return cR(t,e)}}var cR=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function pv(t,e){return{...L(t.innerType._def,e),default:t.defaultValue()}}function fv(t,e){return e.effectStrategy==="input"?L(t.schema._def,e):we(e)}function mv(t){return{type:"string",enum:Array.from(t.values)}}var uR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function hv(t,e){let r=[L(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),L(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(uR(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function gv(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var _l,yt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(_l===void 0&&(_l=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_l),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function aa(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":vt(r,"email",n.message,e);break;case"format:idn-email":vt(r,"idn-email",n.message,e);break;case"pattern:zod":Ve(r,yt.email,n.message,e);break}break;case"url":vt(r,"uri",n.message,e);break;case"uuid":vt(r,"uuid",n.message,e);break;case"regex":Ve(r,n.regex,n.message,e);break;case"cuid":Ve(r,yt.cuid,n.message,e);break;case"cuid2":Ve(r,yt.cuid2,n.message,e);break;case"startsWith":Ve(r,RegExp(`^${bl(n.value,e)}`),n.message,e);break;case"endsWith":Ve(r,RegExp(`${bl(n.value,e)}$`),n.message,e);break;case"datetime":vt(r,"date-time",n.message,e);break;case"date":vt(r,"date",n.message,e);break;case"time":vt(r,"time",n.message,e);break;case"duration":vt(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ve(r,RegExp(bl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&vt(r,"ipv4",n.message,e),n.version!=="v4"&&vt(r,"ipv6",n.message,e);break}case"base64url":Ve(r,yt.base64url,n.message,e);break;case"jwt":Ve(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ve(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ve(r,yt.ipv6Cidr,n.message,e);break}case"emoji":Ve(r,yt.emoji(),n.message,e);break;case"ulid":{Ve(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{vt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ve(r,yt.base64,n.message,e);break}}break}case"nanoid":Ve(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function bl(t,e){return e.patternStrategy==="escape"?dR(t):t}var lR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function dR(t){let e="";for(let r=0;r<t.length;r++)lR.has(t[r])||(e+="\\"),e+=t[r];return e}function vt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ee(t,"format",e,r,n)}function Ve(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:yv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",yv(e,n),r,n)}function yv(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
234
234
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
235
235
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
236
236
  `:`[${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 aa(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]: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===k.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ia(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}=sa(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function fv(t,e){if(e.mapStrategy==="record")return aa(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 hv(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function gv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ns={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vv(t,e){if(e.target==="openApi3")return yv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ns&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ns[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 yv(t,e)}var yv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function _v(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ns[t.innerType._def.typeName],nullable:!0}:{type:[ns[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 bv(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",ml(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 wv(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=iR(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=sR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function sR(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 iR(t){try{return t.isOptional()}catch{return!0}}var xv=(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 Sv=(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 $v(t,e){return L(t.type._def,e)}function kv(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Pv(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 Tv(t){return{not:we(t)}}function Ev(t){return we(t)}var Rv=(t,e)=>L(t.innerType._def,e);var Iv=(t,e,r)=>{switch(e){case k.ZodString:return ia(t,r);case k.ZodNumber:return bv(t,r);case k.ZodObject:return wv(t,r);case k.ZodBigInt:return ov(t,r);case k.ZodBoolean:return sv();case k.ZodDate:return hl(t,r);case k.ZodUndefined:return Tv(r);case k.ZodNull:return gv(r);case k.ZodArray:return nv(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return vv(t,r);case k.ZodIntersection:return lv(t,r);case k.ZodTuple:return Pv(t,r);case k.ZodRecord:return aa(t,r);case k.ZodLiteral:return dv(t,r);case k.ZodEnum:return uv(t);case k.ZodNativeEnum:return mv(t);case k.ZodNullable:return _v(t,r);case k.ZodOptional:return xv(t,r);case k.ZodMap:return fv(t,r);case k.ZodSet:return kv(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return $v(t,r);case k.ZodNaN:case k.ZodNever:return hv(r);case k.ZodEffects:return cv(t,r);case k.ZodAny:return we(r);case k.ZodUnknown:return Ev(r);case k.ZodDefault:return av(t,r);case k.ZodBranded:return sa(t,r);case k.ZodReadonly:return Rv(t,r);case k.ZodCatch:return iv(t,r);case k.ZodPipeline:return Sv(t,r);case k.ZodFunction:case k.ZodVoid:case k.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!==ev)return a}if(n&&!r){let a=aR(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=Iv(t,t.typeName,e),i=typeof s=="function"?L(s(),e):s;if(i&&cR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var aR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:oa(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}},cR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ca=(t,e)=>{let r=rv(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 vl(t){let r=Fi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=hy(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function _l(t,e){let r=lr(t,e);if(!r.success)throw r.error;return r.data}var uR=6e4,ua=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(Hi,r=>{this._oncancel(r)}),this.setNotificationHandler(Gi,r=>{this._onprogress(r)}),this.setRequestHandler(Ki,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ji,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(Yi,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(Xi,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(ta,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),Ko(s)||Vy(s)?this._onresponse(s):Yu(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=Fy(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),Ko(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(Ko(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),Ko(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 _=x instanceof W?x:new W(X.RequestTimeout,String(x));l(_)};this._responseHandlers.set(p,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let _=lr(r,x.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??uR,y=()=>m(W.fromError(X.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let x=_=>{let P=this._responseHandlers.get(p);P?P(_):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,x),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(p),l(_)})}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},Qi,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ea,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Hy,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=vl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=_l(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=vl(e);this._notificationHandlers.set(n,o=>{let s=_l(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"&&Yu(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=Xo.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=Xo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),pr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Av(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Cv(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];Av(i)&&Av(s)?r[o]={...i,...s}:r[o]=s}return r}var vw=Vp(op(),1),_w=Vp(yw(),1);function Xz(){let t=new vw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_w.default)(t),t}var Wa=class{constructor(e){this._ajv=e??Xz()}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 Ha=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 bw(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 ww(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 Ka=class extends ua{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(rs.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 Wa,this.setRequestHandler(tl,n=>this._oninitialize(n)),this.setNotificationHandler(rl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ll,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=rs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ha(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Cv(this._capabilities,e)}setRequestHandler(e,r){let o=Fi(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(ts,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(ra,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){ww(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&bw(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:Ny.includes(r)?r:Ju,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"},Wi)}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},pl,r):this.request({method:"sampling/createMessage",params:e},dl,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},na,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},na,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},fl,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 Sw from"node:process";var Ga=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
238
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),eO(r)}clear(){this._buffer=void 0}};function eO(t){return By.parse(JSON.parse(t))}function xw(t){return JSON.stringify(t)+`
239
- `}var Ja=class{constructor(e=Sw.stdin,r=Sw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ga,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=xw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as SN}from"url";var pp={};Be(pp,{AI_CHAT_TIMEOUT_MS:()=>Ew,getTools:()=>rO,handleTool:()=>iO});import{readFileSync as $w}from"fs";function V(t){let e=ca(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var tO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata")}).optional(),kw=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:tO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Pw=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")}),Tw=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.")}),Ew=9e4;function rO(){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(kw)},{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(Pw)},{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(Tw)}]}async function nO(t,e){let r=kw.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=Vt(l,n);return{path:d,content:$w(d,"utf-8")}})}),a=e.aiChatTimeoutMs??Ew,c;try{c=await Promise.race([i,new Promise((l,d)=>setTimeout(()=>d(new Error("__AI_CHAT_TIMEOUT__")),a))])}catch(l){if(M(l)==="__AI_CHAT_TIMEOUT__"&&e.jobManager){let p=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5});return{content:[{type:"text",text:`\u23F1 Provider "${r.provider}" timed out after ${a/1e3}s. Auto-submitted as background job.
237
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function ca(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===P.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===P.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=aa(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===P.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ia(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function vv(t,e){if(e.mapStrategy==="record")return ca(t,e);let r=L(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function _v(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function bv(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function wv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var os={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Sv(t,e){if(e.target==="openApi3")return xv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in os&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=os[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return xv(t,e)}var xv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function $v(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:os[t.innerType._def.typeName],nullable:!0}:{type:[os[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=L(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function kv(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",yl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function Pv(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=fR(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=L(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=pR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function pR(t,e){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function fR(t){try{return t.isOptional()}catch{return!0}}var Tv=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return L(t.innerType._def,e);let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Ev=(t,e)=>{if(e.pipeStrategy==="input")return L(t.in._def,e);if(e.pipeStrategy==="output")return L(t.out._def,e);let r=L(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=L(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Rv(t,e){return L(t.type._def,e)}function Iv(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Av(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:L(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Cv(t){return{not:we(t)}}function Dv(t){return we(t)}var zv=(t,e)=>L(t.innerType._def,e);var Ov=(t,e,r)=>{switch(e){case P.ZodString:return aa(t,r);case P.ZodNumber:return kv(t,r);case P.ZodObject:return Pv(t,r);case P.ZodBigInt:return uv(t,r);case P.ZodBoolean:return lv();case P.ZodDate:return vl(t,r);case P.ZodUndefined:return Cv(r);case P.ZodNull:return wv(r);case P.ZodArray:return cv(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return Sv(t,r);case P.ZodIntersection:return hv(t,r);case P.ZodTuple:return Av(t,r);case P.ZodRecord:return ca(t,r);case P.ZodLiteral:return gv(t,r);case P.ZodEnum:return mv(t);case P.ZodNativeEnum:return _v(t);case P.ZodNullable:return $v(t,r);case P.ZodOptional:return Tv(t,r);case P.ZodMap:return vv(t,r);case P.ZodSet:return Iv(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return Rv(t,r);case P.ZodNaN:case P.ZodNever:return bv(r);case P.ZodEffects:return fv(t,r);case P.ZodAny:return we(r);case P.ZodUnknown:return Dv(r);case P.ZodDefault:return pv(t,r);case P.ZodBranded:return ia(t,r);case P.ZodReadonly:return zv(t,r);case P.ZodCatch:return dv(t,r);case P.ZodPipeline:return Ev(t,r);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(n=>{})(e)}};function L(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==sv)return a}if(n&&!r){let a=mR(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Ov(t,t.typeName,e),i=typeof s=="function"?L(s(),e):s;if(i&&hR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var mR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sa(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},hR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ua=(t,e)=>{let r=av(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:L(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=L(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function wl(t){let r=Zi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=by(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function xl(t,e){let r=lr(t,e);if(!r.success)throw r.error;return r.data}var gR=6e4,la=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ki,r=>{this._oncancel(r)}),this.setNotificationHandler(Gi,r=>{this._onprogress(r)}),this.setRequestHandler(Ji,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Yi,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Xi,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new W(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new W(X.InvalidParams,`Task not found: ${s}`);if(!pr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(pr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[dr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ea,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new W(X.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ra,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,`Task not found: ${r.params.taskId}`);if(pr(o.status))throw new W(X.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(X.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof W?o:new W(X.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),W.fromError(X.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Jo(s)||Jy(s)?this._onresponse(s):tl(s)?this._onrequest(s,i):Ky(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=W.fromError(X.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[dr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:X.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=By(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:X.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Jo(e))n(e);else{let i=new W(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Jo(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Jo(e))o(e);else{let i=W.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Ln,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(X.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},pr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new W(X.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new W(X.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[dr]:c}});let m=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let v=S instanceof W?S:new W(X.RequestTimeout,String(S));l(v)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let v=lr(r,S.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??gR,y=()=>m(W.fromError(X.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let S=v=>{let k=this._responseHandlers.get(p);k?k(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qi,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ta,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Qy,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[dr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[dr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[dr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=wl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=xl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=wl(e);this._notificationHandlers.set(n,o=>{let s=xl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&tl(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new W(X.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new W(X.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new W(X.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=es.parse({method:"notifications/tasks/status",params:a});await this.notification(c),pr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new W(X.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(pr(a.status))throw new W(X.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=es.parse({method:"notifications/tasks/status",params:c});await this.notification(u),pr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Mv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jv(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Mv(i)&&Mv(s)?r[o]={...i,...s}:r[o]=s}return r}var Sw=Jp(ap(),1),$w=Jp(xw(),1);function iO(){let t=new Sw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$w.default)(t),t}var Ha=class{constructor(e){this._ajv=e??iO()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ka=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function kw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Pw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ja=class extends la{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ns.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ha,this.setRequestHandler(ol,n=>this._oninitialize(n)),this.setNotificationHandler(sl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(fl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ns.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ka(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=jv(this._capabilities,e)}setRequestHandler(e,r){let o=Zi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(jn(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=lr(rs,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new W(X.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=lr(Ln,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new W(X.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=lr(na,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new W(X.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Pw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&kw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Uy.includes(r)?r:Xu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Hi)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},hl,r):this.request({method:"sampling/createMessage",params:e},ml,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},oa,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},oa,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new W(X.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof W?i:new W(X.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},gl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Ew from"node:process";var Ga=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
238
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),aO(r)}clear(){this._buffer=void 0}};function aO(t){return Gy.parse(JSON.parse(t))}function Tw(t){return JSON.stringify(t)+`
239
+ `}var Ya=class{constructor(e=Ew.stdin,r=Ew.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ga,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Tw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as Kj}from"url";var hp={};Ze(hp,{AI_CHAT_TIMEOUT_MS:()=>Dw,getTools:()=>uO,handleTool:()=>fO});import{readFileSync as Rw}from"fs";function V(t){let e=ua(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var cO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata")}).optional(),Iw=h.object({provider:h.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:h.string().describe("Chat prompt to send"),model:h.string().optional().describe("Model override"),system:h.string().optional().describe("System prompt"),files:h.array(h.string()).optional().describe("File paths to include as context"),save_as_document:cO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Aw=h.object({provider:h.string().describe("Provider ID"),file_paths:h.array(h.string()).min(1).describe("File paths to analyze"),question:h.string().describe("Question to ask about the files"),save_to_file:h.string().optional().describe("Path to save the analysis result")}),Cw=h.object({providers:h.array(h.string()).min(1).describe("List of provider IDs to compare"),prompt:h.string().describe("Prompt to send to all providers"),aggregate_provider:h.string().optional().describe("Provider ID to synthesize all responses into a unified document. If omitted, returns raw comparisons only."),aggregate_prompt:h.string().optional().describe("Custom synthesis prompt. Default: synthesize and identify agreements/disagreements.")}),Dw=9e4;function uO(){return[{name:"ai_chat",title:"AI Chat",description:"Chat with a specific AI provider. Sends a prompt and returns the response. Optionally saves the response as a workspace document.",inputSchema:V(Iw)},{name:"ai_analyze_files",title:"Analyze Files with AI",description:"Analyze files with an AI provider. Reads files from disk, sends contents with a question, and optionally saves the result.",inputSchema:V(Aw)},{name:"ai_compare",title:"Compare AI Providers",description:"Send the same prompt to multiple providers and return a comparison. Optionally aggregate results into a unified synthesis using a designated provider.",inputSchema:V(Cw)}]}async function lO(t,e){let r=Iw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("chat",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=s.chat({prompt:r.prompt,model:r.model,system:r.system,files:r.files?.map(l=>{let d=Bt(l,n);return{path:d,content:Rw(d,"utf-8")}})}),a=e.aiChatTimeoutMs??Dw,c;try{c=await Promise.race([i,new Promise((l,d)=>setTimeout(()=>d(new Error("__AI_CHAT_TIMEOUT__")),a))])}catch(l){if(M(l)==="__AI_CHAT_TIMEOUT__"&&e.jobManager){let p=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5});return{content:[{type:"text",text:`\u23F1 Provider "${r.provider}" timed out after ${a/1e3}s. Auto-submitted as background job.
240
240
 
241
241
  **Job ID:** ${p}
242
242
 
@@ -245,7 +245,7 @@ Use \`cli_job_status\` to check progress.`}]}}throw l}let u="";if(r.save_as_docu
245
245
  \u26A0 Document save failed: ${M(l)}`}return{content:[{type:"text",text:`**Provider:** ${c.provider}
246
246
  **Model:** ${c.model}${u}
247
247
 
248
- ${c.text}`}]}}async function oO(t,e){let r=Pw.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=Vt(l,n),p=$w(d,"utf-8");return`--- ${d} ---
248
+ ${c.text}`}]}}async function dO(t,e){let r=Aw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("analysis",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let a=`${r.file_paths.map(l=>{let d=Bt(l,n),p=Rw(d,"utf-8");return`--- ${d} ---
249
249
  ${p}`}).join(`
250
250
 
251
251
  `)}
@@ -257,7 +257,7 @@ Question: ${r.question}`,c=await s.chat({prompt:a});if(r.save_to_file){let l=ht(
257
257
  _Result saved to: ${r.save_to_file}_`:"";return{content:[{type:"text",text:`**Provider:** ${c.provider}
258
258
  **Files analyzed:** ${r.file_paths.join(", ")}
259
259
 
260
- ${c.text}${u}`}]}}async function sO(t,e){let r=Tw.parse(t),n=r.providers.map(c=>e.registry.get(c)),o=await Promise.all(n.map(async c=>{try{let u=await c.chat({prompt:r.prompt});return{provider:c.id,text:u.text,error:null}}catch(u){return{provider:c.id,text:null,error:M(u)}}})),s=`# Comparison
260
+ ${c.text}${u}`}]}}async function pO(t,e){let r=Cw.parse(t),n=r.providers.map(c=>e.registry.get(c)),o=await Promise.all(n.map(async c=>{try{let u=await c.chat({prompt:r.prompt});return{provider:c.id,text:u.text,error:null}}catch(u){return{provider:c.id,text:null,error:M(u)}}})),s=`# Comparison
261
261
 
262
262
  **Prompt:** ${r.prompt}
263
263
 
@@ -276,35 +276,44 @@ ${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${M
276
276
 
277
277
  # Synthesis
278
278
 
279
- ${i}`),{content:[{type:"text",text:a}]}}async function iO(t,e,r){switch(t){case"ai_chat":return nO(e,r);case"ai_analyze_files":return oO(e,r);case"ai_compare":return sO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var kp={};Be(kp,{getTools:()=>fp,handleTool:()=>Rx});var Qa=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),max_rounds:h.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:h.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:h.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:h.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),Ya=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")}),Xa=h.object({session_id:h.string().describe("Session ID to check")}),ec=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)")}),tc=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.")}),rc=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")}),nc=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")}),oc=h.object({task_id:h.string().describe("Task ID to review changes for")}),sc=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),ic=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),Rw=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()}),ac=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.")}),cc=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'.")}),uc=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.")}),lc=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 dc="agent_debate_structured",no="agent_debate_approve",oo="agent_debate_continue",so="agent_debate_reject";function pc(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 Iw(t,e){let r=pc(e);if(r)return r;let n;try{n=ac.parse(t)}catch(s){return Yt(`Invalid arguments: ${M(s)}`)}let o=aO(n.leader,n.participants,e);if(!o)return Yt("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(zw(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(Mw(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(Ow(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
279
+ ${i}`),{content:[{type:"text",text:a}]}}async function fO(t,e,r){switch(t){case"ai_chat":return lO(e,r);case"ai_analyze_files":return dO(e,r);case"ai_compare":return pO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ip={};Ze(Ip,{getTools:()=>gp,handleTool:()=>Ox});var Qa=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),max_rounds:h.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:h.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:h.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:h.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),Xa=h.object({items:h.array(h.object({provider:h.string().describe("Provider that produced the content"),content:h.string().describe("Content to validate"),task:h.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:h.array(h.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:h.string().optional().describe("Custom validation criteria")}),ec=h.object({session_id:h.string().describe("Session ID to check")}),tc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),goal:h.string().optional().describe("Quality goal for the debate"),save_document:h.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),rc=h.object({debate_id:h.string().describe("Debate session ID"),provider:h.string().describe(`Provider ID to take this turn. Use "claude" to record Claude's own opinion as an independent turn (requires claude_comment).`),claude_comment:h.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:h.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),nc=h.object({debate_id:h.string().describe("Debate session ID to conclude"),summary:h.string().optional().describe("Claude's final summary of the debate"),quality_scores:h.array(h.object({provider:h.string(),score:h.number().min(0).max(1),feedback:h.string()})).optional().describe("Quality assessment of each provider's contribution")}),oc=h.object({document:h.string().describe("Document content to review"),providers:h.array(h.string()).min(1).describe("Provider IDs to review the document"),review_prompt:h.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:h.string().optional().describe("Link reviews to an existing debate session's workspace document")}),sc=h.object({task_id:h.string().describe("Task ID to review changes for")}),ic=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),ac=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),zw=h.object({agrees:h.union([h.boolean(),h.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:h.string().optional().default(""),suggestions:h.string().optional()}),cc=h.object({topic:h.string().min(1).describe("Topic for the structured debate"),scope:h.string().optional().describe("What the leader wants debated (file list or task framing). Defaults to topic when omitted."),goal:h.string().optional().describe("Optional quality goal for the debate"),leader:h.string().optional().describe("Participant ID authorized to approve the final synthesis. Defaults to the session-context leader or the first participant."),participants:h.array(h.string()).min(1).describe("Participant IDs. When `auto_inject_specialists` is true (default), `claude-reviewer` and/or `claude-qa` may be added based on the topic."),exclude_participants:h.array(h.string()).optional().describe("Participant IDs to never inject/include. Applied regardless of `auto_inject_specialists`."),auto_inject_specialists:h.boolean().optional().default(!0).describe("When true (default), topic-matching Claude specialists are added to `participants` honoring `exclude_participants`. When false, `participants` is used verbatim."),max_rounds:h.number().int().positive().max(50).optional().describe("Maximum number of rounds. Default: STRUCTURED_DEBATE_DEFAULT_MAX_ROUNDS."),individual_review_prompt:h.string().optional().describe("Override the system prompt used for individual-review fan-out."),files:h.array(h.string()).optional().describe("Optional list of files to pass to participants as context."),locale:h.enum(["ko","zh","ja","en"]).optional().describe("Override config locale for moderator text in this debate only.")}),uc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),leader_note:h.string().optional().describe("Optional note appended to the synthesis footer under 'Leader approval notes'.")}),lc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),additional_rounds:h.union([h.literal(3),h.literal(5),h.literal(10)]).describe("How many extra rounds to run beyond the current round count. Choose one of 3, 5, or 10.")}),dc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),reason:h.string().optional().describe("Optional rejection reason, captured in the debate transcript footer."),spawn_issue:h.boolean().optional().default(!1).describe("If true, write an issue_{sessionIdShort}_{YYYYMMDD}_{seq}.md under individual/ listing all non-accepted proposals (rejected/withdrawn/open/inconclusive/superseded). Default false.")});var pc="agent_debate_structured",no="agent_debate_approve",oo="agent_debate_continue",so="agent_debate_reject";function fc(t){return t.moderatorEngine?t.structuredSessionRegistry?null:{content:[{type:"text",text:"Structured session registry is not initialized for this workspace."}],isError:!0}:{content:[{type:"text",text:"Structured debate engine is not initialized for this workspace. Check MCP server wiring."}],isError:!0}}async function Ow(t,e){let r=fc(e);if(r)return r;let n;try{n=cc.parse(t)}catch(s){return Xt(`Invalid arguments: ${M(s)}`)}let o=mO(n.leader,n.participants,e);if(!o)return Xt("Cannot resolve a leader. Provide `leader` explicitly or ensure the session context exposes one.");try{let s=await e.moderatorEngine.startDebate({topic:n.topic,...n.scope!==void 0?{scope:n.scope}:{},...n.goal!==void 0?{goal:n.goal}:{},leader:o,participants:n.participants,...n.exclude_participants!==void 0?{excludeParticipants:n.exclude_participants}:{},...n.auto_inject_specialists!==void 0?{autoInjectSpecialists:n.auto_inject_specialists}:{},...n.max_rounds!==void 0?{maxRounds:n.max_rounds}:{},...n.locale!==void 0?{locale:n.locale}:{},...n.individual_review_prompt!==void 0?{individualReviewPrompt:n.individual_review_prompt}:{},...n.files!==void 0?{files:n.files}:{}}),i=[s.terminalReport];return i.push(Lw(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(Zw(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(Fw(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
280
280
 
281
- `)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return Yt(`Failed to start structured debate: ${M(s)}`)}}async function Aw(t,e){let r=pc(e);if(r)return r;let n;try{n=cc.parse(t)}catch(o){return Yt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.approve({sessionId:n.session_id,...n.leader_note!==void 0?{leaderNote:n.leader_note}:{}}),s=[o.terminalReport];return s.push(`Synthesis document: ${o.synthesisPath}`),s.push(`Status: ${o.snapshot.status} (session ${n.session_id})`),o.idempotentReplay&&s.push("(idempotent replay of existing approved state \u2014 no new synthesis written)"),{content:[{type:"text",text:s.join(`
281
+ `)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return Xt(`Failed to start structured debate: ${M(s)}`)}}async function Mw(t,e){let r=fc(e);if(r)return r;let n;try{n=uc.parse(t)}catch(o){return Xt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.approve({sessionId:n.session_id,...n.leader_note!==void 0?{leaderNote:n.leader_note}:{}}),s=[o.terminalReport];return s.push(`Synthesis document: ${o.synthesisPath}`),s.push(`Status: ${o.snapshot.status} (session ${n.session_id})`),o.idempotentReplay&&s.push("(idempotent replay of existing approved state \u2014 no new synthesis written)"),{content:[{type:"text",text:s.join(`
282
282
 
283
- `)}]}}catch(o){return Yt(`Approve failed: ${M(o)}`)}}async function Cw(t,e){let r=pc(e);if(r)return r;let n;try{n=uc.parse(t)}catch(o){return Yt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds}),s=[o.terminalReport];return s.push(zw(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(Mw(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(Ow(n.session_id)),{content:[{type:"text",text:s.join(`
283
+ `)}]}}catch(o){return Xt(`Approve failed: ${M(o)}`)}}async function jw(t,e){let r=fc(e);if(r)return r;let n;try{n=lc.parse(t)}catch(o){return Xt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds}),s=[o.terminalReport];return s.push(Lw(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(Zw(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(Fw(n.session_id)),{content:[{type:"text",text:s.join(`
284
284
 
285
- `)}]}}catch(o){return Yt(`Continue failed: ${M(o)}`)}}async function Dw(t,e){let r=pc(e);if(r)return r;let n;try{n=lc.parse(t)}catch(o){return Yt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.reject({sessionId:n.session_id,...n.reason!==void 0?{reason:n.reason}:{},...n.spawn_issue!==void 0?{spawnIssue:n.spawn_issue}:{}}),s=o.snapshot.documentPaths.debate,i=[`Structured debate session ${n.session_id} rejected.`];return n.reason&&i.push(`Reason: ${n.reason}`),i.push(`Transcript: ${s}`),o.issuePath&&i.push(`Issue document: ${o.issuePath}`),o.idempotentReplay&&i.push("(idempotent replay of existing rejected state \u2014 no new artifacts written)"),{content:[{type:"text",text:i.join(`
286
- `)}]}}catch(o){return Yt(`Reject failed: ${M(o)}`)}}function aO(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 zw(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function Ow(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 Mw(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 Yt(t){return{content:[{type:"text",text:t}],isError:!0}}function fp(){return[{name:"agent_debate_start",title:"Start AI Debate",description:"Start a multi-provider debate on a topic. Optionally enable enhanced mode with goal-based quality validation.",inputSchema:V(Qa)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:V(Xa)},{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(Ya)},{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(ec)},{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(tc)},{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(rc)},{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(nc)},{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(oc)},{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(sc)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:V(ic)},{name:dc,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(ac)},{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(cc)},{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(uc)},{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(lc)}]}import{readFileSync as uO}from"fs";import{join as Zw}from"path";function Nw(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 fc="claude-reviewer",mc="claude-qa",cO={"agestra-reviewer":fc,"agestra-qa":mc};function jw(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=Nw(e,r),u=c!==null?cO[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 Lw="claude",mp="claude-cli",lO=new Set([fc,mc]),hp=Object.freeze({[fc]:"agestra-reviewer",[mc]:"agestra-qa"});function dO(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
285
+ `)}]}}catch(o){return Xt(`Continue failed: ${M(o)}`)}}async function Nw(t,e){let r=fc(e);if(r)return r;let n;try{n=dc.parse(t)}catch(o){return Xt(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.reject({sessionId:n.session_id,...n.reason!==void 0?{reason:n.reason}:{},...n.spawn_issue!==void 0?{spawnIssue:n.spawn_issue}:{}}),s=o.snapshot.documentPaths.debate,i=[`Structured debate session ${n.session_id} rejected.`];return n.reason&&i.push(`Reason: ${n.reason}`),i.push(`Transcript: ${s}`),o.issuePath&&i.push(`Issue document: ${o.issuePath}`),o.idempotentReplay&&i.push("(idempotent replay of existing rejected state \u2014 no new artifacts written)"),{content:[{type:"text",text:i.join(`
286
+ `)}]}}catch(o){return Xt(`Reject failed: ${M(o)}`)}}function mO(t,e,r){if(t&&t.length>0)return t;let n=r.sessionContext?.leaderProviderId;return n&&e.includes(n)||n?n:e[0]}function Lw(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function Fw(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${no}\` with { session_id: "${t}" }`,`- Extend debate: call \`${oo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${so}\` with { session_id: "${t}" }`].join(`
287
+ `)}function Zw(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${oo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${no}\` to accept the current synthesis with open items captured.`,`- \`${so}\` to abandon the session.`,`Session ID: ${t}`].join(`
288
+ `)}function Xt(t){return{content:[{type:"text",text:t}],isError:!0}}function gp(){return[{name:"agent_debate_start",title:"Start AI Debate",description:"Start a multi-provider debate on a topic. Optionally enable enhanced mode with goal-based quality validation.",inputSchema:V(Qa)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:V(ec)},{name:"agent_cross_validate",title:"Cross-Validate Outputs",description:"Cross-validate work outputs. Each item is reviewed by agent-tier providers. Tool-tier providers cannot be validators.",inputSchema:V(Xa)},{name:"agent_debate_create",title:"Create Turn-Based Debate",description:"Create a turn-based debate session. Returns a debate ID for use with agent_debate_turn and agent_debate_conclude.",inputSchema:V(tc)},{name:"agent_debate_turn",title:"Execute Debate Turn",description:`Execute one provider's turn in a debate. Optionally inject Claude's comment before the provider responds. Returns the provider's response. Use provider: "claude" with claude_comment to record Claude's own independent opinion as a debate turn.`,inputSchema:V(rc)},{name:"agent_debate_conclude",title:"Conclude Debate",description:"End a debate session and generate the final transcript. Optionally add Claude's summary and quality scores for each provider.",inputSchema:V(nc)},{name:"agent_debate_review",title:"Review Document with Providers",description:"Send a document to multiple providers for structured review. Each provider responds with agree/disagree and feedback. Use iteratively: review \u2192 revise document based on feedback \u2192 review again until all agree.",inputSchema:V(oc)},{name:"agent_changes_review",title:"Review File Changes",description:"Review file changes made by an external AI in an isolated worktree. Shows diff stat and full diff.",inputSchema:V(sc)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:V(ic)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:V(ac)},{name:pc,title:"Start Structured Debate",description:"Start a structured, approval-gated debate. Each participant submits an individual review, then rounds run until consensus or max rounds. Output is a ready-for-approval session \u2014 call agent_debate_approve/continue/reject to finalize. No synthesis is written until approved.",inputSchema:V(cc)},{name:no,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:V(uc)},{name:oo,title:"Continue Structured Debate",description:"Run additional rounds on a ready-for-approval (or escalated) structured-debate session. Choose 3, 5, or 10 extra rounds.",inputSchema:V(lc)},{name:so,title:"Reject Structured Debate",description:"Reject a ready-for-approval (or escalated/leader-timeout) structured-debate session. Transcript is marked rejected; no synthesis is written.",inputSchema:V(dc)}]}import{readFileSync as gO}from"fs";import{join as Hw}from"path";function Uw(t,e){let r=`${t} ${e??""}`.toLowerCase(),n=[{patterns:[/\breview\b/,/\bcode\s*quality\b/,/\bsecurity\b/,/\baudit\b/,/리뷰/,/보안/,/코드\s*품질/],agent:"agestra-reviewer"},{patterns:[/\bdesign\b/,/\barchitect/,/\bstructur/,/설계/,/아키텍처/,/구조/],agent:"agestra-designer"},{patterns:[/\bidea\b/,/\bimprov/,/\bcompare\b/,/\balternativ/,/\bbrainstorm/,/개선/,/아이디어/,/비교/,/대안/],agent:"agestra-ideator"},{patterns:[/\bverif/,/\bvalidat/,/\bqa\b/,/\btest\b/,/\bcheck\b/,/검증/,/테스트/,/확인/],agent:"agestra-qa"}];for(let o of n)if(o.patterns.some(s=>s.test(r)))return o.agent;return null}var mc="claude-reviewer",hc="claude-qa",hO={"agestra-reviewer":mc,"agestra-qa":hc};function qw(t){let{topic:e,goal:r,participants:n,excludeParticipants:o,autoInjectSpecialists:s}=t,i=new Set(o),a=n.filter(d=>!i.has(d)),c=Uw(e,r),u=c!==null?hO[c]??null:null,l=[];return u===null?{participants:a,skipped:l}:s?i.has(u)?(l.push({participantId:u,reason:"explicitly-excluded"}),{participants:a,skipped:l}):a.includes(u)?(l.push({participantId:u,reason:"already-listed"}),{participants:a,skipped:l}):{participants:[...a,u],skipped:l}:(l.push({participantId:u,reason:"auto-disabled"}),{participants:a,skipped:l})}var vp="claude",_p="claude-cli",yO=new Set([mc,hc]),bp=Object.freeze({[mc]:"agestra-reviewer",[hc]:"agestra-qa"});function vO(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
289
289
  `,3);if(e<0)return t;let r=t.indexOf(`
290
290
  ---`,e);if(r<0)return t;let n=t.indexOf(`
291
- `,r+4);return n<0?"":t.slice(n+1)}function Fw(t,e){return lO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:hp[t]}:{transport:"cli-bridge",providerId:mp,agentName:hp[t]}:t===Lw?e==="claude-code"?{transport:"read-only-chat",providerId:Lw}:{transport:"cli-bridge",providerId:mp}:{transport:"read-only-chat",providerId:t}}function pO(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=hp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=Zw(r,`${s}.md`);try{let a=dO(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var gp=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??Zw(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>uO(r,"utf-8")),this.subagentSpawner=e.subagentSpawner}describe(e){return Fw(e,this.hostKind)}async requestTurn(e,r){let n=Fw(e,this.hostKind),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 this.subagentSpawner({agentName:n.agentName??e,prompt:r.prompt,system:r.system});return this.buildSuccess(e,o,s.text)}case"cli-bridge":{let s=n.providerId??mp,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=pO(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a});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=await this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:r.system});return this.buildSuccess(e,o,a.text)}default:{let s=n.transport;return this.buildFailure(e,o,`unknown transport: ${String(s)}`)}}}catch(s){return this.buildFailure(e,o,M(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}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 Uw(t){return new gp(t)}function qw(t,e){return e(t)}var fO=/[.,!?;:]/g,mO=/\s+/g;function Vw(t){return t.toLowerCase().replace(fO," ").replace(mO," ").trim()}function Bw(t){return typeof t.location=="string"&&t.location.length>0}function Ww(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 hO(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 gO(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=Vw(t.title)===Vw(e.title),s=t.severity===e.severity,a=Bw(t)&&Bw(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=Ww(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=yO(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(hO(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=Ww(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 yO(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function Hw(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=gO(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 vO=new Set(of);function _O(t){return vO.has(t)}var bO=new Set(["disagree","revise"]);function wO(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 xO(t){let e=`<${ln}>`;return t.includes(e)}var SO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function $O(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 SO[r]??e})}function kO(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]=$O(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function Gw(t,e){let r=wO(t);if(!r)return xO(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(!Kw(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(!Kw(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=kO(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(!_O(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,v=typeof y=="string"&&y.length>0?y:void 0;if(bO.has(g)&&v===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};v!==void 0&&(x.reason=v),u.push(x)}return{ok:!0,entries:u,entryErrors:l}}function Kw(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var PO=Object.freeze(["same","different","unsure"]),Ds="alias-votes",TO=new Set(PO);function EO(t){return TO.has(t)}function RO(t){let e=`<${Ds}>`,r=`</${Ds}>`,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 IO(t){let e=`<${Ds}>`;return t.includes(e)}var AO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function CO(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 AO[r]??e})}function DO(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]=CO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function Jw(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Qw(t,e){let r=RO(t);if(!r)return IO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Ds}> without matching </${Ds}>`}}:{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(!Jw(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(!Jw(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=DO(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(!EO(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,v=typeof y=="string"&&y.length>0?y:void 0;d.add(m);let x={pair:m,vote:g};v!==void 0&&(x.reason=v),u.push(x)}return{ok:!0,entries:u,entryErrors:l}}var zO="__";function OO(t){return`${t.proposalA}${zO}${t.proposalB}`}var MO=["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(" "),NO=["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(" "),jO=["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
- `),LO="Candidate pairs:";async function ex(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(OO),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=FO(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:VO(m.reason)}),yp(l,s);continue}let{response:y}=m.value;if(y.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),yp(l,s);continue}let v=Qw(y.text,s);if(!v.ok){u.push({participantId:g,reason:v.error.details!==void 0?`${v.error.kind}: ${v.error.details}`:v.error.kind}),yp(l,s);continue}let x=new Set;for(let _ of v.entries)UO(l,_),x.add(_.pair);for(let _ of s)if(!x.has(_)){let P=l.get(_);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=qO(g);if(y.kind==="merge"){let v=m.proposalA,x=m.proposalB;if(e.proposals.get(v)===void 0||e.proposals.get(x)===void 0)continue;e.applyAliasMerge(v,x),d.push({primary:v,alias:x,voteBreakdown:{...g}});continue}p.push({pair:m,voteBreakdown:{...g},reason:y.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function FO(t,e,r){let n=[];n.push(MO),n.push(""),n.push(NO),n.push(""),n.push(LO),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:"),Yw(n,a),n.push(" Proposal B:"),Yw(n,c),n.push("")}return n.push(jO),n.join(`
293
- `)}function Yw(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=ZO(e.description);t.push(` description: ${r}`)}}var Xw=400;function ZO(t){return t.length<=Xw?t:`${t.slice(0,Xw)}\u2026`}function UO(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 yp(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function qO(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 VO(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as BO}from"fs/promises";import{readFileSync as WO,existsSync as vp,unlinkSync as HO,mkdirSync as KO}from"fs";import{join as zs}from"path";var bp=".approval.json";function _p(t){return`${t}${bp}`}function GO(t){return t.endsWith(bp)?t.slice(0,t.length-bp.length):null}function tx(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+sf).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=zs(e,Zs)}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}`);KO(this.debatesDir,{recursive:!0});let r=zs(this.debatesDir,_p(e.sessionId));Ge(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=zs(this.debatesDir,_p(e));if(!vp(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=zs(this.debatesDir,_p(e));if(vp(r))try{HO(r)}catch(n){if(n.code!=="ENOENT")throw n}}async hydrateFromDisk(){if(this.cache.clear(),!vp(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await BO(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=GO(r);if(!n)continue;let o=this.readSnapshotFile(zs(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=WO(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 JO(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function JO(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 QO(t,e){let r=[];r.push(...eM(t,e)),r.push(""),r.push(...nx(t,e));let n=ox(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...sx(t,e)),r.push(""),r.push(...rM(t,e)),r.join(`
294
- `)}function YO(t,e){let r=[];r.push(...nx(t,e));let n=nM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=oM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=sM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=ox(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...sx(t,e)),r.join(`
295
- `)}function rx(){return{renderTerminal:QO,renderSynthesis:YO}}var XO=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 eM(t,e){let r=e.t(XO[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 nx(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=tM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function tM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function ox(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(wp(o))}return r}function wp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function sx(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 rM(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 nM(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 oM(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(wp(s))}return n}function sM(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(wp(s))}return n}var co=class{deps;sessions=new Map;formatter=rx();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??iM)(),n=this.nowIso(),o=jw({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??Rc,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,nextProposalIndex:1};this.sessions.set(r,c);try{let u=await this.runIndividualPhase(c,o),{ledger:l}=Hw(u);c.ledger=l,c.nextProposalIndex=fM(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",hc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:hc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:hc(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}}xp(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??Sp(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);xp(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}:{}};xp(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??Sp(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:pM(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 runIndividualPhase(e,r){let n=bM(),o=wM(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});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=_M(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 ex({ledger:e.ledger,participantIds:e.config.participants,askParticipant:async(o,s)=>{let i=await this.deps.bridge.requestTurn(o,{prompt:s,round:0});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=$M(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;){let r=e.ledger.getOpenProposals().map(d=>d.id);if(r.length===0)return;e.rounds+=1;let n=e.rounds,o=e.config.participants.filter(d=>!e.unavailableParticipants.has(d)),s=e.ledger.getOpenProposals(),i=xM({round:n,maxRounds:e.maxRounds,topic:e.config.topic,scope:e.config.scope,openProposals:s}),a=await Promise.allSettled(o.map(async d=>{let p={prompt:i,round:n},f=await this.deps.bridge.requestTurn(d,p);return{participantId:d,resp:f}})),c=[],u=new Set;for(let d=0;d<a.length;d+=1){let p=a[d],f=o[d];if(p.status==="rejected"||p.value.resp.failed){this.registerFailure(e,f);let y=p.status==="rejected"?hc(p.reason):p.value.resp.failureReason??"unknown";c.push({participantId:f,text:`(no response: ${y})`,failed:!0});continue}this.clearFailure(e,f),u.add(f);let m=p.value.resp.text;c.push({participantId:f,text:m,failed:!1});let g=Gw(m,r);if(g.ok)for(let y of g.entries)e.ledger.recordVote(y.proposalId,f,{vote:y.vote,roundRecorded:n,...y.reason!==void 0?{reason:y.reason}:{}})}let l=e.ledger.aggregateRound(n,e.config.participants,Array.from(e.unavailableParticipants));for(let d of l){let p=e.ledger.proposals.get(d.proposalId);if(!p)continue;let f=e.config.participants.filter(m=>!p.proposerIds.includes(m)).length;if(cM(d.tally,f)){e.ledger.setStatus(d.proposalId,"consensus"),e.allAbstainCount.delete(d.proposalId);continue}if(uM(d.tally,f)){e.ledger.setStatus(d.proposalId,"rejected"),e.allAbstainCount.delete(d.proposalId);continue}if(lM(d.tally)){let m=(e.allAbstainCount.get(d.proposalId)??0)+1;e.allAbstainCount.set(d.proposalId,m),m>=Ac&&(e.ledger.setStatus(d.proposalId,"unresolved"),e.allAbstainCount.delete(d.proposalId));continue}e.allAbstainCount.delete(d.proposalId)}for(let d of l){if(d.tally.revise===0)continue;let p=e.ledger.proposals.get(d.proposalId);if(!p||p.status!=="open"||e.ledger.countRevisesThisRound(d.proposalId,n)===0)continue;let m=this.synthesizeReviseSuccessor(e,p,n);e.reviseSuccessors.set(p.id,m)}if(await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:SM({round:n,maxRounds:e.maxRounds,openProposals:s,turns:c,aggregation:l,ledger:e.ledger})}),u.size===0)return}}registerFailure(e,r){let n=(e.consecutiveFailures.get(r)??0)+1;e.consecutiveFailures.set(r,n),n>=Ic&&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=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:Sp(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,nextProposalIndex:s+1}}buildSnapshot(e,r,n){let o=this.nowIso(),s=aM(r)?qw(o,tx):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,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:dM(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=mM(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=hM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:ux(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}
291
+ `,r+4);return n<0?"":t.slice(n+1)}function _O(t,e){return yO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:bp[t]}:{transport:"cli-bridge",providerId:_p,agentName:bp[t]}:t===vp?e==="claude-code"?{transport:"read-only-chat",providerId:vp}:{transport:"cli-bridge",providerId:_p}:{transport:"read-only-chat",providerId:t}}function Vw(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var Bw=18e4;function yp(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${Bw/1e3}s)`)),Bw))])}function Ww(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=bp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=Hw(r,`${s}.md`);try{let a=vO(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var wp=class{registry;readOnlyAdapter;hostKind;agentsDir;readFile;subagentSpawner;sysPromptCache=new Map;constructor(e){this.registry=e.registry,this.readOnlyAdapter=e.readOnlyAdapter,this.hostKind=e.hostKind,this.agentsDir=e.agentsDir??Hw(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>gO(r,"utf-8")),this.subagentSpawner=e.subagentSpawner}describe(e){return this.resolveDescriptor(e)}async requestTurn(e,r){let n=this.resolveDescriptor(e),o=performance.now();try{switch(n.transport){case"task-subagent":{if(!this.subagentSpawner)return this.buildFailure(e,o,"subagent spawner not wired (integration pending \u2014 T10/T12)");let s=await yp(this.subagentSpawner({agentName:n.agentName??e,prompt:r.prompt,system:r.system}),e);return this.buildSuccess(e,o,s.text)}case"cli-bridge":{let s=n.providerId??_p,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=Ww(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await yp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:Vw(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}case"read-only-chat":{let s=n.providerId??e,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`provider "${s}" not registered`);let a=n.agentName!==void 0?Ww(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await yp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:Vw(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}default:{let s=n.transport;return this.buildFailure(e,o,`unknown transport: ${String(s)}`)}}}catch(s){return this.buildFailure(e,o,M(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=_O(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:vp,agentName:r.agentName}:r}buildSuccess(e,r,n){return{participantId:e,text:n,latencyMs:Math.round(performance.now()-r),failed:!1}}buildFailure(e,r,n){return{participantId:e,text:"",latencyMs:Math.round(performance.now()-r),failed:!0,failureReason:n}}};function Kw(t){return new wp(t)}function Jw(t,e){return e(t)}var bO=/[.,!?;:]/g,wO=/\s+/g;function Gw(t){return t.toLowerCase().replace(bO," ").replace(wO," ").trim()}function Yw(t){return typeof t.location=="string"&&t.location.length>0}function Qw(t,e){if(e.length===0)return t;let r=new Set(t),n=t.slice();for(let o of e)r.has(o)||(r.add(o),n.push(o));return n}function xO(t){let e={id:t.id,proposerIds:t.proposerIds.slice(),title:t.title,severity:t.severity,roundOpened:t.roundOpened,status:t.status,votes:new Map};t.location!==void 0&&(e.location=t.location),t.description!==void 0&&(e.description=t.description),t.supersededBy!==void 0&&(e.supersededBy=t.supersededBy),t.mergedInto!==void 0&&(e.mergedInto=t.mergedInto);for(let[r,n]of t.votes)e.votes.set(r,{...n});return e}function SO(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=Gw(t.title)===Gw(e.title),s=t.severity===e.severity,a=Yw(t)&&Yw(e)&&t.location===e.location,c=[];if(o&&c.push("title"),s&&c.push("severity"),a&&c.push("location"),c.length===0)return{kind:"unrelated"};if(o&&s&&a)return{kind:"hard-merge"};let l;return o?s?l="location":l="severity":l="title",{kind:"alias",pair:{proposalA:t.id,proposalB:e.id,matchedFields:c,missingField:l}}}var io=class t{_proposals=new Map;_aliasCandidates=[];get proposals(){return this._proposals}get aliasCandidates(){return this._aliasCandidates.slice()}addProposal(e){if(this._proposals.has(e.id))throw new Error(`ProposalLedger.addProposal: duplicate id "${e.id}"`);let r={id:e.id,proposerIds:e.proposerIds.slice(),title:e.title,severity:e.severity,roundOpened:e.roundOpened,status:e.status??"open",votes:new Map};e.location!==void 0&&(r.location=e.location),e.description!==void 0&&(r.description=e.description),this._proposals.set(r.id,r)}recordVote(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.recordVote: unknown proposal id "${e}"`);o.votes.set(r,{...n}),o.proposerIds.includes(r)&&n.vote==="revise"&&o.status==="open"&&(o.status="withdrawn-by-author")}countRevisesThisRound(e,r){let n=this._proposals.get(e);if(!n)return 0;let o=0;for(let[s,i]of n.votes)i.vote==="revise"&&i.roundRecorded===r&&(n.proposerIds.includes(s)||(o+=1));return o}markSuperseded(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.markSuperseded: unknown old id "${e}"`);if(!this._proposals.has(r))throw new Error(`ProposalLedger.markSuperseded: successor id "${r}" not registered`);o.status="superseded",o.supersededBy=r;for(let s of o.votes.values())s.supersededAt===void 0&&(s.supersededAt=n)}applyAliasMerge(e,r){if(e===r)throw new Error(`ProposalLedger.applyAliasMerge: cannot merge id "${e}" into itself`);let n=this._proposals.get(e),o=this._proposals.get(r);if(!n)throw new Error(`ProposalLedger.applyAliasMerge: unknown primary id "${e}"`);if(!o)throw new Error(`ProposalLedger.applyAliasMerge: unknown alias id "${r}"`);n.proposerIds=Qw(n.proposerIds,o.proposerIds);for(let[s,i]of o.votes){let a=n.votes.get(s);if(!a){n.votes.set(s,{...i});continue}i.roundRecorded>a.roundRecorded&&n.votes.set(s,{...i})}o.status="merged",o.mergedInto=e;for(let s=this._aliasCandidates.length-1;s>=0;s-=1){let i=this._aliasCandidates[s];(i.proposalA===r||i.proposalB===r||i.proposalA===e||i.proposalB===e)&&this._aliasCandidates.splice(s,1)}}setStatus(e,r){let n=this._proposals.get(e);if(!n)throw new Error(`ProposalLedger.setStatus: unknown proposal id "${e}"`);n.status=r}aggregateRound(e,r,n=[]){let o=new Set(n),s=[];for(let i of this._proposals.values()){if(i.status!=="open")continue;let a={agree:0,disagree:0,abstain:0,revise:0,missing:0};for(let u of r){if(i.proposerIds.includes(u))continue;let l=i.votes.get(u);if(l===void 0||l.roundRecorded!==e){o.has(u)?a.abstain+=1:a.missing+=1;continue}switch(l.vote){case"agree":a.agree+=1;break;case"disagree":a.disagree+=1;break;case"abstain":a.abstain+=1;break;case"revise":a.revise+=1;break;default:{let d=l.vote}}}let c=$O(a);s.push({proposalId:i.id,tally:a,verdict:c})}return s}getOpenProposals(){return this.selectByStatus("open")}getConsensusProposals(){return this.selectByStatus("consensus")}getUnresolved(){return this.selectByStatus("unresolved")}selectByStatus(e){let r=[];for(let n of this._proposals.values())n.status===e&&r.push(xO(n));return r}toJSON(){let e=Array.from(this._proposals.values()).map(n=>{let o=[];for(let[i,a]of n.votes){let c={voter:i,vote:a.vote,roundRecorded:a.roundRecorded};a.reason!==void 0&&(c.reason=a.reason),a.supersededAt!==void 0&&(c.supersededAt=a.supersededAt),o.push(c)}let s={id:n.id,proposerIds:n.proposerIds.slice(),title:n.title,severity:n.severity,roundOpened:n.roundOpened,status:n.status,votes:o};return n.location!==void 0&&(s.location=n.location),n.description!==void 0&&(s.description=n.description),n.supersededBy!==void 0&&(s.supersededBy=n.supersededBy),n.mergedInto!==void 0&&(s.mergedInto=n.mergedInto),s}),r=this._aliasCandidates.map(n=>({proposalA:n.proposalA,proposalB:n.proposalB,matchedFields:n.matchedFields.slice(),missingField:n.missingField}));return{proposals:e,aliasCandidates:r}}static fromJSON(e){let r=new t,n=new Set;for(let o of e.proposals){if(n.has(o.id))throw new Error(`ProposalLedger.fromJSON: duplicate proposal id "${o.id}"`);n.add(o.id);let s={id:o.id,proposerIds:o.proposerIds.slice(),title:o.title,severity:o.severity,roundOpened:o.roundOpened,status:o.status,votes:new Map};o.location!==void 0&&(s.location=o.location),o.description!==void 0&&(s.description=o.description),o.supersededBy!==void 0&&(s.supersededBy=o.supersededBy),o.mergedInto!==void 0&&(s.mergedInto=o.mergedInto);for(let i of o.votes){let a={vote:i.vote,roundRecorded:i.roundRecorded};i.reason!==void 0&&(a.reason=i.reason),i.supersededAt!==void 0&&(a.supersededAt=i.supersededAt),s.votes.set(i.voter,a)}r._proposals.set(s.id,s)}for(let o of e.aliasCandidates)r._aliasCandidates.push({proposalA:o.proposalA,proposalB:o.proposalB,matchedFields:o.matchedFields.slice(),missingField:o.missingField});return r}_rawProposal(e){return this._proposals.get(e)}_pushAliasCandidate(e){this._aliasCandidates.push(e)}_extendProposers(e,r){let n=this._proposals.get(e);n&&(n.proposerIds=Qw(n.proposerIds,r))}_maybeReplaceDescription(e,r){let n=this._proposals.get(e);if(!n||r===void 0)return;let o=n.description??"";r.length>o.length&&(n.description=r)}};function $O(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function Xw(t){let e=new io,r=new Set;for(let s of t){if(r.has(s.id))throw new Error(`buildInitialLedger: duplicate proposal id "${s.id}"`);r.add(s.id),e.addProposal({id:s.id,proposerIds:[s.proposerId],title:s.title,severity:s.severity,...s.location!==void 0?{location:s.location}:{},...s.description!==void 0?{description:s.description}:{},roundOpened:s.roundOpened??1,status:"open"})}let n=new Set,o=t.map(s=>s.id);for(let s=0;s<o.length;s+=1){let i=o[s];if(n.has(i))continue;let a=e._rawProposal(i);if(a)for(let c=s+1;c<o.length;c+=1){let u=o[c];if(n.has(u))continue;let l=e._rawProposal(u);if(!l)continue;let d=SO(a,l);if(d.kind==="hard-merge"){e._extendProposers(i,l.proposerIds),e._maybeReplaceDescription(i,l.description),e._proposals.delete(u),n.add(u);continue}d.kind==="alias"&&e._pushAliasCandidate(d.pair)}}return{ledger:e,aliasCandidates:e.aliasCandidates}}var kO=new Set(lf);function PO(t){return kO.has(t)}var TO=new Set(["disagree","revise"]);function EO(t){let e=`<${ln}>`,r=`</${ln}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function RO(t){let e=`<${ln}>`;return t.includes(e)}var IO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function AO(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return IO[r]??e})}function CO(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=AO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function xp(t,e){let r=EO(t);if(!r)return RO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${ln}> without matching </${ln}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!ex(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!ex(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=CO(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.id,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({proposalId:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!PO(g)){l.push({proposalId:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({proposalId:m,reason:"unknown-id",raw:p.raw});continue}if(d.has(m)){l.push({proposalId:m,reason:"duplicate-id",raw:p.raw});continue}let y=f.reason,_=typeof y=="string"&&y.length>0?y:void 0;if(TO.has(g)&&_===void 0){d.add(m),l.push({proposalId:m,reason:"missing-reason",raw:p.raw});continue}d.add(m);let S={proposalId:m,vote:g};_!==void 0&&(S.reason=_),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}function ex(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var DO=Object.freeze(["same","different","unsure"]),zs="alias-votes",zO=new Set(DO);function OO(t){return zO.has(t)}function MO(t){let e=`<${zs}>`,r=`</${zs}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function jO(t){let e=`<${zs}>`;return t.includes(e)}var NO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function LO(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return NO[r]??e})}function FO(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=LO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function tx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Sp(t,e){let r=MO(t);if(!r)return jO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${zs}> without matching </${zs}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!tx(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!tx(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=FO(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.pair,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({pair:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!OO(g)){l.push({pair:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({pair:m,reason:"unknown-pair",raw:p.raw});continue}if(d.has(m)){l.push({pair:m,reason:"duplicate-pair",raw:p.raw});continue}let y=f.reason,_=typeof y=="string"&&y.length>0?y:void 0;d.add(m);let S={pair:m,vote:g};_!==void 0&&(S.reason=_),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}var ZO="__";function UO(t){return`${t.proposalA}${ZO}${t.proposalB}`}var qO=["You are participating in the alias clarification phase of a structured debate.","The moderator has detected the following proposal pairs that partially match","on title / severity / location but did not satisfy the automatic hard-merge","rule. For each pair, decide whether the two proposals describe the SAME","underlying issue or DIFFERENT issues. If you cannot tell from the material","given, answer `unsure` \u2014 there is no penalty for uncertainty here, this","phase is not the main debate."].join(" "),VO=["For every pair below, emit exactly one `<item>` element inside the","`<alias-votes>` block. The `pair` attribute must match the identifier","printed with each pair. The `vote` attribute must be one of:","`same`, `different`, `unsure`. A `reason` attribute is optional but","encouraged when you answer `different` or `unsure`."].join(" "),BO=["Response format \u2014 append the following block at the end of your reply","(moderator parses only this block; preamble is ignored):","","<alias-votes>",' <item pair="P1__P2" vote="same"/>',' <item pair="P3__P4" vote="different" reason="P3 concerns cache invalidation; P4 concerns read-through."/>',' <item pair="P5__P6" vote="unsure" reason="Insufficient detail on location."/>',"</alias-votes>"].join(`
292
+ `),WO="Candidate pairs:";function HO(t,e){return["Your previous response did not include a valid `<alias-votes>` block.",`Problem: ${e}`,"Reply with ONLY the `<alias-votes>` block. Do not include prose.","<alias-votes>",...t.map(r=>` <item pair="${r}" vote="same|different|unsure" reason="optional"/>`),"</alias-votes>"].join(`
293
+ `)}async function ix(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(UO),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=KO(e,o,s),c=await Promise.allSettled(r.map(async f=>{let m=await n(f,a);return{participantId:f,response:m}})),u=[],l=new Map;for(let f of s)l.set(f,{same:0,different:0,unsure:0,missing:0});for(let f=0;f<c.length;f+=1){let m=c[f],g=r[f];if(m.status==="rejected"){u.push({participantId:g,reason:sx(m.reason)}),gc(l,s);continue}let{response:y}=m.value;if(y.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),gc(l,s);continue}let _=Sp(y.text,s),S=new Set;if(!_.ok){let v=await n(g,HO(s,_.error.details!==void 0?`${_.error.kind}: ${_.error.details}`:_.error.kind)).catch(x=>({text:"",failed:!0,reason:sx(x)}));if(v.failed===!0){u.push({participantId:g,reason:"reason"in v&&typeof v.reason=="string"?v.reason:"retry failed"}),gc(l,s);continue}let k=Sp(v.text,s);if(!k.ok){u.push({participantId:g,reason:k.error.details!==void 0?`${k.error.kind}: ${k.error.details}`:k.error.kind}),gc(l,s);continue}for(let x of k.entries)ox(l,x),S.add(x.pair);for(let x of s)if(!S.has(x)){let z=l.get(x);z!==void 0&&(z.missing+=1)}continue}for(let v of _.entries)ox(l,v),S.add(v.pair);for(let v of s)if(!S.has(v)){let k=l.get(v);k!==void 0&&(k.missing+=1)}}let d=[],p=[];for(let f of s){let m=i.get(f),g=l.get(f);if(m===void 0||g===void 0)continue;let y=GO(g);if(y.kind==="merge"){let _=m.proposalA,S=m.proposalB;if(e.proposals.get(_)===void 0||e.proposals.get(S)===void 0)continue;e.applyAliasMerge(_,S),d.push({primary:_,alias:S,voteBreakdown:{...g}});continue}p.push({pair:m,voteBreakdown:{...g},reason:y.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function KO(t,e,r){let n=[];n.push(qO),n.push(""),n.push(VO),n.push(""),n.push(WO),n.push("");for(let o=0;o<e.length;o+=1){let s=e[o],i=r[o],a=t.proposals.get(s.proposalA),c=t.proposals.get(s.proposalB);n.push(`Pair ${o+1} \u2014 pair="${i}"`),n.push(` matched fields: ${s.matchedFields.join(", ")||"(none)"}`),n.push(` blocking field: ${s.missingField}`),n.push(" Proposal A:"),rx(n,a),n.push(" Proposal B:"),rx(n,c),n.push("")}return n.push(BO),n.join(`
294
+ `)}function rx(t,e){if(e===void 0){t.push(" (proposal unavailable \u2014 already removed from ledger)");return}if(t.push(` id: ${e.id}`),t.push(` title: ${e.title}`),t.push(` severity: ${e.severity}`),t.push(` location: ${e.location!==void 0&&e.location.length>0?e.location:"(empty)"}`),e.description!==void 0&&e.description.length>0){let r=JO(e.description);t.push(` description: ${r}`)}}var nx=400;function JO(t){return t.length<=nx?t:`${t.slice(0,nx)}\u2026`}function ox(t,e){let r=t.get(e.pair);if(r!==void 0)switch(e.vote){case"same":r.same+=1;break;case"different":r.different+=1;break;case"unsure":r.unsure+=1;break;default:{let n=e.vote}}}function gc(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function GO(t){return t.same===0&&t.different===0?{kind:"undecided",reason:"no-votes"}:t.same>t.different?{kind:"merge"}:t.same===t.different?{kind:"undecided",reason:"tie"}:{kind:"undecided",reason:"different-majority"}}function sx(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as YO}from"fs/promises";import{readFileSync as QO,existsSync as $p,unlinkSync as XO,mkdirSync as eM}from"fs";import{join as Os}from"path";var Pp=".approval.json";function kp(t){return`${t}${Pp}`}function tM(t){return t.endsWith(Pp)?t.slice(0,t.length-Pp.length):null}function ax(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+df).toISOString()}var ao=class{debatesDir;cache=new Map;hydrated=!1;constructor(e){if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=Os(e,Us)}getDebatesDir(){return this.debatesDir}async persist(e){if(!e||!e.sessionId)throw new Error("StructuredSessionRegistry.persist: snapshot.sessionId is required");if(e.schemaVersion!==1)throw new Error(`StructuredSessionRegistry.persist: unsupported schemaVersion=${e.schemaVersion}`);eM(this.debatesDir,{recursive:!0});let r=Os(this.debatesDir,kp(e.sessionId));Ue(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=Os(this.debatesDir,kp(e));if(!$p(n))return null;let o=this.readSnapshotFile(n);return o&&this.cache.set(e,o),o}async remove(e){this.cache.delete(e);let r=Os(this.debatesDir,kp(e));if($p(r))try{XO(r)}catch(n){if(n.code!=="ENOENT")throw n}}async hydrateFromDisk(){if(this.cache.clear(),!$p(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await YO(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=tM(r);if(!n)continue;let o=this.readSnapshotFile(Os(this.debatesDir,r));o&&o.sessionId===n&&this.cache.set(n,o)}this.hydrated=!0}get(e){return this.cache.get(e)}getAll(){return Array.from(this.cache.values())}async sweepTimeouts(e=new Date){let r=e.getTime(),n=[];for(let o of this.cache.values()){if(o.status!=="ready-for-approval")continue;let s=Date.parse(o.deadline);if(Number.isNaN(s)||r<=s)continue;let i={...o,status:"leader-timeout",terminalNote:o.terminalNote??"leader-timeout after approval window"};await this.persist(i),n.push(i)}return n}isHydrated(){return this.hydrated}readSnapshotFile(e){let r;try{r=QO(e,"utf-8")}catch(o){if(o.code==="ENOENT")return null;throw o}let n;try{n=JSON.parse(r)}catch{return console.warn(`[session-registry] skipping unparseable snapshot file: ${e}`),null}return rM(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function rM(t){if(!t||typeof t!="object")return!1;let e=t;return e.schemaVersion===1&&typeof e.sessionId=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.readyAt=="string"&&typeof e.deadline=="string"&&typeof e.config=="object"&&e.config!==null&&typeof e.rounds=="number"&&Array.isArray(e.aggregatedVotes)&&typeof e.documentPaths=="object"&&e.documentPaths!==null}function nM(t,e){let r=[];r.push(...iM(t,e)),r.push(""),r.push(...ux(t,e));let n=lx(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...dx(t,e)),r.push(""),r.push(...cM(t,e)),r.join(`
295
+ `)}function oM(t,e){let r=[];r.push(...ux(t,e));let n=uM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=lM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=dM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=lx(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...dx(t,e)),r.join(`
296
+ `)}function cx(){return{renderTerminal:nM,renderSynthesis:oM}}var sM=Object.freeze({running:"report.status.running","ready-for-approval":"report.status.readyForApproval",consensus:"report.status.consensus",escalated:"report.status.escalated",approved:"report.status.approved",rejected:"report.status.rejected","leader-timeout":"report.status.leaderTimeout",error:"report.status.error"});function iM(t,e){let r=e.t(sM[t.status]),n=e.t("report.header.topic"),o=e.t("report.header.participants"),s=e.t("report.header.individualDocs"),i=[`## ${n}: ${t.topic} (${t.rounds}/${t.maxRounds} \u2014 ${r})`,`## ${o}: ${t.participantIds.join(", ")}`,`## ${s}:`],a=Math.min(t.participantIds.length,t.individualPaths.length);for(let c=0;c<a;c+=1)i.push(` - ${t.participantIds[c]}: ${t.individualPaths[c]}`);return i}function ux(t,e){let r=[`## ${e.t("report.section.mainTable")}`,"",`| ${e.t("report.table.proposer")} | ${e.t("report.table.opinion")} | ${e.t("report.table.severity")} | ${e.t("report.table.agreement")} |`,"|---|---|---|---|"];for(let n of t.proposals){let o=n.proposerIds.join(", "),s=aM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function aM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function lx(t,e){if(t.dissentDetails.length===0)return[];let r=[`## ${e.t("report.section.dissentDetail")}`];for(let n of t.dissentDetails){r.push(""),r.push(`### ${n.proposalTitle} (${n.severity})`);for(let o of n.perParticipant)r.push(Tp(o))}return r}function Tp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function dx(t,e){let r=`| ${e.t("report.contribution.ai")} | ${e.t("report.contribution.proposed")} | ${e.t("report.contribution.accepted")} | ${e.t("report.contribution.revises")} | ${e.t("report.contribution.abstains")} |`,n=[`## ${e.t("report.section.contributionSummary")}`,"",r,"|---|---|---|---|---|"];for(let o of t.contributionSummary){let s=o.proposed===0?"\u2014":String(o.consensusReceived);n.push(`| ${o.participantId} | ${o.proposed} | ${s} | ${o.revisesProposed} | ${o.abstains} |`)}return n}function cM(t,e){let r=e.t("report.footer.synthesisPath"),n=e.t("report.footer.debatePath"),o=t.synthesisPath??e.t("report.footer.pendingSynthesis"),s=[`## ${r}: ${o}`,`## ${n}: ${t.debatePath}`];return t.status==="ready-for-approval"&&(s.push(""),s.push(e.t("approval.pending"))),s}function uM(t,e){let r=t.acceptedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.acceptedItems")}`];for(let o of r)n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.proposer")}:** ${o.proposerIds.join(", ")}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`),o.finalStatement.length>0&&(n.push(""),n.push(o.finalStatement));return n}function lM(t,e){let r=t.rejectedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.rejectedItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),o.rejectionReason.length>0&&(n.push(""),n.push(o.rejectionReason));for(let s of o.dissentVotes)n.push(Tp(s))}return n}function dM(t,e){let r=t.openItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.openItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`);for(let s of o.perParticipant)n.push(Tp(s))}return n}var co=class{deps;sessions=new Map;formatter=cx();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??pM)(),n=this.nowIso(),o=qw({topic:e.topic,...e.goal!==void 0?{goal:e.goal}:{},participants:e.participants,excludeParticipants:e.excludeParticipants??[],autoInjectSpecialists:e.autoInjectSpecialists??!0}),s=o.participants,i={topic:e.topic,scope:e.scope??e.topic,participants:s,excludeParticipants:e.excludeParticipants??[],leader:e.leader,maxRounds:e.maxRounds??Cc,locale:e.locale??this.deps.i18n.locale,autoInjectSpecialists:e.autoInjectSpecialists??!0},a=await this.deps.documentManager.createDebateDocument({topic:e.topic,providers:s.slice(),...e.goal!==void 0?{goal:e.goal}:{}}),c={sessionId:r,config:i,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],debateDocId:a.id,debateDocPath:a.path,individualPaths:{},createdAt:n,ledger:new io,rounds:0,maxRounds:i.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1};this.sessions.set(r,c);try{let u=await this.runIndividualPhase(c,o),{ledger:l}=Xw(u);c.ledger=l,c.nextProposalIndex=_M(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,px(c));return await this.deps.registry.persist(d),this.emitTrace(c,"debate_rfa",{status:d.status}),{sessionId:r,status:d.status,snapshot:d,terminalReport:this.renderTerminal(c,d)}}catch(u){let l=this.buildSnapshot(c,"error",yc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:yc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:yc(u)}}}async approve(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="approved"){if(!r.documentPaths.synthesis)throw new Error(`approve: session "${e.sessionId}" is marked approved but has no synthesis path recorded. Snapshot is inconsistent.`);let u=this.sessions.get(e.sessionId);return{snapshot:r,synthesisPath:r.documentPaths.synthesis,terminalReport:this.renderTerminal(u??null,r),idempotentReplay:!0}}Ep(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?this.buildReportData(n,r,e.leaderNote):mx(r,e.leaderNote),s=this.formatter.renderSynthesis(o,this.deps.i18n),i=(r.status==="escalated"||r.status==="ready-for-approval")&&r.status==="escalated"?"escalated":"consensus",a=await this.deps.documentManager.createSynthesis({sessionId:r.sessionId,topic:r.config.topic,status:i,rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:s,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}});await this.deps.documentManager.addComment(n?.debateDocId??vc(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});let c={...r,status:"approved",documentPaths:{...r.documentPaths,synthesis:a.path}};return await this.deps.registry.persist(c),this.emitTrace(n??null,"debate_approved",{sessionId:r.sessionId,synthesisPath:a.path}),{snapshot:c,synthesisPath:a.path,terminalReport:this.renderTerminal(n??null,c)}}async continueDebate(e){if(!Number.isInteger(e.additionalRounds)||e.additionalRounds<=0)throw new Error(`continueDebate: additionalRounds must be a positive integer (got ${e.additionalRounds})`);let r=await this.loadSnapshotOrThrow(e.sessionId);Ep(r,["ready-for-approval","escalated"],"continue");let n=this.sessions.get(e.sessionId);if(!n){if(!r.ledgerState)throw new Error(`continueDebate: snapshot for session "${e.sessionId}" is too old to resume after restart \u2014 missing ledgerState. Use approve or reject instead, or rerun the debate.`);n=this.rehydrateSessionContext(r),this.sessions.set(e.sessionId,n)}n.maxRounds=r.config.maxRounds+e.additionalRounds;for(let i of n.ledger.proposals.values())i.status;await this.runRoundLoop(n);let o=px(n),s=this.buildSnapshot(n,o);return await this.deps.registry.persist(s),this.emitTrace(n,"debate_continued",{additionalRounds:e.additionalRounds,status:s.status}),{snapshot:s,terminalReport:this.renderTerminal(n,s)}}async reject(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="rejected")return{snapshot:r,idempotentReplay:!0,...r.documentPaths.issue!==void 0?{issuePath:r.documentPaths.issue}:{}};Ep(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??vc(r);await this.deps.documentManager.addComment(o,{author:"moderator",content:this.formatRejectionFooter(e.reason)});let s;e.spawnIssue===!0&&(s=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...e.reason!==void 0?{reason:e.reason}:{},items:vM(r)})).path);let i={...r,status:"rejected",terminalNote:e.reason??r.terminalNote,documentPaths:{...r.documentPaths,...s!==void 0?{issue:s}:{}}};return await this.deps.registry.persist(i),this.emitTrace(n??null,"debate_rejected",{sessionId:r.sessionId,...s!==void 0?{issuePath:s}:{}}),{snapshot:i,...s!==void 0?{issuePath:s}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=vc(r);try{await this.deps.documentManager.addComment(n,{author:"moderator",content:this.formatLeaderTimeoutFooter(r)})}catch{}this.emitTrace(this.sessions.get(r.sessionId)??null,"debate_leader_timeout",{sessionId:r.sessionId})}}async runIndividualPhase(e,r){let n=PM(),o=TM(e),s=await Promise.allSettled(e.config.participants.map(async a=>{let c=await this.deps.bridge.requestTurn(a,{prompt:o,system:e.individualReviewPrompt??n,round:0,...e.files.length>0?{files:e.files}:{}});return{participantId:a,resp:c}})),i=[];for(let a of s){if(a.status==="rejected")continue;let{participantId:c,resp:u}=a.value,l=u.failed?`(no response: ${u.failureReason??"unknown"})`:u.text,d=await this.deps.documentManager.createIndividualReview({participantId:c,topic:e.config.topic,content:l,...e.files.length>0?{files:e.files}:{}});if(e.individualPaths[c]=d.path,u.failed)continue;let p=kM(u.text);for(let f of p){let m=fx(e,f.id);i.push({id:m,proposerId:c,title:f.title,severity:f.severity,...f.location!==void 0?{location:f.location}:{},...f.description!==void 0?{description:f.description}:{},roundOpened:1})}}return i}async runAliasClarificationPhase(e){let r=await ix({ledger:e.ledger,participantIds:e.config.participants,askParticipant:async(o,s)=>{let i=await this.deps.bridge.requestTurn(o,{prompt:s,round:0,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=CM(r,this.deps.i18n);n.length>0&&await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:n})}async runRoundLoop(e){for(;e.rounds<e.maxRounds;){if(e.ledger.getOpenProposals().map(p=>p.id).length===0)return;e.rounds+=1;let n=e.rounds,o=e.config.participants.filter(p=>!e.unavailableParticipants.has(p)),s=e.ledger.getOpenProposals(),i=e.pendingVoteWarnings,a=new Map,c=await Promise.allSettled(o.map(async p=>{let f={prompt:EM({round:n,maxRounds:e.maxRounds,topic:e.config.topic,scope:e.config.scope,openProposals:s,previousVoteIssues:i.get(p)}),round:n,...e.files.length>0?{files:e.files}:{}},m=await this.deps.bridge.requestTurn(p,f);return{participantId:p,request:f,resp:m}})),u=[],l=new Set;for(let p=0;p<c.length;p+=1){let f=c[p],m=o[p];if(f.status==="rejected"||f.value.resp.failed){this.registerFailure(e,m);let y=f.status==="rejected"?yc(f.reason):f.value.resp.failureReason??"unknown";u.push({participantId:m,text:`(no response: ${y})`,failed:!0});continue}l.add(m);let g=await this.parseVotesWithRetry(m,f.value.request,f.value.resp.text,s,n);if(u.push({participantId:m,text:g.displayText,failed:!g.ok}),!g.ok){this.registerFailure(e,m),a.set(m,g.warnings);continue}this.clearFailure(e,m);for(let y of g.parsed.entries)e.ledger.recordVote(y.proposalId,m,{vote:y.vote,roundRecorded:n,...y.reason!==void 0?{reason:y.reason}:{}});g.parsed.entryErrors.length>0&&a.set(m,IM(g.parsed.entryErrors))}e.pendingVoteWarnings=a;let d=e.ledger.aggregateRound(n,e.config.participants,Array.from(e.unavailableParticipants));for(let p of d){let f=e.ledger.proposals.get(p.proposalId);if(!f)continue;let m=e.config.participants.filter(g=>!f.proposerIds.includes(g)).length;if(mM(p.tally,m)){e.ledger.setStatus(p.proposalId,"consensus"),e.allAbstainCount.delete(p.proposalId);continue}if(hM(p.tally,m)){e.ledger.setStatus(p.proposalId,"rejected"),e.allAbstainCount.delete(p.proposalId);continue}if(gM(p.tally)){let g=(e.allAbstainCount.get(p.proposalId)??0)+1;e.allAbstainCount.set(p.proposalId,g),g>=zc&&(e.ledger.setStatus(p.proposalId,"unresolved"),e.allAbstainCount.delete(p.proposalId));continue}e.allAbstainCount.delete(p.proposalId)}for(let p of d){if(p.tally.revise===0)continue;let f=e.ledger.proposals.get(p.proposalId);if(!f||f.status!=="open"||e.ledger.countRevisesThisRound(p.proposalId,n)===0)continue;let g=this.synthesizeReviseSuccessor(e,f,n);e.reviseSuccessors.set(f.id,g)}if(await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:AM({round:n,maxRounds:e.maxRounds,openProposals:s,turns:u,aggregation:d,ledger:e.ledger})}),l.size===0)return}}async parseVotesWithRetry(e,r,n,o,s){let i=o.map(p=>p.id),a=xp(n,i);if(a.ok)return{ok:!0,parsed:a,displayText:n};let c={prompt:RM({openProposals:o,errorKind:a.error.kind,errorDetails:a.error.details}),round:s,...r.files!==void 0?{files:r.files}:{}},u=await this.deps.bridge.requestTurn(e,c);if(u.failed)return{ok:!1,displayText:`${n}
297
+
298
+ [retry failed: ${u.failureReason??"unknown"}]`,warnings:[`Missing or malformed <votes> block (${a.error.kind}). Retry failed: ${u.failureReason??"unknown"}.`]};let l=xp(u.text,i),d=`${n}
299
+
300
+ [retry response]
301
+ ${u.text}`;return l.ok?{ok:!0,parsed:l,displayText:d}:{ok:!1,displayText:d,warnings:[`Missing or malformed <votes> block (${l.error.kind}).${l.error.details?` ${l.error.details}`:""}`]}}registerFailure(e,r){let n=(e.consecutiveFailures.get(r)??0)+1;e.consecutiveFailures.set(r,n),n>=Dc&&e.unavailableParticipants.add(r)}clearFailure(e,r){e.consecutiveFailures.delete(r)}synthesizeReviseSuccessor(e,r,n){let o=fx(e),s=[];for(let[,a]of r.votes)a.vote==="revise"&&a.roundRecorded===n&&a.reason&&s.push(a.reason);let i=s.length>0?`Revised from ${r.id}: ${s.join(" / ")}`:`Revised from ${r.id}`;return e.ledger.addProposal({id:o,proposerIds:r.proposerIds,title:`${r.title} (revised)`,severity:r.severity,...r.location!==void 0?{location:r.location}:{},description:i,roundOpened:n+1}),e.ledger.markSuperseded(r.id,o,n),o}rehydrateSessionContext(e){if(!e.ledgerState)throw new Error(`rehydrateSessionContext: snapshot "${e.sessionId}" has no ledgerState`);let r=io.fromJSON(e.ledgerState),n=new Map;if(e.consecutiveFailuresByParticipant)for(let[a,c]of Object.entries(e.consecutiveFailuresByParticipant))c>0&&n.set(a,c);let o=new Set(e.unavailableParticipants??[]),s=0;for(let a of e.ledgerState.proposals.map(c=>c.id)){let c=a.match(/^P(\d+)$/);if(c){let u=Number.parseInt(c[1],10);Number.isFinite(u)&&u>s&&(s=u)}}return{sessionId:e.sessionId,config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],debateDocId:vc(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:r,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:n,unavailableParticipants:o,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:s+1}}buildSnapshot(e,r,n){let o=this.nowIso(),s=fM(r)?Jw(o,ax):o,i=this.snapshotAggregatedVotes(e),a={};for(let[u,l]of e.consecutiveFailures)l>0&&(a[u]=l);return{schemaVersion:1,sessionId:e.sessionId,status:r,createdAt:e.createdAt,readyAt:o,deadline:s,config:{...e.config,maxRounds:e.maxRounds},rounds:e.rounds,aggregatedVotes:i,documentPaths:{individual:{...e.individualPaths},debate:e.debateDocPath},ledgerState:e.ledger.toJSON(),...Object.keys(a).length>0?{consecutiveFailuresByParticipant:a}:{},...e.unavailableParticipants.size>0?{unavailableParticipants:Array.from(e.unavailableParticipants)}:{},...n!==void 0?{terminalNote:n}:{}}}snapshotAggregatedVotes(e){let r=[];for(let n of e.ledger.proposals.values()){if(n.status==="merged")continue;let o={};for(let[s,i]of n.votes)o[s]={vote:i.vote,roundRecorded:i.roundRecorded,...i.reason!==void 0?{reason:i.reason}:{}};r.push({proposalId:n.id,title:n.title,severity:n.severity,...n.location!==void 0?{location:n.location}:{},proposers:n.proposerIds,status:yM(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){let n=e?this.buildReportData(e,r):mx(r);return this.formatter.renderTerminal(n,this.deps.i18n)}buildReportData(e,r,n){let o=[],s=[],i=[],a=[],c=[];for(let l of e.ledger.proposals.values()){if(l.status==="merged"||l.status==="superseded")continue;let d=e.config.participants.filter(f=>!l.proposerIds.includes(f)),p=bM(l,d);o.push({proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,accepted:l.status==="consensus",...p.dissentSummary!==void 0?{dissentSummary:p.dissentSummary}:{}}),p.perParticipant.length>0&&l.status!=="consensus"&&s.push({proposalTitle:l.title,severity:l.severity,perParticipant:p.perParticipant}),l.status==="consensus"?i.push({id:l.id,proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,finalStatement:l.description??""}):l.status==="rejected"||l.status==="withdrawn-by-author"?a.push({id:l.id,title:l.title,severity:l.severity,rejectionReason:l.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:p.perParticipant}):(l.status==="open"||l.status==="unresolved")&&c.push({id:l.id,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,perParticipant:p.perParticipant})}let u=wM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:hx(r.status),participantIds:e.config.participants,individualPaths:Object.values(e.individualPaths),debatePath:e.debateDocPath,...r.documentPaths.synthesis!==void 0?{synthesisPath:r.documentPaths.synthesis}:{},proposals:o,contributionSummary:u,dissentDetails:s,acceptedItems:i,rejectedItems:a,openItems:c,...n!==void 0?{leaderNote:n}:{}}}nowIso(){return(this.deps.now?this.deps.now():new Date).toISOString()}async loadSnapshotOrThrow(e){let r=await this.deps.registry.load(e);if(!r)throw new Error(`Structured debate session "${e}" not found`);return r}formatApprovalFooter(e){let r=this.deps.i18n.t("moderator.narration.approved");if(!e)return r;let n=this.deps.i18n.t("synthesis.narration.leaderNote");return`${r}
296
302
 
297
303
  **${n}:** ${e}`}formatRejectionFooter(e){let r=this.deps.i18n.t("moderator.narration.rejected");return e?`${r}
298
304
 
299
- Reason: ${e}`:r}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 iM(){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 aM(t){return t==="ready-for-approval"||t==="escalated"}function cM(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 uM(t,e){if(e===0||t.agree>0||t.revise>0)return!1;let r=Math.ceil(e/2);return t.disagree>=r}function lM(t){return t.abstain>0&&t.agree===0&&t.disagree===0&&t.revise===0&&t.missing===0}function xp(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 dM(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 ux(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 hc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function Sp(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function pM(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 fM(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 mM(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 hM(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:ux(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 gM=/<proposals>([\s\S]*?)<\/proposals>/i,yM=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,vM=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function _M(t){let e=gM.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(yM.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp(vM.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 bM(){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(`
300
- `)}function wM(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(`
301
- `)}function xM(t){let e=[];e.push(`Structured debate \u2014 round ${t.round} of ${t.maxRounds}.`),e.push(`Topic: ${t.topic}`),e.push(`Scope: ${t.scope}`),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(`
302
- `)}function SM(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(`
303
- `)}function $M(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(`
304
- `)}var lx=18e4;function Ms(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${lx/1e3}s)`)),lx))])}function fx(t){return new Rn({tools:xi(),baseDir:t})}var $p,dx;function mx(t){return(!$p||dx!==t)&&($p=new ko,dx=t),$p}var Os;function gc(t,e){if(Os&&Os.registry===t&&Os.hostKind===e)return Os.bridge;let r=new Rn({tools:xi(),baseDir:process.cwd()}),n=Uw({registry:t,readOnlyAdapter:r,hostKind:e});return Os={bridge:n,registry:t,hostKind:e},n}var px=new Map;function hx(t){let e=px.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 px.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function gx(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=Io(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 yc(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function yx(t,e){let r=Qa.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),o=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(o.id,"in_progress");let s=e.debateEngine,i=s.create({topic:r.topic,providerIds:r.providers,goal:r.goal}),a=!!(r.goal&&r.validator),c=a?e.registry.get(r.validator):void 0,u=a?r.min_rounds??2:r.max_rounds;return(async()=>{try{let l="";for(let p=0;p<r.max_rounds;p++){for(let[f,m]of n){let g=s.buildPromptForProvider(i.id,f);l&&(g+=`
305
+ Reason: ${e}`:r}formatLeaderTimeoutFooter(e){let r=this.deps.i18n.t("moderator.narration.leaderTimeoutFooter"),n=Date.parse(e.readyAt),o=Date.parse(e.deadline),s=Number.isFinite(n)&&Number.isFinite(o)&&o>n?Math.round((o-n)/(3600*1e3)):24,i=this.deps.i18n.t("approval.timeout",{hours:s});return`## ${r}
306
+
307
+ ${i}`}emitTrace(e,r,n){if(this.deps.traceWriter)try{this.deps.traceWriter.write({traceId:e?.sessionId??"unknown",action:r,providerId:"moderator-engine",task:e?.config.topic??"",request:{promptSummary:JSON.stringify(n),fileCount:0},response:{success:!0,charLength:0},latencyMs:0})}catch{}}};function pM(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function px(t){for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function fM(t){return t==="ready-for-approval"||t==="escalated"}function mM(t,e){return e===0?t.agree===0&&!1:t.disagree>0||t.revise>0||t.missing>0||t.agree<1?!1:t.agree+t.abstain===e}function hM(t,e){if(e===0||t.agree>0||t.revise>0)return!1;let r=Math.ceil(e/2);return t.disagree>=r}function gM(t){return t.abstain>0&&t.agree===0&&t.disagree===0&&t.revise===0&&t.missing===0}function Ep(t,e,r){if(!e.includes(t.status))throw new Error(`Operation \`${r}\` is not allowed in state \`${t.status}\`. Allowed states: ${e.join(", ")}`)}function yM(t){switch(t){case"consensus":return"accepted";case"rejected":return"rejected";case"withdrawn-by-author":return"withdrawn-by-author";case"superseded":return"superseded";case"unresolved":return"inconclusive";default:return"open"}}function hx(t){switch(t){case"running":return"running";case"ready-for-approval":return"ready-for-approval";case"escalated":return"escalated";case"approved":return"approved";case"rejected":return"rejected";case"leader-timeout":return"leader-timeout";default:return"error"}}function yc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function vc(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function vM(t){let e=[];for(let r of t.aggregatedVotes){if(r.status==="accepted")continue;let n={agree:0,disagree:0,abstain:0,revise:0,total:0};for(let o of Object.values(r.votes))switch(n.total+=1,o.vote){case"agree":n.agree+=1;break;case"disagree":n.disagree+=1;break;case"abstain":n.abstain+=1;break;case"revise":n.revise+=1;break}e.push({title:r.title,severity:r.severity,status:r.status,proposerIds:r.proposers,...r.location!==void 0?{location:r.location}:{},votes:n})}return e}function _M(t){let e=0;for(let r of t){let n=r.id.match(/^P(\d+)$/);if(n){let o=Number.parseInt(n[1],10);Number.isFinite(o)&&o>e&&(e=o)}}return e+1}function fx(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function bM(t,e){let r=0,n=0,o=[];for(let a of e){let c=t.votes.get(a);if(!c){o.push({participantId:a,vote:"missing"});continue}o.push({participantId:a,vote:c.vote,...c.reason!==void 0?{reason:c.reason}:{}}),c.vote==="agree"?r+=1:c.vote==="abstain"&&(n+=1)}let s=e.length-n,i=[];for(let a of o)a.vote==="agree"||a.vote==="abstain"||i.push(`${a.participantId} ${a.vote}`);return{agree:r,denominator:s,perParticipant:o,...i.length>0?{dissentSummary:i.join(", ")}:{}}}function wM(t){let e=new Map;for(let r of t.config.participants)e.set(r,{proposed:0,consensusReceived:0,revisesProposed:0,abstains:0});for(let r of t.ledger.proposals.values())if(r.status!=="merged"){for(let n of r.proposerIds){let o=e.get(n);o&&(o.proposed+=1,r.status==="consensus"&&(o.consensusReceived+=1))}for(let[n,o]of r.votes){let s=e.get(n);s&&(o.vote==="revise"&&(s.revisesProposed+=1),o.vote==="abstain"&&(s.abstains+=1))}}return Array.from(e.entries()).map(([r,n])=>({participantId:r,proposed:n.proposed,consensusReceived:n.consensusReceived,revisesProposed:n.revisesProposed,abstains:n.abstains}))}function mx(t,e){let r=[],n=[],o=[],s=[],i=[];for(let a of t.aggregatedVotes){let c=t.config.participants.filter(m=>!a.proposers.includes(m)),u=c.map(m=>{let g=a.votes[m];return g?{participantId:m,vote:g.vote,...g.reason!==void 0?{reason:g.reason}:{}}:{participantId:m,vote:"missing"}}),l=0,d=0;for(let m of u)m.vote==="agree"?l+=1:m.vote==="abstain"&&(d+=1);let p=c.length-d;r.push({proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,accepted:a.status==="accepted"}),a.status==="accepted"?n.push({id:a.proposalId,proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,finalStatement:""}):a.status==="rejected"||a.status==="withdrawn-by-author"?o.push({id:a.proposalId,title:a.title,severity:a.severity,rejectionReason:a.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:u}):a.status==="open"&&s.push({id:a.proposalId,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,perParticipant:u}),u.some(m=>m.vote!=="agree"&&m.vote!=="abstain")&&a.status!=="accepted"&&i.push({proposalTitle:a.title,severity:a.severity,perParticipant:u})}return{topic:t.config.topic,rounds:t.rounds,maxRounds:t.config.maxRounds,status:hx(t.status),participantIds:t.config.participants,individualPaths:Object.values(t.documentPaths.individual),debatePath:t.documentPaths.debate,...t.documentPaths.synthesis!==void 0?{synthesisPath:t.documentPaths.synthesis}:{},proposals:r,contributionSummary:[],dissentDetails:i,acceptedItems:n,rejectedItems:o,openItems:s}}var xM=/<proposals>([\s\S]*?)<\/proposals>/i,SM=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,$M=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function kM(t){let e=xM.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(SM.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp($M.source,"g"),l;for(;(l=u.exec(i))!==null;)c[l[1]]=l[2];let d=c.id,p=c.title,f=c.severity;if(!d||!p||!f)continue;let m={id:d,title:p,severity:f,...c.location?{location:c.location}:{},...a.length>0?{description:a}:{}};n.push(m)}return n}function PM(){return["You are a participant in the individual-review phase of a structured multi-AI debate.","Produce a concise review of the stated topic and propose concrete findings.","Findings must be emitted inside a `<proposals>` XML block using the exact shape:","<proposals>",' <item id="P1" title="Short title" severity="CRITICAL|HIGH|MEDIUM|LOW" location="file:line or component">'," Multi-line description / evidence."," </item>","</proposals>","Rules:","- Do NOT emit `<votes>` in this phase.","- Use stable, unique `id` attributes (e.g. P1, P2).","- Severity labels are free-form but stick to the four levels above.","- Description text is AI-native; the moderator preserves it verbatim."].join(`
308
+ `)}function TM(t){let e=[];if(e.push(`Topic: ${t.config.topic}`),t.goal&&e.push(`Goal: ${t.goal}`),e.push(`Scope: ${t.config.scope}`),t.files.length>0){e.push("Files examined:");for(let r of t.files)e.push(` - ${r}`)}return t.individualReviewPrompt&&(e.push(""),e.push(t.individualReviewPrompt)),e.push(""),e.push("Return your review followed by the required `<proposals>` block."),e.join(`
309
+ `)}function EM(t){let e=[];if(e.push(`Structured debate \u2014 round ${t.round} of ${t.maxRounds}.`),e.push(`Topic: ${t.topic}`),e.push(`Scope: ${t.scope}`),t.previousVoteIssues&&t.previousVoteIssues.length>0){e.push(""),e.push("Previous round vote issues in your response:");for(let r of t.previousVoteIssues)e.push(`- ${r}`);e.push("Correct these issues in this round. Every open proposal still needs an explicit vote.")}e.push(""),e.push("Open proposals:");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`),r.description&&e.push(` ${r.description}`);e.push(""),e.push("Respond with your analysis followed by a `<votes>` block:"),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`. Vote on every open proposal."),e.join(`
310
+ `)}function RM(t){let e=[];e.push("Your previous response did not include a valid `<votes>` block."),e.push(`Problem: ${t.errorKind}.`),t.errorDetails&&e.push(`Details: ${t.errorDetails}`),e.push("Reply with ONLY the `<votes>` block. Do not include prose."),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`."),e.join(`
311
+ `)}function IM(t){return t.map(e=>`${e.proposalId??"unparsed entry"}: ${e.reason}`)}function AM(t){let e=[];e.push(`## Round ${t.round} / ${t.maxRounds}`),e.push(""),e.push("### Proposal Ledger (open at round start)");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`);e.push(""),e.push("### Turns");for(let r of t.turns)e.push(""),e.push(`#### [${r.participantId}]${r.failed?" (failed)":""}`),e.push(r.text);e.push(""),e.push("### Aggregation");for(let r of t.aggregation){let o=t.ledger.proposals.get(r.proposalId)?.status??"open";e.push(`- ${r.proposalId} \u2192 ${o} (${r.verdict}; agree=${r.tally.agree}, disagree=${r.tally.disagree}, abstain=${r.tally.abstain}, revise=${r.tally.revise}, missing=${r.tally.missing})`)}return e.join(`
312
+ `)}function CM(t,e){let n=[`## ${e.t("moderator.narration.aliasClarification")}`];if(t.mergesApplied.length>0){n.push(""),n.push("Applied merges:");for(let o of t.mergesApplied)n.push(`- ${o.alias} \u2192 ${o.primary} (same=${o.voteBreakdown.same}, different=${o.voteBreakdown.different}, unsure=${o.voteBreakdown.unsure}, missing=${o.voteBreakdown.missing})`)}if(t.undecided.length>0){n.push(""),n.push("Undecided pairs (kept separate):");for(let o of t.undecided)n.push(`- ${o.pair.proposalA} \u2194 ${o.pair.proposalB} (${o.reason})`)}return n.join(`
313
+ `)}var gx=18e4;function js(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${gx/1e3}s)`)),gx))])}function _x(t){return new Rn({tools:Si(),baseDir:t})}var Rp,yx;function bx(t){return(!Rp||yx!==t)&&(Rp=new Po,yx=t),Rp}var Ms;function _c(t,e){if(Ms&&Ms.registry===t&&Ms.hostKind===e)return Ms.bridge;let r=new Rn({tools:Si(),baseDir:process.cwd()}),n=Kw({registry:t,readOnlyAdapter:r,hostKind:e});return Ms={bridge:n,registry:t,hostKind:e},n}var vx=new Map;function wx(t){let e=vx.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new co({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return vx.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function xx(t,e,r){let n=.7;if(r&&e){for(let o of r)e.updateQuality(t.id,o.provider,{score:o.score,evaluator:"claude",feedback:o.feedback});n=r.reduce((o,s)=>o+s.score,0)/r.length}else if(e){let o=new Map;for(let a of t.turns){if(a.speaker==="claude")continue;let c=t.turns.filter(d=>d.turnNumber<a.turnNumber).map(d=>({speaker:d.speaker,content:d.content})),u=Ao(a.content,c,t.topic),l=o.get(a.speaker)??[];l.push(u.score),o.set(a.speaker,l)}let s=0,i=0;for(let[a,c]of o){let u=c.reduce((l,d)=>l+d,0)/c.length;e.updateQuality(t.id,a,{score:u,evaluator:"auto_rule_based",feedback:`Auto-aggregated from ${c.length} turns`}),s+=u,i++}i>0&&(n=s/i)}return{avgQuality:n}}function bc(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function Sx(t,e){let r=Qa.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),o=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(o.id,"in_progress");let s=e.debateEngine,i=s.create({topic:r.topic,providerIds:r.providers,goal:r.goal}),a=!!(r.goal&&r.validator),c=a?e.registry.get(r.validator):void 0,u=a?r.min_rounds??2:r.max_rounds;return(async()=>{try{let l="";for(let p=0;p<r.max_rounds;p++){for(let[f,m]of n){let g=s.buildPromptForProvider(i.id,f);l&&(g+=`
305
314
 
306
315
  Validator feedback from previous round:
307
- ${l}`);let y=await Ms(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}"
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}"
308
317
 
309
318
  Current discussion:
310
319
  ${f}
@@ -316,12 +325,12 @@ Respond in JSON:
316
325
  "accuracy": true/false,
317
326
  "consistency": true/false,
318
327
  "feedback": "..."
319
- }`,g=await Ms(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=yc(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=M(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
328
+ }`,g=await js(e.readOnlyAdapter.chat(c,{prompt:m}),c.id);try{let y=JSON.parse(g.text);if(y.goalAchievement&&y.completeness&&y.accuracy&&y.consistency)break;l=String(y.feedback??"")}catch{l=g.text}}}let d=bc(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=M(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
320
329
  **Session ID:** ${o.id}
321
330
  **Topic:** ${r.topic}
322
331
  **Participants:** ${r.providers.join(", ")}
323
332
 
324
- Use \`agent_debate_status\` to check progress.`}]}}async function vx(t,e){let r=Xa.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${n.id}
333
+ Use \`agent_debate_status\` to check progress.`}]}}async function $x(t,e){let r=ec.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${n.id}
325
334
  **Type:** ${n.type}
326
335
  **Status:** ${n.status}
327
336
  **Created:** ${n.createdAt}
@@ -331,7 +340,7 @@ Use \`agent_debate_status\` to check progress.`}]}}async function vx(t,e){let r=
331
340
 
332
341
  ---
333
342
 
334
- ${n.result}`),{content:[{type:"text",text:o}]}}async function _x(t,e){let r=Ya.parse(t),n=new To(e.registry,e.readOnlyAdapter);try{let o=await n.validate({items:r.items.map(i=>({providerId:i.provider,content:i.content,task:i.task})),validators:r.validators?.map(i=>e.registry.get(i)),criteria:r.criteria}),s=`**Cross-Validation ${o.overallPass?"PASSED":"FAILED"}**
343
+ ${n.result}`),{content:[{type:"text",text:o}]}}async function kx(t,e){let r=Xa.parse(t),n=new Eo(e.registry,e.readOnlyAdapter);try{let o=await n.validate({items:r.items.map(i=>({providerId:i.provider,content:i.content,task:i.task})),validators:r.validators?.map(i=>e.registry.get(i)),criteria:r.criteria}),s=`**Cross-Validation ${o.overallPass?"PASSED":"FAILED"}**
335
344
 
336
345
  `;for(let i of o.reviews)s+=`### ${i.targetProvider} reviewed by ${i.reviewerProvider}
337
346
  `,s+=`**Result:** ${i.passed?"PASS":"FAIL"}
@@ -341,13 +350,13 @@ ${n.result}`),{content:[{type:"text",text:o}]}}async function _x(t,e){let r=Ya.p
341
350
  `;return o.conflicts.length>0&&(s+=`## Conflicts
342
351
  ${o.conflicts.map(i=>`- ${i}`).join(`
343
352
  `)}
344
- `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${M(o)}`}],isError:!0}}}async function bx(t,e){let r=ec.parse(t);for(let s of r.providers)s!=="claude"&&e.registry.get(s);let n;return r.save_document&&(n=(await e.documentManager.createDebateDocument({topic:r.topic,providers:r.providers,goal:r.goal})).id),{content:[{type:"text",text:`**Debate created**
353
+ `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${M(o)}`}],isError:!0}}}async function Px(t,e){let r=tc.parse(t);for(let s of r.providers)s!=="claude"&&e.registry.get(s);let n;return r.save_document&&(n=(await e.documentManager.createDebateDocument({topic:r.topic,providers:r.providers,goal:r.goal})).id),{content:[{type:"text",text:`**Debate created**
345
354
  **Debate ID:** ${e.debateEngine.create({topic:r.topic,providerIds:r.providers,goal:r.goal,documentId:n}).id}
346
355
  **Topic:** ${r.topic}
347
356
  **Participants:** ${r.providers.join(", ")}${n?`
348
- **Document ID:** ${n}`:""}`}]}}async function wx(t,e){let r=tc.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};if(n.status==="concluded")return{content:[{type:"text",text:`Debate already concluded: ${r.debate_id}`}],isError:!0};if(r.provider==="claude")return r.claude_comment?(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}),{content:[{type:"text",text:`**[claude]:** ${r.claude_comment}`}]}):{content:[{type:"text",text:'provider: "claude" requires claude_comment to be set.'}],isError:!0};let o=e.registry.get(r.provider);r.claude_comment&&(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}));let s=e.debateEngine.buildPromptForProvider(r.debate_id,r.provider),i=e.traceWriter?{candidateProviders:n.providerIds,selectedProvider:r.provider,selectionReason:`Debate turn: ${r.provider}'s turn to respond`,memoryHit:!1}:void 0,a=performance.now(),c;try{c=await e.readOnlyAdapter.chat(o,{prompt:s})}catch(p){let f=Math.round(performance.now()-a),m=M(p);return e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!1,charLength:0,error:m},latencyMs:f,reasoning:i}),{content:[{type:"text",text:`**Debate turn failed (${r.provider}):** ${m}`}],isError:!0}}let u=Math.round(performance.now()-a);e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!0,charLength:c.text.length},latencyMs:u,reasoning:i});let l=n.turns.map(p=>({speaker:p.speaker,content:p.content})),d=Io(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}
357
+ **Document ID:** ${n}`:""}`}]}}async function Tx(t,e){let r=rc.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};if(n.status==="concluded")return{content:[{type:"text",text:`Debate already concluded: ${r.debate_id}`}],isError:!0};if(r.provider==="claude")return r.claude_comment?(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}),{content:[{type:"text",text:`**[claude]:** ${r.claude_comment}`}]}):{content:[{type:"text",text:'provider: "claude" requires claude_comment to be set.'}],isError:!0};let o=e.registry.get(r.provider);r.claude_comment&&(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}));let s=e.debateEngine.buildPromptForProvider(r.debate_id,r.provider),i=e.traceWriter?{candidateProviders:n.providerIds,selectedProvider:r.provider,selectionReason:`Debate turn: ${r.provider}'s turn to respond`,memoryHit:!1}:void 0,a=performance.now(),c;try{c=await e.readOnlyAdapter.chat(o,{prompt:s})}catch(p){let f=Math.round(performance.now()-a),m=M(p);return e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!1,charLength:0,error:m},latencyMs:f,reasoning:i}),{content:[{type:"text",text:`**Debate turn failed (${r.provider}):** ${m}`}],isError:!0}}let u=Math.round(performance.now()-a);e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!0,charLength:c.text.length},latencyMs:u,reasoning:i});let l=n.turns.map(p=>({speaker:p.speaker,content:p.content})),d=Ao(c.text,l,n.topic);return e.traceWriter&&e.traceWriter.updateQuality(n.id,r.provider,{score:d.score,evaluator:"auto_rule_based",feedback:JSON.stringify(d.breakdown)}),e.debateEngine.addTurn(r.debate_id,r.provider,c.text),n.documentId&&await e.documentManager.addComment(n.documentId,{author:r.provider,content:c.text}),{content:[{type:"text",text:`**[${r.provider}]:** ${c.text}
349
358
 
350
- _Quality: ${d.score.toFixed(2)}_`}]}}async function xx(t,e){let r=rc.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};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}=gx(n,e.traceWriter,r.quality_scores),s=yc(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
359
+ _Quality: ${d.score.toFixed(2)}_`}]}}async function Ex(t,e){let r=nc.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};r.summary&&(e.debateEngine.addTurn(r.debate_id,"claude",r.summary),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude (Summary)",content:r.summary})),e.debateEngine.conclude(r.debate_id);let{avgQuality:o}=xx(n,e.traceWriter,r.quality_scores),s=bc(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
351
360
  **Debate ID:** ${r.debate_id}
352
361
  **Topic:** ${n.topic}
353
362
  **Turns:** ${n.turns.length}`;return n.documentId&&(i+=`
@@ -355,13 +364,13 @@ _Quality: ${d.score.toFixed(2)}_`}]}}async function xx(t,e){let r=rc.parse(t),n=
355
364
 
356
365
  ---
357
366
 
358
- ${s}`,{content:[{type:"text",text:i}]}}async function Sx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function vc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function _c(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
367
+ ${s}`,{content:[{type:"text",text:i}]}}async function Rx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function wc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function xc(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
359
368
 
360
369
  **Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
361
370
 
362
371
  **Raw response:**
363
372
 
364
- ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function $x(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
373
+ ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function Ix(t,e,r,n,o){if(!e)return;let s=await t.documentManager.createReview({files:[],rules:[`Independent review from ${o.provider}`,`Parent document: ${e}`,...r?[`Debate ID: ${r}`]:[]],provider:o.provider,topic:`review-${e.slice(0,12)}`});await t.documentManager.addComment(s.id,{author:"Moderator",content:`## Review Target
365
374
 
366
375
  Parent document: ${e}${r?`
367
376
  Debate ID: ${r}`:""}
@@ -372,27 +381,27 @@ ${n}`});let i=o.rawResponse?`
372
381
 
373
382
  **Raw response:**
374
383
 
375
- ${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${vc(o.outcome)}**
384
+ ${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${wc(o.outcome)}**
376
385
 
377
- ${_c(o.outcome)}${i}`}),s.id}function kM(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
378
- ${uf}`}function PM(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=Rw.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 kx(t,e){let r=nc.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 v=new Set(e.debateEngine.getActiveProviders(r.debate_id)),x=[];for(let _ of n)if(_==="claude"||v.has(_))x.push(_);else{let P=(s.unavailableProviders??[]).find(S=>S.providerId===_);o.push({id:_,reason:P?`Marked unavailable for this debate: ${P.reason}`:"Not currently active in this debate."})}n=x}let a=o.length===0?"":`
379
- **Excluded Providers:** ${o.map(v=>`${v.id} (${v.reason})`).join(", ")}`;if(n.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${a}`}],isError:!0};let c=kM(r.review_prompt),u=[],l=n.map(async v=>{if(v==="claude")return null;let x=e.registry.get(v),_=`${c}
386
+ ${xc(o.outcome)}${i}`}),s.id}function DM(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
387
+ ${mf}`}function zM(t){let e=En(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=zw.safeParse(e);if(!r.success)return{kind:"parseError",rawResponse:t,reason:`Response JSON did not match review contract: ${r.error.message}`};let{agrees:n,feedback:o,suggestions:s}=r.data;return n?{kind:"agree",feedback:o,suggestions:s}:{kind:"disagree",feedback:o,suggestions:s}}async function Ax(t,e){let r=oc.parse(t),n=[...r.providers],o=[],s=r.debate_id?e.debateEngine.getState(r.debate_id):void 0,i=s?.documentId;if(r.debate_id&&s){let _=new Set(e.debateEngine.getActiveProviders(r.debate_id)),S=[];for(let v of n)if(v==="claude"||_.has(v))S.push(v);else{let k=(s.unavailableProviders??[]).find(x=>x.providerId===v);o.push({id:v,reason:k?`Marked unavailable for this debate: ${k.reason}`:"Not currently active in this debate."})}n=S}let a=o.length===0?"":`
388
+ **Excluded Providers:** ${o.map(_=>`${_.id} (${_.reason})`).join(", ")}`;if(n.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${a}`}],isError:!0};let c=DM(r.review_prompt),u=[],l=n.map(async _=>{if(_==="claude")return null;let S=e.registry.get(_),v=`${c}
380
389
 
381
390
  ---
382
391
 
383
- ${r.document}`,P,S;try{let O=await Ms(e.readOnlyAdapter.chat(x,{prompt:_}),v);P=O.text,S=PM(O.text)}catch(O){let Z=M(O);if(S={kind:"unavailable",reason:Z},r.debate_id&&s){let De=O instanceof me?`Provider reported unavailable: ${Z}`:`Chat failed: ${Z}`;e.debateEngine.markProviderUnavailable(r.debate_id,v,De),s=e.debateEngine.getState(r.debate_id)}}let z={provider:v,outcome:S,rawResponse:P};if(z.linkedDocumentId=await $x(e,i,r.debate_id,r.document,z),i){let O=_c(z.outcome),Z=z.linkedDocumentId?`
392
+ ${r.document}`,k,x;try{let O=await js(e.readOnlyAdapter.chat(S,{prompt:v}),_);k=O.text,x=zM(O.text)}catch(O){let Z=M(O);if(x={kind:"unavailable",reason:Z},r.debate_id&&s){let De=O instanceof me?`Provider reported unavailable: ${Z}`:`Chat failed: ${Z}`;e.debateEngine.markProviderUnavailable(r.debate_id,_,De),s=e.debateEngine.getState(r.debate_id)}}let z={provider:_,outcome:x,rawResponse:k};if(z.linkedDocumentId=await Ix(e,i,r.debate_id,r.document,z),i){let O=xc(z.outcome),Z=z.linkedDocumentId?`
384
393
 
385
- **Independent review document:** ${z.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${v} (review)`,content:`**${vc(z.outcome)}**
394
+ **Independent review document:** ${z.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${_} (review)`,content:`**${wc(z.outcome)}**
386
395
 
387
- ${O}${Z}`})}return z}),d=await Promise.all(l);for(let v of d)v&&u.push(v);let p=u.filter(v=>v.outcome.kind==="agree"||v.outcome.kind==="disagree"),f=u.length>0&&p.length===u.length&&p.every(v=>v.outcome.kind==="agree"),m=u.filter(v=>v.outcome.kind==="parseError"||v.outcome.kind==="unavailable"),y=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
396
+ ${O}${Z}`})}return z}),d=await Promise.all(l);for(let _ of d)_&&u.push(_);let p=u.filter(_=>_.outcome.kind==="agree"||_.outcome.kind==="disagree"),f=u.length>0&&p.length===u.length&&p.every(_=>_.outcome.kind==="agree"),m=u.filter(_=>_.outcome.kind==="parseError"||_.outcome.kind==="unavailable"),y=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
388
397
 
389
- `;for(let v of u)y+=`### ${v.provider}: ${vc(v.outcome)}
390
- `,y+=`${_c(v.outcome)}
391
- `,v.linkedDocumentId&&(y+=`**Independent review document:** ${v.linkedDocumentId}
398
+ `;for(let _ of u)y+=`### ${_.provider}: ${wc(_.outcome)}
399
+ `,y+=`${xc(_.outcome)}
400
+ `,_.linkedDocumentId&&(y+=`**Independent review document:** ${_.linkedDocumentId}
392
401
  `),y+=`
393
- `;if(!f){let v=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+=`---
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+=`---
394
403
 
395
- **Next step:** ${v}`}return await Sx(e,i,"Moderator (Review Aggregation)",y),{content:[{type:"text",text:y}]}}async function Px(t,e){let r=oc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};let n;try{n=e.cliWorkerManager.reviewChanges(r.task_id)}catch(s){return{content:[{type:"text",text:M(s)}],isError:!0}}let o=`**File Change Review**
404
+ **Next step:** ${_}`}return await Rx(e,i,"Moderator (Review Aggregation)",y),{content:[{type:"text",text:y}]}}async function Cx(t,e){let r=sc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};let n;try{n=e.cliWorkerManager.reviewChanges(r.task_id)}catch(s){return{content:[{type:"text",text:M(s)}],isError:!0}}let o=`**File Change Review**
396
405
  **Task ID:** ${r.task_id}
397
406
  **Worktree:** ${n.worktreePath}
398
407
  **Branch:** ${n.branch}
@@ -406,25 +415,25 @@ ${n.diffStat}
406
415
  ### Changes
407
416
  \`\`\`diff
408
417
  ${n.fullDiff}
409
- \`\`\``,{content:[{type:"text",text:o}]}}async function Tx(t,e){let r=sc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{let n=e.cliWorkerManager.acceptChanges(r.task_id,r.message);return{content:[{type:"text",text:`**Changes accepted**
418
+ \`\`\``,{content:[{type:"text",text:o}]}}async function Dx(t,e){let r=ic.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{let n=e.cliWorkerManager.acceptChanges(r.task_id,r.message);return{content:[{type:"text",text:`**Changes accepted**
410
419
  **Task ID:** ${r.task_id}
411
420
  **Merged files:** ${n.merged.length}
412
421
 
413
422
  ${n.merged.map(o=>`- ${o}`).join(`
414
- `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${M(n)}`}],isError:!0}}}async function Ex(t,e){let r=ic.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{e.cliWorkerManager.rejectChanges(r.task_id)}catch(o){return{content:[{type:"text",text:M(o)}],isError:!0}}let n=`**Changes rejected**
423
+ `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${M(n)}`}],isError:!0}}}async function zx(t,e){let r=ac.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{e.cliWorkerManager.rejectChanges(r.task_id)}catch(o){return{content:[{type:"text",text:M(o)}],isError:!0}}let n=`**Changes rejected**
415
424
  **Task ID:** ${r.task_id}`;return r.reason&&(n+=`
416
- **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as TM}from"path";var EM="unknown";async function Rx(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new ao(TM(n,fo)),s=gc(r.registry,EM),i=r.moderatorEngine??hx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:mx(n),readOnlyAdapter:fx(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return yx(e,a);case"agent_debate_status":return vx(e,a);case"agent_cross_validate":return _x(e,a);case"agent_debate_create":return bx(e,a);case"agent_debate_turn":return wx(e,a);case"agent_debate_conclude":return xx(e,a);case"agent_debate_review":return kx(e,a);case"agent_changes_review":return Px(e,a);case"agent_changes_accept":return Tx(e,a);case"agent_changes_reject":return Ex(e,a);case dc:return Iw(e,a);case no:return Aw(e,a);case oo:return Cw(e,a);case so:return Dw(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Pp={};Be(Pp,{getTools:()=>RM,handleTool:()=>NM});var Ix=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")}),Ax=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")}),Cx=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),Dx=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")}),zx=h.object({doc_id:h.string().describe("Document ID to read")}),Ox=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)")}),Mx=h.object({});function RM(){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(Ix)},{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(Ax)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:V(Cx)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:V(Dx)},{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(Ox)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:V(zx)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:V(Mx)}]}async function IM(t,e){let r=Ix.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
425
+ **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as OM}from"path";var MM="unknown";async function Ox(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new ao(OM(n,mo)),s=_c(r.registry,r.sessionContext?.hostKind??MM),i=r.moderatorEngine??wx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:bx(n),readOnlyAdapter:_x(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return Sx(e,a);case"agent_debate_status":return $x(e,a);case"agent_cross_validate":return kx(e,a);case"agent_debate_create":return Px(e,a);case"agent_debate_turn":return Tx(e,a);case"agent_debate_conclude":return Ex(e,a);case"agent_debate_review":return Ax(e,a);case"agent_changes_review":return Cx(e,a);case"agent_changes_accept":return Dx(e,a);case"agent_changes_reject":return zx(e,a);case pc:return Ow(e,a);case no:return Mw(e,a);case oo:return jw(e,a);case so:return Nw(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ap={};Ze(Ap,{getTools:()=>jM,handleTool:()=>BM});var Mx=h.object({files:h.array(h.string()).min(1).describe("File paths to include in the review"),rules:h.array(h.string()).describe("Review rules/guidelines to apply")}),jx=h.object({doc_id:h.string().describe("Document ID to request review for"),provider:h.union([h.string(),h.array(h.string()).min(1)]).describe("Provider ID(s) to perform the review")}),Nx=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),Lx=h.object({doc_id:h.string().describe("Document ID to comment on"),author:h.string().describe("Comment author name"),content:h.string().describe("Comment content")}),Fx=h.object({doc_id:h.string().describe("Document ID to read")}),Zx=h.object({title:h.string().describe("Document title"),content:h.string().describe("Document content (markdown)"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)")}),Ux=h.object({});function jM(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:V(Mx)},{name:"workspace_request_review",title:"Request Code Review",description:"Request AI provider(s) to perform a code review on an existing review document. Returns immediately with a session ID. Use workspace_review_status to check progress.",inputSchema:V(jx)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:V(Nx)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:V(Lx)},{name:"workspace_create_document",title:"Create Document",description:"Create a general-purpose workspace document with a title, content, and optional metadata. Use for independent analysis documents, aggregated reports, or any structured output.",inputSchema:V(Zx)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:V(Fx)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:V(Ux)}]}async function NM(t,e){let r=Mx.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
417
426
  **Document ID:** ${n.id}
418
427
  **Path:** ${n.path}
419
428
  **Files:** ${r.files.join(", ")}
420
- **Rules:** ${r.rules.length}`}]}}async function AM(t,e){let r=Ax.parse(t),n=Array.isArray(r.provider)?r.provider:[r.provider],o=[];for(let c of n){let u=e.registry.get(c);o.push({id:c,provider:u})}let s=await e.documentManager.read(r.doc_id),i=e.sessionManager.createSession("review",{doc_id:r.doc_id,providers:n,completed:[],failed:[]});e.sessionManager.updateSessionStatus(i.id,"in_progress");let a=o.map(async({id:c,provider:u})=>{try{let l=await u.chat({prompt:`Please review the following document and provide feedback:
429
+ **Rules:** ${r.rules.length}`}]}}async function LM(t,e){let r=jx.parse(t),n=Array.isArray(r.provider)?r.provider:[r.provider],o=[];for(let c of n){let u=e.registry.get(c);o.push({id:c,provider:u})}let s=await e.documentManager.read(r.doc_id),i=e.sessionManager.createSession("review",{doc_id:r.doc_id,providers:n,completed:[],failed:[]});e.sessionManager.updateSessionStatus(i.id,"in_progress");let a=o.map(async({id:c,provider:u})=>{try{let l=await u.chat({prompt:`Please review the following document and provide feedback:
421
430
 
422
- ${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=M(l);try{await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:`**Review failed:** ${d}`})}catch{}let p=e.sessionManager.getSession(i.id);if(p){let f=p.config.failed||[];f.push(c),p.config.failed=f}}});return Promise.all(a).then(()=>{try{let c=e.sessionManager.getSession(i.id),u=c?.config.completed||[],l=c?.config.failed||[],d=`Completed: ${u.join(", ")||"none"}. Failed: ${l.join(", ")||"none"}.`,p=ru({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
431
+ ${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=M(l);try{await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:`**Review failed:** ${d}`})}catch{}let p=e.sessionManager.getSession(i.id);if(p){let f=p.config.failed||[];f.push(c),p.config.failed=f}}});return Promise.all(a).then(()=>{try{let c=e.sessionManager.getSession(i.id),u=c?.config.completed||[],l=c?.config.failed||[],d=`Completed: ${u.join(", ")||"none"}. Failed: ${l.join(", ")||"none"}.`,p=su({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
423
432
  **Session ID:** ${i.id}
424
433
  **Document ID:** ${r.doc_id}
425
434
  **Providers:** ${n.join(", ")}
426
435
 
427
- Use \`workspace_review_status\` with session_id to check progress.`}]}}async function CM(t,e){let r=Cx.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=n.config.providers||[],s=n.config.completed||[],i=n.config.failed||[],a=o.filter(u=>!s.includes(u)&&!i.includes(u)),c=`**Review Session Status**
436
+ Use \`workspace_review_status\` with session_id to check progress.`}]}}async function FM(t,e){let r=Nx.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=n.config.providers||[],s=n.config.completed||[],i=n.config.failed||[],a=o.filter(u=>!s.includes(u)&&!i.includes(u)),c=`**Review Session Status**
428
437
  `;return c+=`**Session ID:** ${n.id}
429
438
  `,c+=`**Status:** ${n.status}
430
439
  `,c+=`**Document:** ${n.config.doc_id}
@@ -434,30 +443,30 @@ Use \`workspace_review_status\` with session_id to check progress.`}]}}async fun
434
443
  `,c+=`- Failed: ${i.join(", ")||"none"}
435
444
  `,c+=`- Pending: ${a.join(", ")||"none"}
436
445
  `,n.result&&(c+=`
437
- **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function DM(t,e){let r=Dx.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
446
+ **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function ZM(t,e){let r=Lx.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
438
447
  **Document ID:** ${r.doc_id}
439
448
  **Author:** ${r.author}
440
449
 
441
- ${r.content}`}]}}async function zM(t,e){let r=Ox.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata});return{content:[{type:"text",text:`**Document created**
450
+ ${r.content}`}]}}async function UM(t,e){let r=Zx.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata});return{content:[{type:"text",text:`**Document created**
442
451
  **Document ID:** ${n.id}
443
452
  **Path:** ${n.path}
444
- **Title:** ${r.title}`}]}}async function OM(t,e){let r=zx.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
453
+ **Title:** ${r.title}`}]}}async function qM(t,e){let r=Fx.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
445
454
  **Path:** ${n.path}
446
455
 
447
- ${n.content}`}]}}async function MM(t,e){Mx.parse(t);let r=await e.documentManager.list();if(r.length===0)return{content:[{type:"text",text:"No workspace documents found."}]};let n=`# Workspace Documents
456
+ ${n.content}`}]}}async function VM(t,e){Ux.parse(t);let r=await e.documentManager.list();if(r.length===0)return{content:[{type:"text",text:"No workspace documents found."}]};let n=`# Workspace Documents
448
457
 
449
458
  **Total:** ${r.length}
450
459
 
451
460
  `;for(let o of r){let s=o.content.slice(0,100).replace(/\n/g," ");n+=`- **${o.id}** \u2014 ${s}...
452
- `}return{content:[{type:"text",text:n}]}}async function NM(t,e,r){switch(t){case"workspace_create_review":return IM(e,r);case"workspace_request_review":return AM(e,r);case"workspace_review_status":return CM(e,r);case"workspace_add_comment":return DM(e,r);case"workspace_create_document":return zM(e,r);case"workspace_read":return OM(e,r);case"workspace_list":return MM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Tp={};Be(Tp,{getTools:()=>LM,handleTool:()=>UM});function bc(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var jM=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function LM(){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 FM(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
461
+ `}return{content:[{type:"text",text:n}]}}async function BM(t,e,r){switch(t){case"workspace_create_review":return NM(e,r);case"workspace_request_review":return LM(e,r);case"workspace_review_status":return FM(e,r);case"workspace_add_comment":return ZM(e,r);case"workspace_create_document":return UM(e,r);case"workspace_read":return qM(e,r);case"workspace_list":return VM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Cp={};Ze(Cp,{getTools:()=>HM,handleTool:()=>GM});function Sc(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var WM=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function HM(){return[{name:"provider_list",title:"List AI Providers",description:"List all registered AI providers with their availability status and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"provider_health",title:"Check Provider Health",description:"Run health checks on AI providers. Optionally specify a provider ID, or omit to check all.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider ID to check (omit to check all)"}},required:[]}}]}async function KM(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
453
462
 
454
463
  `;t.sessionContext&&(r+=`## Host Session
455
464
  `,r+=`- **Host:** ${t.sessionContext.hostId} (${t.sessionContext.hostKind})
456
465
  `,r+=`- **Leader Provider:** ${t.sessionContext.leaderProviderId}
457
- `,r+=`- **Execution Mode:** ${bc(t.sessionContext.executionMode,t.sessionContext.hostKind)}
466
+ `,r+=`- **Execution Mode:** ${Sc(t.sessionContext.executionMode,t.sessionContext.hostKind)}
458
467
  `,r+=`- **Participants:** ${t.sessionContext.participantProviderIds.join(", ")}
459
468
 
460
- `);for(let n of e){let o=n.isAvailable(),s=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):er(n,s),a=o?"Available":"Unavailable";r+=`## ${n.id} (${n.type})
469
+ `);for(let n of e){let o=n.isAvailable(),s=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):tr(n,s),a=o?"Available":"Unavailable";r+=`## ${n.id} (${n.type})
461
470
  `,r+=`- **Status:** ${a}
462
471
  `,r+=`- **Invocation:** ${i.invocation}
463
472
  `,r+=`- **Roles:** ${i.roles.join(", ")}
@@ -472,30 +481,32 @@ ${n.content}`}]}}async function MM(t,e){Mx.parse(t);let r=await e.documentManage
472
481
  `,s.strengths.length>0&&(r+=`- **Strengths:** ${s.strengths.join(", ")}
473
482
  `),s.models.length>0&&(r+=`- **Models:** ${s.models.map(c=>c.name).join(", ")}
474
483
  `),r+=`
475
- `}return{content:[{type:"text",text:r}]}}async function ZM(t,e){let r=jM.parse(t),n=r.provider?[e.registry.get(r.provider)]:e.registry.getAll();if(n.length===0)return{content:[{type:"text",text:"No providers to check."}]};let o=await Promise.all(n.map(async i=>{try{let a=await i.healthCheck();return{id:i.id,type:i.type,status:a.status,message:a.message,details:a.details,error:null}}catch(a){return{id:i.id,type:i.type,status:"error",message:M(a),details:void 0,error:M(a)}}})),s=`# Health Check Results
484
+ `}return{content:[{type:"text",text:r}]}}async function JM(t,e){let r=WM.parse(t),n=r.provider?[e.registry.get(r.provider)]:e.registry.getAll();if(n.length===0)return{content:[{type:"text",text:"No providers to check."}]};let o=await Promise.all(n.map(async i=>{try{let a=await i.healthCheck();return{id:i.id,type:i.type,status:a.status,message:a.message,details:a.details,error:null}}catch(a){return{id:i.id,type:i.type,status:"error",message:M(a),details:void 0,error:M(a)}}})),s=`# Health Check Results
476
485
 
477
486
  `;for(let i of o){let a=i.status==="ok"?"OK":i.status==="degraded"?"DEGRADED":"ERROR";s+=`## ${i.id} (${i.type})
478
487
  `,s+=`- **Status:** ${a}
479
488
  `,i.message&&(s+=`- **Message:** ${i.message}
480
489
  `),i.error&&(s+=`- **Error:** ${i.error}
481
490
  `),s+=`
482
- `}return{content:[{type:"text",text:s}]}}async function UM(t,e,r){switch(t){case"provider_list":return FM(r);case"provider_health":return ZM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ep={};Be(Ep,{getTools:()=>VM,handleTool:()=>HM});var qM=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function VM(){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 Nx(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 BM(t){let r=Nx(t).getModels();if(r.length===0)return{content:[{type:"text",text:"No models installed. Use `ollama_pull` to download a model."}]};let n=`# Installed Ollama Models (${r.length})
491
+ `}return{content:[{type:"text",text:s}]}}async function GM(t,e,r){switch(t){case"provider_list":return KM(r);case"provider_health":return JM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var zp={};Ze(zp,{getTools:()=>lj,handleTool:()=>fj});import{existsSync as nj,readFileSync as oj}from"fs";import{join as sj}from"path";import{readFileSync as YM,existsSync as QM}from"fs";import{join as XM}from"path";var ej={ollama:{executionPolicy:"workspace-write",config:{host:fo,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Vt("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Vt("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Vt("claude-cli"),config:{timeout:12e4}}};async function uo(){let t=[{id:"ollama",type:"ollama",provider:new qr({id:"ollama",host:fo})},{id:"gemini",type:"gemini-cli",provider:new Vr({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Br({id:"codex"})},{id:"claude-cli",type:"claude-cli",provider:new Wr({id:"claude-cli"})}],e=[],r=[];await Promise.all(t.map(async o=>{try{await o.provider.initialize()}catch{}let s=o.provider.isAvailable();e.push({id:o.id,type:o.type,available:s}),s&&r.push(o.provider)}));let n=["ollama","gemini","codex","claude-cli"];return e.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),r.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),{results:e,providers:r}}function tj(t){if(!QM(t))return null;try{return JSON.parse(YM(t,"utf-8"))}catch{return null}}function rj(t){return t==="auto"?"auto":"default-only"}function qx(t,e,r){let n=XM(t,"providers.config.json"),o=tj(n),s=new Set(r.enabledIds??[]),i=new Map((o?.providers??[]).map(m=>[m.id,m])),a=e.map(m=>{let g=ej[m.type]||{executionPolicy:Vt(m.type),config:{}},y=i.get(m.id);return i.delete(m.id),{id:m.id,type:m.type,enabled:m.available&&s.has(m.id),executionPolicy:y?.executionPolicy??g.executionPolicy,config:{...y?.config??g.config}}});for(let m of i.values())a.push({...m,enabled:s.has(m.id)?m.enabled:!1});if(a.length===0)throw new Error("No providers available to write into providers.config.json");let c=a.find(m=>m.enabled),u=r.defaultProvider&&a.some(m=>m.id===r.defaultProvider&&m.enabled)?r.defaultProvider:void 0,l={selectionPolicy:rj(r.selectionPolicy??o?.selectionPolicy),...u!==void 0?{defaultProvider:u}:c!==void 0?{defaultProvider:c.id}:{},...r.locale!==void 0?{locale:r.locale}:o?.locale!==void 0?{locale:o.locale}:{},providers:a},d=o?JSON.stringify(o):null,p=JSON.stringify(l),f=d===null?"created":d===p?"unchanged":"updated";return!r.dryRun&&f!=="unchanged"&&Ue(n,l),{action:f,path:n,config:l}}function Vx(t,e){Dp(t,e)}function Dp(t,e,r){let n=[];for(let o of t)e.has(o.id)||r?.excludeIds?.has(o.id)||r?.excludeTypes?.has(o.type)||(e.register(o),n.push(o));return n}var ij=h.object({}),aj=h.object({enabled_providers:h.array(h.string()).describe("Provider IDs to enable for Agestra workflows."),default_provider:h.string().optional().describe("Default provider ID. Must be one of the enabled providers when supplied."),locale:h.enum(["ko","en","ja","zh"]).describe("UI language for moderator/setup-facing text."),selection_policy:h.enum(["default-only","auto"]).optional().default("default-only").describe("Provider selection policy stored in providers.config.json."),dry_run:h.boolean().optional().default(!1).describe("When true, compute the resulting config without writing it to disk.")});function cj(t){let e=sj(t,"providers.config.json");if(!nj(e))return null;try{return JSON.parse(oj(e,"utf-8"))}catch{return null}}function uj(t){if(!t)return["Current config: not found"];let e=t.providers.filter(r=>r.enabled);return[`Current config: ${e.length>0?"present":"present (no providers enabled)"}`,`Enabled providers: ${e.length>0?e.map(r=>r.id).join(", "):"(none)"}`,`Default provider: ${t.defaultProvider??"(none)"}`,`Locale: ${t.locale??"(default)"}`,`Selection policy: ${t.selectionPolicy}`]}function lj(){return[{name:"setup_status",title:"Read Agestra Setup Status",description:"Detect available AI providers and show the current Agestra setup state from providers.config.json.",inputSchema:{type:"object",properties:{},required:[]}},{name:"setup_apply",title:"Apply Agestra Setup",description:"Write the selected AI providers and locale into providers.config.json for Agestra workflows.",inputSchema:{type:"object",properties:{enabled_providers:{type:"array",items:{type:"string"},description:"Provider IDs to enable"},default_provider:{type:"string",description:"Default provider ID"},locale:{type:"string",enum:["ko","en","ja","zh"],description:"UI locale"},selection_policy:{type:"string",enum:["default-only","auto"],description:"Stored provider selection policy"},dry_run:{type:"boolean",description:"Preview without writing providers.config.json"}},required:["enabled_providers","locale"]}}]}async function dj(t){let e=t.workspaceBaseDir??process.cwd(),r=cj(e),{results:n}=await uo(),o=["# Agestra Setup"];if(o.push(""),o.push(...uj(r)),o.push(""),o.push("Detected providers:"),n.length===0)o.push("- (none detected)");else for(let s of n)o.push(`- ${s.id} (${s.type}) \u2014 ${s.available?"available":"unavailable"}`);return{content:[{type:"text",text:o.join(`
492
+ `)}]}}async function pj(t,e){let r=aj.parse(t),n=e.workspaceBaseDir??process.cwd(),{results:o}=await uo();if(o.length===0)return{content:[{type:"text",text:"No AI providers were detected, so setup could not be applied."}],isError:!0};let s=new Set(o.filter(l=>l.available).map(l=>l.id)),i=r.enabled_providers.filter(l=>!s.has(l));if(i.length>0)return{content:[{type:"text",text:`These providers are not currently available and cannot be enabled: ${i.join(", ")}`}],isError:!0};if(r.default_provider!==void 0&&!r.enabled_providers.includes(r.default_provider))return{content:[{type:"text",text:"`default_provider` must be included in `enabled_providers`."}],isError:!0};let a=qx(n,o,{enabledIds:r.enabled_providers,...r.default_provider!==void 0?{defaultProvider:r.default_provider}:{},locale:r.locale,selectionPolicy:r.selection_policy,dryRun:r.dry_run}),c=a.config.providers.filter(l=>l.enabled);return{content:[{type:"text",text:[r.dry_run?"# Agestra Setup Preview":"# Agestra Setup Applied","",`Config path: ${a.path}`,`Action: ${a.action}`,`Enabled providers: ${c.length>0?c.map(l=>l.id).join(", "):"(none)"}`,`Default provider: ${a.config.defaultProvider??"(none)"}`,`Locale: ${a.config.locale??"(default)"}`,`Selection policy: ${a.config.selectionPolicy}`].join(`
493
+ `)}]}}async function fj(t,e,r){switch(t){case"setup_status":return ij.parse(e),dj(r);case"setup_apply":return pj(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Op={};Ze(Op,{getTools:()=>hj,handleTool:()=>vj});var mj=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function hj(){return[{name:"ollama_models",title:"List Ollama Models",description:"List installed Ollama models with their sizes and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"ollama_pull",title:"Pull Ollama Model",description:"Download (pull) a model from the Ollama registry.",inputSchema:{type:"object",properties:{model:{type:"string",description:"Model name to download (e.g. 'llama3', 'codellama')"}},required:["model"]}}]}function Bx(t){let e=t.ollamaProviderId||"ollama",r=t.registry.get(e);if(r.type!=="ollama")throw new Error(`Provider '${e}' is not an Ollama provider (type: ${r.type})`);return r}async function gj(t){let r=Bx(t).getModels();if(r.length===0)return{content:[{type:"text",text:"No models installed. Use `ollama_pull` to download a model."}]};let n=`# Installed Ollama Models (${r.length})
483
494
 
484
495
  `;for(let o of r){let s=(o.size/1e9).toFixed(1);n+=`## ${o.name}
485
496
  `,n+=`- **Size:** ${s} GB
486
497
  `,o.strengths.length>0&&(n+=`- **Strengths:** ${o.strengths.join(", ")}
487
498
  `),n+=`
488
- `}return{content:[{type:"text",text:n}]}}async function WM(t,e){let r=qM.parse(t),n=Nx(e);try{let o=n.getConnectionInfo().host,s=await fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.model,stream:!1})});if(!s.ok){let a=await s.text();return{content:[{type:"text",text:`**Pull failed**
499
+ `}return{content:[{type:"text",text:n}]}}async function yj(t,e){let r=mj.parse(t),n=Bx(e);try{let o=n.getConnectionInfo().host,s=await fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.model,stream:!1})});if(!s.ok){let a=await s.text();return{content:[{type:"text",text:`**Pull failed**
489
500
  **Model:** ${r.model}
490
501
  **Error:** HTTP ${s.status}: ${a}`}],isError:!0}}let i=await s.json();return{content:[{type:"text",text:`**Model pulled successfully**
491
502
  **Model:** ${r.model}
492
503
  **Status:** ${i.status||"success"}`}]}}catch(o){let s=M(o);return{content:[{type:"text",text:`**Pull failed**
493
504
  **Model:** ${r.model}
494
- **Error:** ${s}`}],isError:!0}}}async function HM(t,e,r){switch(t){case"ollama_models":return BM(r);case"ollama_pull":return WM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Rp={};Be(Rp,{getTools:()=>KM,handleTool:()=>QM});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(),Lx=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function KM(){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(Lx)}]}async function GM(t,e){let r=jx.parse(t);return{content:[{type:"text",text:`**Job submitted**
505
+ **Error:** ${s}`}],isError:!0}}}async function vj(t,e,r){switch(t){case"ollama_models":return gj(r);case"ollama_pull":return yj(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Mp={};Ze(Mp,{getTools:()=>_j,handleTool:()=>xj});var Wx=h.object({provider:h.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:h.string().describe("Prompt to send to the provider CLI"),timeout:h.number().int().positive().optional().describe("Timeout in ms (default: 300000)")}).strict(),Hx=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function _j(){return[{name:"cli_job_submit",title:"Submit CLI Job",description:"Submit a long-running CLI job to a provider. Returns a job ID immediately. Use cli_job_status to check progress.",inputSchema:V(Wx)},{name:"cli_job_status",title:"Check CLI Job Status",description:"Check the status of a CLI job. Returns state, output (on completion), and stderr.",inputSchema:V(Hx)}]}async function bj(t,e){let r=Wx.parse(t);return{content:[{type:"text",text:`**Job submitted**
495
506
  **Job ID:** ${e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout})}
496
507
  **Provider:** ${r.provider}
497
508
 
498
- Use \`cli_job_status\` with this job_id to check progress.`}]}}async function JM(t,e){let r=Lx.parse(t),n=e.jobManager.getResult(r.job_id);if(!n)return{content:[{type:"text",text:`Job not found: ${r.job_id}`}],isError:!0};let o=`**Job ID:** ${n.id}
509
+ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function wj(t,e){let r=Hx.parse(t),n=e.jobManager.getResult(r.job_id);if(!n)return{content:[{type:"text",text:`Job not found: ${r.job_id}`}],isError:!0};let o=`**Job ID:** ${n.id}
499
510
  **State:** ${n.state}`;return n.exitCode!==void 0&&(o+=`
500
511
  **Exit Code:** ${n.exitCode}`),n.output&&(o+=`
501
512
 
@@ -505,10 +516,10 @@ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function JM
505
516
  ${n.output}`),n.error&&(o+=`
506
517
 
507
518
  **Stderr:**
508
- ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function QM(t,e,r){switch(t){case"cli_job_submit":return GM(e,r);case"cli_job_status":return JM(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ip={};Be(Ip,{getTools:()=>YM,handleTool:()=>XM});var Fx=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)}),Zx=h.object({days_back:h.number().optional().default(30)}),Ux=h.object({trace_id:h.string()});function YM(){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(Fx)},{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(Zx)},{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(Ux)}]}async function XM(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 eN(e,n);case"trace_summary":return tN(e,n);case"trace_visualize":return rN(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function eN(t,e){let r=Fx.parse(t),n=e.traceWriter.query({providerId:r.provider_id,task:r.task,traceId:r.trace_id,daysBack:r.days_back,limit:r.limit});if(n.length===0)return{content:[{type:"text",text:"No trace records found."}]};let o=`**Trace Records** (${n.length} results)
519
+ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function xj(t,e,r){switch(t){case"cli_job_submit":return bj(e,r);case"cli_job_status":return wj(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var jp={};Ze(jp,{getTools:()=>Sj,handleTool:()=>$j});var Kx=h.object({provider_id:h.string().optional(),task:h.string().optional(),trace_id:h.string().optional(),days_back:h.number().optional().default(7),limit:h.number().optional().default(50)}),Jx=h.object({days_back:h.number().optional().default(30)}),Gx=h.object({trace_id:h.string()});function Sj(){return[{name:"trace_query",title:"Query Trace Records",description:"Query trace records with filtering. Returns recent provider interactions with latency, quality scores, and reasoning.",inputSchema:V(Kx)},{name:"trace_summary",title:"Summarize Trace Stats",description:"Get quality and performance stats per provider and task type. Shows average quality scores, latency, and success rates.",inputSchema:V(Jx)},{name:"trace_visualize",title:"Visualize Trace Flow",description:"Generate a Mermaid diagram showing the flow of a traced operation. Shows provider selection, execution, and quality assessment.",inputSchema:V(Gx)}]}async function $j(t,e,r){if(!r.traceWriter)return{content:[{type:"text",text:"Trace tools require traceWriter to be configured."}],isError:!0};let n={traceWriter:r.traceWriter};switch(t){case"trace_query":return kj(e,n);case"trace_summary":return Pj(e,n);case"trace_visualize":return Tj(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function kj(t,e){let r=Kx.parse(t),n=e.traceWriter.query({providerId:r.provider_id,task:r.task,traceId:r.trace_id,daysBack:r.days_back,limit:r.limit});if(n.length===0)return{content:[{type:"text",text:"No trace records found."}]};let o=`**Trace Records** (${n.length} results)
509
520
 
510
521
  `;for(let s of n)o+=`| ${s.timestamp?.slice(0,19)} | ${s.providerId} | ${s.task} | ${s.latencyMs}ms | ${s.response.success?"OK":"FAIL"} |`,s.quality&&(o+=` quality: ${s.quality.score}`),o+=`
511
- `;return{content:[{type:"text",text:o}]}}function tN(t,e){let r=Zx.parse(t),n=e.traceWriter.getQualityStats(r.days_back);if(n.size===0)return{content:[{type:"text",text:"No quality data available yet."}]};let o=`**Provider Quality Summary** (last ${r.days_back} days)
522
+ `;return{content:[{type:"text",text:o}]}}function Pj(t,e){let r=Jx.parse(t),n=e.traceWriter.getQualityStats(r.days_back);if(n.size===0)return{content:[{type:"text",text:"No quality data available yet."}]};let o=`**Provider Quality Summary** (last ${r.days_back} days)
512
523
 
513
524
  `;o+=`| Provider:Task | Avg Quality | Count | Avg Latency |
514
525
  `,o+=`|---|---|---|---|
@@ -516,23 +527,23 @@ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state=
516
527
  `;let s=new Map;for(let[a,c]of n){let u=a.split(":")[0],l=s.get(u)??{totalScore:0,count:0};l.totalScore+=c.avgScore*c.count,l.count+=c.count,s.set(u,l)}let i=["low","medium","high"];o+=`
517
528
  **Provider Difficulty Qualification**
518
529
 
519
- `,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Bs.medium}) | High (>=${Bs.high}) |
530
+ `,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Ws.medium}) | High (>=${Ws.high}) |
520
531
  `,o+=`|---|---|---|---|---|---|
521
- `;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Ws(u,d)?"YES":"no");o+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
522
- `}return{content:[{type:"text",text:o}]}}function rN(t,e){let r=Ux.parse(t),n=e.traceWriter.query({traceId:r.trace_id});if(n.length===0)return{content:[{type:"text",text:`No records found for trace: ${r.trace_id}`}],isError:!0};let o="```mermaid\ngraph LR\n";o+=` A[User Request] --> B{Provider Selection}
532
+ `;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Hs(u,d)?"YES":"no");o+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
533
+ `}return{content:[{type:"text",text:o}]}}function Tj(t,e){let r=Gx.parse(t),n=e.traceWriter.query({traceId:r.trace_id});if(n.length===0)return{content:[{type:"text",text:`No records found for trace: ${r.trace_id}`}],isError:!0};let o="```mermaid\ngraph LR\n";o+=` A[User Request] --> B{Provider Selection}
523
534
  `;for(let i=0;i<n.length;i++){let a=n[i],c=String.fromCharCode(67+i),u=a.reasoning?.selectionReason?a.reasoning.selectionReason.slice(0,40):`${a.latencyMs}ms`;o+=` B -->|${u}| ${c}[${a.providerId}]
524
535
  `;let l=a.response.success?`${a.response.charLength} chars, ${a.latencyMs}ms`:`FAIL: ${a.response.error?.slice(0,30)??"error"}`;o+=` ${c} --> ${c}R[${l}]
525
536
  `,a.quality&&(o+=` ${c}R --> ${c}Q[Quality: ${a.quality.score}]
526
537
  `)}return o+="```",{content:[{type:"text",text:`**Trace Visualization: ${r.trace_id}**
527
538
 
528
- ${o}`}]}}var Cp={};Be(Cp,{getTools:()=>iN,handleTool:()=>uN,resetCache:()=>aN});import{execFile as nN}from"child_process";import{promisify as oN}from"util";var Vx=oN(nN),Bx=5e3;async function Ns(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await Vx(e,[t],{timeout:Bx,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function sN(){try{return await Vx("git",["worktree","list"],{timeout:Bx,encoding:"utf-8"}),!0}catch{return!1}}function iN(){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 wc=null,Ap=null;function aN(){wc=null,Ap=null}async function cN(t,e){let r=JSON.stringify(e.sessionContext??null);if(wc&&Ap===r&&!t.force_refresh)return{content:[{type:"text",text:qx(wc)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(Q=>Q.isAvailable()),o=n.find(Q=>Q.type==="claude-cli"),s=n.find(Q=>Q.type==="claude-host"),i=n.find(Q=>Q.type==="codex-cli"),a=n.find(Q=>Q.type==="codex-host"),c=n.find(Q=>Q.type==="gemini-cli"),u=n.find(Q=>Q.type==="gemini-host"),[l,d,p,f,m,g]=await Promise.all([Ns("claude"),Ns("codex"),Ns("gemini"),Ns("tmux"),Ns("git"),sN()]),y=[],v=e.registry.getAll(),x=v.find(Q=>Q.id==="ollama");if(x?.isAvailable()){let Q=x.getCapabilities();for(let kt of Q.models){let wr=kt.sizeGb??0;y.push({name:kt.name,size_gb:wr,tier:Dc(wr)})}}let _=i!==void 0||c!==void 0,P=f!==null,S=m!==null&&g,z=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",O=v.some(Q=>Q.isAvailable()&&!Q.type.endsWith("-host")&&Q.id!=="ollama"),Z=[z?"leader_only":"claude_only"];(O||y.length>0)&&Z.push("independent","debate"),_&&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:_&&S,can_tmux_visible:P,can_parallel_workers:_&&S,max_parallel_workers:_?3:0,available_modes:Z}};return wc=De,Ap=r,{content:[{type:"text",text:qx(De)}]}}function qx(t){let e=`# Environment Check
539
+ ${o}`}]}}var Lp={};Ze(Lp,{getTools:()=>Aj,handleTool:()=>zj,resetCache:()=>Cj});import{execFile as Ej}from"child_process";import{promisify as Rj}from"util";var Qx=Rj(Ej),Xx=5e3;async function Ns(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await Qx(e,[t],{timeout:Xx,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function Ij(){try{return await Qx("git",["worktree","list"],{timeout:Xx,encoding:"utf-8"}),!0}catch{return!1}}function Aj(){return[{name:"environment_check",title:"Check Environment",description:"Check installed AI CLI tools (codex, gemini), infrastructure (tmux, git worktree), and Ollama models. Returns a capability map showing available v3 orchestration modes. Results are cached per session \u2014 call with force_refresh to re-check.",inputSchema:{type:"object",properties:{force_refresh:{type:"boolean",description:"Force re-check even if cached (default: false)"}},required:[]}}]}var $c=null,Np=null;function Cj(){$c=null,Np=null}async function Dj(t,e){let r=JSON.stringify(e.sessionContext??null);if($c&&Np===r&&!t.force_refresh)return{content:[{type:"text",text:Yx($c)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(Y=>Y.isAvailable()),o=n.find(Y=>Y.type==="claude-cli"),s=n.find(Y=>Y.type==="claude-host"),i=n.find(Y=>Y.type==="codex-cli"),a=n.find(Y=>Y.type==="codex-host"),c=n.find(Y=>Y.type==="gemini-cli"),u=n.find(Y=>Y.type==="gemini-host"),[l,d,p,f,m,g]=await Promise.all([Ns("claude"),Ns("codex"),Ns("gemini"),Ns("tmux"),Ns("git"),Ij()]),y=[],_=e.registry.getAll(),S=_.find(Y=>Y.id==="ollama");if(S?.isAvailable()){let Y=S.getCapabilities();for(let kt of Y.models){let wr=kt.sizeGb??0;y.push({name:kt.name,size_gb:wr,tier:Mc(wr)})}}let v=i!==void 0||c!==void 0,k=f!==null,x=m!==null&&g,z=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",O=_.some(Y=>Y.isAvailable()&&!Y.type.endsWith("-host")&&Y.id!=="ollama"),Z=[z?"leader_only":"claude_only"];(O||y.length>0)&&Z.push("independent","debate"),v&&x&&Z.push("team");let De={host:e.sessionContext?{id:e.sessionContext.hostId,kind:e.sessionContext.hostKind,leader_provider:e.sessionContext.leaderProviderId,execution_mode:e.sessionContext.executionMode,participant_providers:e.sessionContext.participantProviderIds}:void 0,providers:{ollama:{available:S?.isAvailable()??!1,models:y},claude:{available:o!==void 0||s!==void 0,cli_path:l,host_backed:s!==void 0},gemini:{available:c!==void 0||u!==void 0,cli_path:p,autonomous_capable:c!==void 0,host_backed:u!==void 0},codex:{available:i!==void 0||a!==void 0,cli_path:d,autonomous_capable:i!==void 0,host_backed:a!==void 0}},infrastructure:{tmux:{available:k,path:f},git:{available:m!==null,worktree_support:x}},capabilities:{can_autonomous_work:v&&x,can_tmux_visible:k,can_parallel_workers:v&&x,max_parallel_workers:v?3:0,available_modes:Z}};return $c=De,Np=r,{content:[{type:"text",text:Yx(De)}]}}function Yx(t){let e=`# Environment Check
529
540
 
530
541
  `;t.host&&(e+=`## Host Session
531
542
 
532
543
  `,e+=`- **Host:** ${t.host.id}
533
544
  `,e+=`- **Kind:** ${t.host.kind}
534
545
  `,e+=`- **Leader Provider:** ${t.host.leader_provider}
535
- `,e+=`- **Execution Mode:** ${bc(t.host.execution_mode,t.host.kind)}
546
+ `,e+=`- **Execution Mode:** ${Sc(t.host.execution_mode,t.host.kind)}
536
547
  `,e+=`- **Participants:** ${t.host.participant_providers.join(", ")}
537
548
 
538
549
  `),e+=`## Providers
@@ -556,14 +567,14 @@ ${o}`}]}}var Cp={};Be(Cp,{getTools:()=>iN,handleTool:()=>uN,resetCache:()=>aN});
556
567
  `,e+=`- **tmux visible:** ${t.capabilities.can_tmux_visible?"Yes":"No"}
557
568
  `,e+=`- **Parallel workers:** ${t.capabilities.can_parallel_workers?`Yes (max ${t.capabilities.max_parallel_workers})`:"No"}
558
569
  `,e+=`- **Available modes:** ${t.capabilities.available_modes.join(", ")}
559
- `,e}async function uN(t,e,r){return t==="environment_check"?cN(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Dp={};Be(Dp,{getTools:()=>lN,handleTool:()=>_N});var Wx=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(),Hx=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),Kx=h.object({worker_id:h.string().trim().min(1)}).strict(),Gx=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(Wx)},{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(Hx)},{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(Kx)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:V(Gx)}]}function xc(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 dN(t){let e=`# Worker Spawned
570
+ `,e}async function zj(t,e,r){return t==="environment_check"?Dj(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Fp={};Ze(Fp,{getTools:()=>Oj,handleTool:()=>Vj});var eS=h.object({provider:h.string().trim().min(1),task_description:h.string().trim().min(1),working_dir:h.string().trim().min(1),files_to_read:h.array(h.string().trim().min(1)).optional(),files_to_modify:h.array(h.string().trim().min(1)).optional(),constraints:h.string().optional(),success_criteria:h.array(h.string().trim().min(1)).optional(),timeout_minutes:h.number().positive().optional(),use_worktree:h.boolean().optional(),use_tmux:h.boolean().optional()}).strict(),tS=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),rS=h.object({worker_id:h.string().trim().min(1)}).strict(),nS=h.object({worker_id:h.string().trim().min(1)}).strict();function Oj(){return[{name:"cli_worker_spawn",title:"Spawn CLI Worker",description:"Spawn a CLI AI worker (any registered provider; use `provider_list` to discover available) in autonomous mode. The worker runs in the background and can be monitored with cli_worker_status.",inputSchema:V(eS)},{name:"cli_worker_status",title:"Check CLI Worker Status",description:"Get the status of a CLI worker by ID, or list all tracked workers if no ID is given.",inputSchema:V(tS)},{name:"cli_worker_collect",title:"Collect CLI Worker Results",description:"Collect results from a successful COLLECTING worker, a completed worker, or a failed CLI worker. Returns full output, git diff, and changed files.",inputSchema:V(rS)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:V(nS)}]}function kc(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function $t(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function Mj(t){let e=`# Worker Spawned
560
571
 
561
572
  `;return e+=`- **Worker ID:** ${t.workerId}
562
573
  `,e+=`- **Provider:** ${t.provider}
563
574
  `,e+=`- **State:** ${t.state}
564
575
  `,e+=`- **PID:** ${t.pid??"N/A"}
565
576
  `,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
566
- `),e}function pN(t){let e=`# Worker Status
577
+ `),e}function jj(t){let e=`# Worker Status
567
578
 
568
579
  `;return e+=`- **Worker ID:** ${t.workerId}
569
580
  `,e+=`- **Provider:** ${t.provider}
@@ -578,12 +589,12 @@ ${o}`}]}}var Cp={};Be(Cp,{getTools:()=>iN,handleTool:()=>uN,resetCache:()=>aN});
578
589
  \`\`\`
579
590
  ${t.outputTail}
580
591
  \`\`\`
581
- `),e}function fN(t){if(t.length===0)return`# Workers
592
+ `),e}function Nj(t){if(t.length===0)return`# Workers
582
593
 
583
594
  No tracked workers.`;let e=`# Workers (${t.length})
584
595
 
585
596
  `;for(let r of t)e+=`- **${r.workerId}** \u2014 ${r.provider} \u2014 ${r.state}`,r.pid&&(e+=` (PID ${r.pid})`),e+=`
586
- `;return e}function mN(t){let e=`# Worker Results
597
+ `;return e}function Lj(t){let e=`# Worker Results
587
598
 
588
599
  `;if(e+=`- **Worker ID:** ${t.workerId}
589
600
  `,e+=`- **State:** ${t.state}
@@ -605,7 +616,7 @@ ${t.gitDiff}
605
616
  \`\`\`
606
617
  ${t.outputFull}
607
618
  \`\`\`
608
- `),e}async function hN(t,e){let r=xc(e),n=Wx.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(dN(i))}catch(i){let a=M(i);return $t(`Error spawning worker: ${a}`,!0)}}async function gN(t,e){let r=xc(e),n=Hx.parse(t);if(!n.worker_id){let s=r.listAll();return $t(fN(s))}let o=r.getStatus(n.worker_id);return o?$t(pN(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function yN(t,e){let r=xc(e),n=Kx.parse(t),o=r.collect(n.worker_id);return o?$t(mN(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function vN(t,e){let r=xc(e),n=Gx.parse(t);return r.stop(n.worker_id),$t(`Stop signal sent to worker: ${n.worker_id}`)}async function _N(t,e,r){try{switch(t){case"cli_worker_spawn":return await hN(e??{},r);case"cli_worker_status":return await gN(e??{},r);case"cli_worker_collect":return await yN(e??{},r);case"cli_worker_stop":return await vN(e??{},r);default:return $t(`Unknown tool: ${t}`,!0)}}catch(n){let o=M(n);return $t(`Error: ${o}`,!0)}}var zp={};Be(zp,{getTools:()=>bN,handleTool:()=>xN});var Jx=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 bN(){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(Jx)}]}function wN(t){let e=`# Auto QA
619
+ `),e}async function Fj(t,e){let r=kc(e),n=eS.parse(t),o=r.knownProviders();if(!o.includes(n.provider))return $t(`Unknown provider: "${n.provider}". Known: [${o.join(", ")}]`,!0);let s={provider:n.provider,taskDescription:n.task_description,workingDir:n.working_dir,filesToRead:n.files_to_read,filesToModify:n.files_to_modify,constraints:n.constraints,successCriteria:n.success_criteria,timeoutMinutes:n.timeout_minutes,useWorktree:n.use_worktree,useTmux:n.use_tmux};try{let i=r.spawn(s);return $t(Mj(i))}catch(i){let a=M(i);return $t(`Error spawning worker: ${a}`,!0)}}async function Zj(t,e){let r=kc(e),n=tS.parse(t);if(!n.worker_id){let s=r.listAll();return $t(Nj(s))}let o=r.getStatus(n.worker_id);return o?$t(jj(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function Uj(t,e){let r=kc(e),n=rS.parse(t),o=r.collect(n.worker_id);return o?$t(Lj(o)):$t(`Worker not found: ${n.worker_id}`,!0)}async function qj(t,e){let r=kc(e),n=nS.parse(t);return r.stop(n.worker_id),$t(`Stop signal sent to worker: ${n.worker_id}`)}async function Vj(t,e,r){try{switch(t){case"cli_worker_spawn":return await Fj(e??{},r);case"cli_worker_status":return await Zj(e??{},r);case"cli_worker_collect":return await Uj(e??{},r);case"cli_worker_stop":return await qj(e??{},r);default:return $t(`Unknown tool: ${t}`,!0)}}catch(n){let o=M(n);return $t(`Error: ${o}`,!0)}}var Zp={};Ze(Zp,{getTools:()=>Bj,handleTool:()=>Hj});var oS=h.object({design_doc:h.string().optional().describe("Optional design document path to verify against"),build_profile:h.enum(["auto","tsc","vitest","npm-build","npm-test"]).optional().describe("QA build profile to execute. Defaults to 'auto' which detects from project structure."),timeout_ms:h.number().int().positive().optional().describe("Timeout per command in milliseconds")}).strict();function Bj(){return[{name:"qa_run",title:"Run Auto QA",description:"Run automatic QA for the current project. Detects build/test commands, optionally includes a design document reference, and returns a PASS/FAIL summary with captured output.",inputSchema:V(oS)}]}function Wj(t){let e=`# Auto QA
609
620
 
610
621
  ${t.summary}
611
622
  `;return t.designDoc&&(e+=`
@@ -622,12 +633,12 @@ ${t.buildOutput||"(no output)"}
622
633
  \`\`\`
623
634
  ${t.testOutput||"(no output)"}
624
635
  \`\`\`
625
- `,e}async function xN(t,e,r){if(t==="qa_run"){let n=Jx.parse(e??{}),s=await new Ro(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:wN(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Xx=[pp,kp,Pp,Tp,Ep,Rp,Ip,Cp,Dp,zp];function eS(){let t=[];for(let e of Xx)t.push(...e.getTools());return t}var Yx=new Map;function $N(t){return t.sessionId??"__default__"}function kN(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return SN(e.uri)}catch{}}async function PN(t,e,r){let n=$N(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=kN(o.roots);if(s)return Yx.set(n,s),s}catch{}return Yx.get(n)??e.workspaceBaseDir??process.cwd()}function TN(t,e){return t.filter(r=>tS(r.name,e))}function EN(t,e){let r=er(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return Xs(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=>EN(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 RN(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 Op=null;function IN(){if(Op)return Op;let t=new Map;for(let e of Xx)for(let r of e.getTools())t.set(r.name,e);return Op=t,t}function rS(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:RN(r.text,51200)+`
636
+ `,e}async function Hj(t,e,r){if(t==="qa_run"){let n=oS.parse(e??{}),s=await new Io(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:Wj(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var aS=[hp,Ip,Ap,Cp,zp,Op,Mp,jp,Lp,Fp,Zp];function cS(){let t=[];for(let e of aS)t.push(...e.getTools());return t}var iS=new Map;function Jj(t){return t.sessionId??"__default__"}function Gj(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return Kj(e.uri)}catch{}}async function Yj(t,e,r){let n=Jj(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=Gj(o.roots);if(s)return iS.set(n,s),s}catch{}return iS.get(n)??e.workspaceBaseDir??process.cwd()}function Qj(t,e){return t.filter(r=>uS(r.name,e))}function Xj(t,e){let r=tr(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return ei(n)}function uS(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>Xj(i,e.providerPolicies));return t.startsWith("ollama_")?o:t.startsWith("cli_worker_")||t.startsWith("agent_changes_")?s&&e.cliWorkerManager!==void 0:t.startsWith("ai_")||t.startsWith("agent_debate_")||t==="agent_cross_validate"?n:!0}function eN(t,e){let r=[],n=0;for(let o of t){let s=Buffer.byteLength(o,"utf-8");if(n+s>e)break;r.push(o),n+=s}return r.join("")}var Up=null;function tN(){if(Up)return Up;let t=new Map;for(let e of aS)for(let r of e.getTools())t.set(r.name,e);return Up=t,t}function lS(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:eN(r.text,51200)+`
626
637
 
627
- ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function nS(t,e,r){let o=IN().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 rS(i)}function Mp(t){let e=new Ka({name:"agestra",version:Bp},{capabilities:{tools:{}}});return e.setRequestHandler(ul,async()=>({tools:TN(eS(),t)})),e.setRequestHandler(ts,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await PN(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await nS(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${M(i)}`}],isError:!0}}}),e}async function Np(t){let e=new Ja;await t.connect(e)}function oS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function AN(t){return Array.isArray(t)?t.filter(oS).map(e=>e.text).join(`
638
+ ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function dS(t,e,r){let o=tN().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!uS(t,r))return{content:[{type:"text",text:`Tool unavailable in current environment: ${t}`}],isError:!0};let s={registry:r.registry,sessionManager:r.sessionManager,documentManager:r.documentManager,jobManager:r.jobManager,traceWriter:r.traceWriter,qualityStatsProvider:r.qualityStatsProvider,cliWorkerManager:r.cliWorkerManager,sessionContext:r.resolveSessionContext?.()??r.sessionContext,workspaceBaseDir:r.workspaceBaseDir,i18n:r.i18n,structuredSessionRegistry:r.structuredSessionRegistry,moderatorEngine:r.moderatorEngine},i=await o.handleTool(t,e,s);return lS(i)}function qp(t){let e=new Ja({name:"agestra",version:Gp},{capabilities:{tools:{}}});return e.setRequestHandler(pl,async()=>({tools:Qj(cS(),t)})),e.setRequestHandler(rs,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await Yj(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await dS(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${M(i)}`}],isError:!0}}}),e}async function Vp(t){let e=new Ya;await t.connect(e)}function pS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function rN(t){return Array.isArray(t)?t.filter(pS).map(e=>e.text).join(`
628
639
 
629
- `).trim():oS(t)?t.text:""}function sS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function iS(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function uo(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function jp(t,e,r){let n=()=>uo(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:sS(o.metadata,"maxTokens")??4096,temperature:sS(o.metadata,"temperature"),modelPreferences:iS(o.metadata,"model")?{hints:[{name:iS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=AN(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 Sc(t,e="claude"){return jp(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function $c(t,e="codex-host"){return jp(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function kc(t,e="gemini-host"){return jp(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var CN=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new mi({id:e,bridge:Sc(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new hi({id:e,bridge:$c(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new gi({id:e,bridge:kc(t,e)})}];function lo(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function DN(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function zN(t,e){switch(t){case"claude-code":return lo(e,"claude-host","claude");case"codex-cli":return lo(e,"codex-host","codex-host");case"gemini-cli":return lo(e,"gemini-host","gemini-host");default:return}}function ON(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 Lp(t,e){let r=()=>uo(t.getClientVersion()?.name),n=()=>DN(r()),o=()=>zN(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=lo(e,"claude-host","claude");return Sc(t,s)}case"codex-cli":{let s=lo(e,"codex-host","codex-host");return $c(t,s)}case"gemini-cli":{let s=lo(e,"gemini-host","gemini-host");return kc(t,s)}default:return null}},createHostProviders(){let s=r();return CN.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??sr(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:ON(i,c.id)}}}}async function Fp(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 Zp(t,e){let r=typeof e.getAvailableDescriptors=="function"?e.getAvailableDescriptors():e.getAvailable().map(n=>typeof e.getDescriptor=="function"?e.getDescriptor(n.id):{id:n.id,type:n.type,invocation:"unknown",roles:["participant"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0,supportsToolUse:n.getCapabilities().supportsToolUse});return t.createSessionContext?.(r)}var zW={ollama:{executionPolicy:"workspace-write",config:{host:po,defaultModel:"auto"}},"gemini-cli":{executionPolicy:sr("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:sr("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:sr("claude-cli"),config:{timeout:12e4}}};async function Up(){let t=[{id:"ollama",type:"ollama",provider:new qr({id:"ollama",host:po})},{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 aS(t,e){qp(t,e)}function qp(t,e,r){let n=[];for(let o of t)e.has(o.id)||r?.excludeIds?.has(o.id)||r?.excludeTypes?.has(o.type)||(e.register(o),n.push(o));return n}import{existsSync as cS}from"fs";import{dirname as dS,join as uS,resolve as pS}from"path";import{fileURLToPath as MN}from"url";function NN(t){return cS(uS(t,"package.json"))&&cS(uS(t,"AGENTS.md"))}function lS(t){let e=pS(t);for(;;){if(NN(e))return e;let r=dS(e);if(r===e)return null;e=r}}function jN(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return pS(t);let e=dS(MN(import.meta.url));return lS(process.cwd())??lS(e)??process.cwd()}function fS(){let t=jN();return process.cwd()!==t&&process.chdir(t),t}var mS={ollama:t=>new qr({id:t.id,host:t.config?.host||po}),"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 ZN(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 Up(),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(aS(o,t),r(`Auto-detected ${s.length} provider(s): ${s.map(i=>i.id).join(", ")}`),{detected:s.length})}catch(n){return r(`Auto-detect failed (non-fatal): ${M(n)}`),{detected:0}}}async function UN(){let t=_=>process.stderr.write(`[mcp-server] ${_}
630
- `),e=fS(),r=Pc(e,"providers.config.json"),n;try{let _=LN(r,"utf-8");n=JSON.parse(_)}catch(_){t(`Warning: Could not load ${r}: ${M(_)}`),t("Starting with empty provider registry."),n=null}let o=new Hs,s=null;if(n)try{s=Sf(n)}catch(_){t(`Warning: Invalid provider config in ${r}: ${M(_)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}if(s){let _=s.enabledProviders.map(S=>{let z=mS[S.type];if(!z)return t(`Unknown provider type: ${S.type} (id: ${S.id}), skipping`),null;let O=z(S);return{pc:S,provider:O}}).filter(S=>S!==null),P=await Promise.allSettled(_.map(async({pc:S,provider:z})=>(await z.initialize(),{pc:S,provider:z})));for(let S of P)if(S.status==="fulfilled"){let{pc:z,provider:O}=S.value;o.register(O),t(`Registered provider: ${z.id} (${z.type})`)}else t(`Failed to initialize provider: ${M(S.reason)}`)}if(await ZN(o,e,t),s){let _=s.providers.filter(P=>!P.enabled&&!o.has(P.id));if(_.length>0){let P=await Promise.allSettled(_.map(async S=>{let z=mS[S.type];if(!z)return null;let O=z(S);return await O.initialize(),O.isAvailable()?{pc:S,provider:O}:null}));for(let S of P)if(S.status==="fulfilled"&&S.value){let{pc:z,provider:O}=S.value;o.register(O),t(`Re-enabled previously disabled provider: ${z.id} (${z.type})`)}}}if(s){let _=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 Up(),z=qp(S,o,{excludeIds:_,excludeTypes:P});for(let O of z)t(`Registered newly detected provider: ${O.id} (${O.type})`)}catch(S){t(`Supplemental provider detection failed (non-fatal): ${M(S)}`)}}let i=new Map(s?.providers.map(_=>[_.id,_.executionPolicy])??[]),a=new Map(o.getAll().map(_=>[_.id,i.get(_.id)??sr(_.type)])),c=im(s?.locale);t(`Localization active: ${c.locale}`);let u=new Map,l=()=>"unknown",d=async _=>{let P=u.get(_);if(P)return P;let S=new Po(Pc(_,Jp)),z=new Do(Pc(_,fo)),O=new si(_),Z=new ii(_);Z.cleanup(30);let De=new di(Z,{ttlMs:6e4}),Q=new So(_,{providerPolicies:a}),kt=new ao(Pc(_,fo));try{await kt.hydrateFromDisk()}catch(hS){t(`Structured session registry hydrate failed for ${_}: ${M(hS)}`)}let wr=gc(o,l()),js=new co({bridge:wr,documentManager:z,registry:kt,i18n:c,traceWriter:Z}),Ls={sessionManager:S,documentManager:z,jobManager:O,traceWriter:Z,qualityStatsProvider:De,cliWorkerManager:Q,structuredSessionRegistry:kt,moderatorEngine:js};return u.set(_,Ls),Ls},p=await d(e),f={registry:o,...p,providerPolicies:a,workspaceBaseDir:e,resolveWorkspaceServices:async _=>d(_),i18n:c},m=Mp(f),g=Lp(m,s);l=()=>uo(m.getClientVersion()?.name),await Fp(g,o,a,t),f.resolveSessionContext=()=>Zp(g,o);let y=setInterval(()=>{(async()=>{for(let _ of u.values())try{await _.structuredSessionRegistry.sweepTimeouts()}catch(P){t(`Session sweep failed: ${M(P)}`)}})()},af);y.unref?.();let v=!1,x=async()=>{if(!v){v=!0,t("Shutting down..."),clearInterval(y);for(let _ of u.values())_.traceWriter.shutdown();for(let _ of o.getAll())if(_.shutdown)try{await _.shutdown()}catch{}}};process.on("SIGTERM",()=>{x().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{x().finally(()=>process.exit(0))}),process.on("uncaughtException",_=>{for(let P of u.values())P.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${_}
631
- `),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await Np(m),t("MCP server connected via stdio.")}var qN=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=FN(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();qN&&UN().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
632
- `),process.exit(1)});export{ZN as autoDetectIfNeeded,eS as collectTools,Np as connectStdio,Sc as createClaudeLeaderBridge,$c as createCodexLeaderBridge,kc as createGeminiLeaderBridge,Lp as createRuntimeHostAdapter,Mp as createServer,nS as dispatch,uo as inferHostKindFromClientName,Fp as registerHostBackedProviders,Zp as resolveSessionContext,rS as truncateResponse};
640
+ `).trim():pS(t)?t.text:""}function fS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function mS(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function lo(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function Bp(t,e,r){let n=()=>lo(t.getClientVersion()?.name);return{providerId:e,isAvailable(){return!!t.getClientCapabilities()?.sampling&&n()===r.expectedHostKind},async healthCheck(){if(!t.getClientCapabilities()?.sampling)return{status:"error",message:"Client does not support MCP sampling"};let o=n();return o!==r.expectedHostKind?{status:"error",message:`${r.displayName} host bridge requires a ${r.displayName} host, got ${o}`}:{status:"ok",message:`${r.displayName} host bridge available via ${t.getClientVersion()?.name??"unknown client"}`}},async runTurn(o){if(!this.isAvailable())throw new Error(r.unavailableMessage);let s=await t.createMessage({messages:[{role:"user",content:{type:"text",text:o.prompt}}],systemPrompt:o.system,includeContext:"none",maxTokens:fS(o.metadata,"maxTokens")??4096,temperature:fS(o.metadata,"temperature"),modelPreferences:mS(o.metadata,"model")?{hints:[{name:mS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=rN(s.content);if(!i)throw new Error("Claude host bridge returned no text content");return{text:i,metadata:{model:s.model,stopReason:s.stopReason,hostKind:n()}}}}}function Pc(t,e="claude"){return Bp(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Tc(t,e="codex-host"){return Bp(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Ec(t,e="gemini-host"){return Bp(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var nN=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new hi({id:e,bridge:Pc(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new gi({id:e,bridge:Tc(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new yi({id:e,bridge:Ec(t,e)})}];function po(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function oN(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function sN(t,e){switch(t){case"claude-code":return po(e,"claude-host","claude");case"codex-cli":return po(e,"codex-host","codex-host");case"gemini-cli":return po(e,"gemini-host","gemini-host");default:return}}function iN(t,e){return t.some(o=>o.roles.includes("worker")&&o.supportsAutonomousExecution)?"team":t.some(o=>o.id!==e&&o.supportsReadOnlyChat)&&t.length>1?"debate":"claude-only"}function Wp(t,e){let r=()=>lo(t.getClientVersion()?.name),n=()=>oN(r()),o=()=>sN(r(),e);return{get id(){return r()},get kind(){return r()},get leaderProviderId(){return o()},get leaderProviderType(){return n()},get supportsHooks(){return r()==="claude-code"},get supportsInteractiveChoices(){return r()!=="unknown"},get supportsSampling(){return!!t.getClientCapabilities()?.sampling},createLeaderBridge(){switch(r()){case"claude-code":{let s=po(e,"claude-host","claude");return Pc(t,s)}case"codex-cli":{let s=po(e,"codex-host","codex-host");return Tc(t,s)}case"gemini-cli":{let s=po(e,"gemini-host","gemini-host");return Ec(t,s)}default:return null}},createHostProviders(){let s=r();return nN.flatMap(i=>{if(s==="unknown"||!i.supportedHosts.includes(s))return[];let a=e?.providers.find(u=>u.type===i.type||u.id===i.defaultId);if(a?.enabled===!1)return[];let c=a?.id??i.defaultId;return[{id:c,type:i.type,executionPolicy:a?.executionPolicy??Vt(i.type),provider:i.createProvider(t,c)}]})},createSessionContext(s){let i=s.filter(u=>u.supportsReadOnlyChat);if(i.length===0)return;let a=o(),c=(a?i.find(u=>u.id===a):void 0)??(n()?i.find(u=>u.type===n()):void 0)??i.find(u=>u.roles.includes("leader"))??i[0];return{hostId:r(),hostKind:r(),leaderProviderId:c.id,participantProviderIds:i.map(u=>u.id),executionMode:iN(i,c.id)}}}}async function Hp(t,e,r,n){let o=t.createHostProviders();for(let s of o)e.has(s.id)||(await s.provider.initialize(),e.register(s.provider),r.set(s.id,s.executionPolicy),n(`Registered provider: ${s.id} (${s.type})`))}function Kp(t,e){let r=typeof e.getAvailableDescriptors=="function"?e.getAvailableDescriptors():e.getAvailable().map(n=>typeof e.getDescriptor=="function"?e.getDescriptor(n.id):{id:n.id,type:n.type,invocation:"unknown",roles:["participant"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0,supportsToolUse:n.getCapabilities().supportsToolUse});return t.createSessionContext?.(r)}import{existsSync as hS}from"fs";import{dirname as vS,join as gS,resolve as _S}from"path";import{fileURLToPath as aN}from"url";function cN(t){return hS(gS(t,"package.json"))&&hS(gS(t,"AGENTS.md"))}function yS(t){let e=_S(t);for(;;){if(cN(e))return e;let r=vS(e);if(r===e)return null;e=r}}function uN(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return _S(t);let e=vS(aN(import.meta.url));return yS(process.cwd())??yS(e)??process.cwd()}function bS(){let t=uN();return process.cwd()!==t&&process.chdir(t),t}var wS={ollama:t=>new qr({id:t.id,host:t.config?.host||fo}),"gemini-cli":t=>new Vr({id:t.id,timeout:t.config?.timeout}),"codex-cli":t=>new Br({id:t.id,timeout:t.config?.timeout}),"claude-cli":t=>new Wr({id:t.id,timeout:t.config?.timeout})};async function pN(t,e,r){if(t.getAll().length>0)return r("Providers already registered, skipping auto-detect."),{detected:0};r("No providers found \u2014 running auto-detect...");try{let{results:n,providers:o}=await uo(),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(Vx(o,t),r(`Auto-detected ${s.length} provider(s): ${s.map(i=>i.id).join(", ")}`),{detected:s.length})}catch(n){return r(`Auto-detect failed (non-fatal): ${M(n)}`),{detected:0}}}async function fN(){let t=v=>process.stderr.write(`[mcp-server] ${v}
641
+ `),e=bS(),r=Rc(e,"providers.config.json"),n;try{let v=lN(r,"utf-8");n=JSON.parse(v)}catch(v){t(`Warning: Could not load ${r}: ${M(v)}`),t("Starting with empty provider registry."),n=null}let o=new Ks,s=null;if(n)try{s=Ef(n)}catch(v){t(`Warning: Invalid provider config in ${r}: ${M(v)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}if(s){let v=s.enabledProviders.map(x=>{let z=wS[x.type];if(!z)return t(`Unknown provider type: ${x.type} (id: ${x.id}), skipping`),null;let O=z(x);return{pc:x,provider:O}}).filter(x=>x!==null),k=await Promise.allSettled(v.map(async({pc:x,provider:z})=>(await z.initialize(),{pc:x,provider:z})));for(let x of k)if(x.status==="fulfilled"){let{pc:z,provider:O}=x.value;o.register(O),t(`Registered provider: ${z.id} (${z.type})`)}else t(`Failed to initialize provider: ${M(x.reason)}`)}if(await pN(o,e,t),s){let v=s.providers.filter(k=>!k.enabled&&!o.has(k.id));if(v.length>0){let k=await Promise.allSettled(v.map(async x=>{let z=wS[x.type];if(!z)return null;let O=z(x);return await O.initialize(),O.isAvailable()?{pc:x,provider:O}:null}));for(let x of k)if(x.status==="fulfilled"&&x.value){let{pc:z,provider:O}=x.value;o.register(O),t(`Re-enabled previously disabled provider: ${z.id} (${z.type})`)}}}if(s){let v=new Set(s.providers.filter(x=>!x.enabled).map(x=>x.id)),k=new Set(s.providers.filter(x=>!x.enabled).map(x=>x.type));try{let{providers:x}=await uo(),z=Dp(x,o,{excludeIds:v,excludeTypes:k});for(let O of z)t(`Registered newly detected provider: ${O.id} (${O.type})`)}catch(x){t(`Supplemental provider detection failed (non-fatal): ${M(x)}`)}}let i=new Map(s?.providers.map(v=>[v.id,v.executionPolicy])??[]),a=new Map(o.getAll().map(v=>[v.id,i.get(v.id)??Vt(v.type)])),c=dm(s?.locale);t(`Localization active: ${c.locale}`);let u=new Map,l=()=>"unknown",d=async v=>{let k=u.get(v);if(k)return k;let x=new To(Rc(v,tf)),z=new zo(Rc(v,mo)),O=new ii(v),Z=new ai(v);Z.cleanup(30);let De=new pi(Z,{ttlMs:6e4}),Y=new $o(v,{providerPolicies:a}),kt=new ao(Rc(v,mo));try{await kt.hydrateFromDisk()}catch(xS){t(`Structured session registry hydrate failed for ${v}: ${M(xS)}`)}let wr=_c(o,l()),Ls=new co({bridge:wr,documentManager:z,registry:kt,i18n:c,traceWriter:Z}),Fs={sessionManager:x,documentManager:z,jobManager:O,traceWriter:Z,qualityStatsProvider:De,cliWorkerManager:Y,structuredSessionRegistry:kt,moderatorEngine:Ls};return u.set(v,Fs),Fs},p=await d(e),f={registry:o,...p,providerPolicies:a,workspaceBaseDir:e,resolveWorkspaceServices:async v=>d(v),i18n:c},m=qp(f),g=Wp(m,s);l=()=>lo(m.getClientVersion()?.name),await Hp(g,o,a,t),f.resolveSessionContext=()=>Kp(g,o);let y=setInterval(()=>{(async()=>{for(let v of u.values())try{let k=await v.structuredSessionRegistry.sweepTimeouts();k.length>0&&await v.moderatorEngine.handleTimedOutSnapshots(k)}catch(k){t(`Session sweep failed: ${M(k)}`)}})()},pf);y.unref?.();let _=!1,S=async()=>{if(!_){_=!0,t("Shutting down..."),clearInterval(y);for(let v of u.values())v.traceWriter.shutdown();for(let v of o.getAll())if(v.shutdown)try{await v.shutdown()}catch{}}};process.on("SIGTERM",()=>{S().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{S().finally(()=>process.exit(0))}),process.on("uncaughtException",v=>{for(let k of u.values())k.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${v}
642
+ `),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await Vp(m),t("MCP server connected via stdio.")}var mN=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=dN(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();mN&&fN().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
643
+ `),process.exit(1)});export{pN as autoDetectIfNeeded,cS as collectTools,Vp as connectStdio,Pc as createClaudeLeaderBridge,Tc as createCodexLeaderBridge,Ec as createGeminiLeaderBridge,Wp as createRuntimeHostAdapter,qp as createServer,dS as dispatch,lo as inferHostKindFromClientName,Hp as registerHostBackedProviders,Kp as resolveSessionContext,lS as truncateResponse};
633
644
  //# sourceMappingURL=bundle.js.map